CloudSecurity

Probing DNS at Cloudflare | Cloudflare Blog


Imagine this: you’ve just pushed a release. All the unit tests passed and your dashboards are green. You sit back to relax but then suddenly your phone starts blowing up: prod is broken.

This is something the Cloudflare DNS team has experienced firsthand. In one rollout of the service that publishes DNS records to our edge, a scheduling bug let some record changes sit unpublished for hours. The service stayed up and was healthy, but new hostnames were slow to resolve and certificates couldn’t be issued until the bug was squashed.

DNS failures are hard to catch because they are slow, spread across the network, and partial in where they cause impact. We needed to figure out a way to test DNS the way customers experience it: constantly, from every data center, and against production.

For us, the answer was to extend Flamingo, the end-to-end testing framework we were already using to run hundreds of millions of tests a day against Cloudflare’s edge. This post covers how Flamingo’s modular design lets us add DNS support, how we measure propagation, and how those measurements now decide whether a release goes ahead or gets rolled back.

A little background

At Cloudflare we’re obsessed with improving performance and safety for our customers. It’s crucial that our code is tested constantly, both at scale and against the real Cloudflare edge that our users operate in. That’s one reason why we created a tool called Flamingo: to measure the behavior of our production environments and make sure that code in lower-tier environments behaves as expected.

We’ve already written a little about how this tool has been used in the upgrades to our CDN stack. However, this is only a small portion of how we use Flamingo internally. One of the features of Flamingo is its modular architecture that enables teams to extend the capabilities of the tool to speak other networking protocols. In our case, we wanted to use these modular capabilities to test DNS.

What is Flamingo?

Testing is hard. Testing at scale, when you have a widely distributed system, is even harder. There are many complex pathways that requests take and multiple systems that each network request must traverse before making its way to the origin. Unit testing alone is not nearly enough for this. We need to run constant automated testing against real systems and measure the outcomes of those requests to make informed decisions on the health of a service.

Enter Flamingo. Originally built around complex multi-step HTTP testing, its capabilities and scope have increased substantially over the years. Flamingo is built from the ground up with Cloudflare’s infrastructure in mind. We built a control plane and scheduler that let teams target specific environments, data centers, or percentages of metals. We needed to integrate with custom reporting, metrics, and analytics tooling. Additionally, it needed to be a tool with predictable performance and run well on bare-metal servers in resource-constrained environments.

Being delightful

When we’re building internal tooling like this, we strive to create a delightful developer experience. Internal tooling should be as easy as possible to use, but also powerful enough to handle over 80% of all use cases. And in order for a new edge acceptance test framework to be successful, it needs to be built in such a way that it forces teams to follow common guidelines and build reusable scripts in an environment that is stable, scalable, and manages complexity.

One thing that is not delightful is debugging a test. If you allow a user to write tests in a traditional programming language, when their test fails they then both need to debug the upstream system being tested and the test itself. This is why we built Flamingo to use a custom domain-specific language (DSL) consisting of a simple setup-request-response format.

For example, let’s imagine that we want to make sure we are redirecting all unencrypted traffic to its encrypted counterpart.

TEST test-redirect
SET $hostname www.cloudflare.com

GET "http://$(hostname)/"

ASSERT STATUS IS 301
ASSERT HEADER Location IS "https://$(hostname)/"

Here we can see the power of the DSL. In five lines of code, we have a script that can run anywhere on Cloudflare’s edge and scale to thousands of requests per minute. We can take the data produced from the millions of data points generated from this and turn those into a graph defining how our service is actually performing in the real world.

Taking the setup-request-response test format from above and modifying it slightly allows us to use Flamingo for more than just HTTP testing. Instead of the middle step being a request, we can now look at it as an action. Now we’ve changed our system from something that makes HTTP requests into something that can perform any action for which we’d like to measure the outcome.

In Flamingo we call these modules and have put immense effort into making them as easy as possible for anyone to write. Flamingo is written in Rust, due to its consistent performance characteristics and strong type system. The type system in particular lends itself to this modularity, by allowing us to use strongly-typed enumerations for input and output in the Flamingo action runner:

pub enum Action {
  Query {
    method: String,
    url: Expression,
    parameters: Vec<:queryparameters>,
  },
  DnsQuery {
    query_name: Expression,
    query_type: Expression,
    parameters: Vec<:dnsqueryparameters>,
  },
}

pub enum ActionOutput {
  Http(http::FetchResponse),
  Dns(dns::QueryResponse),
}

pub type ActionHandlerFunction = Arc<
  dyn Fn(
      Action,
      Arc,
      InterpreterConfig,
    )
      -> BoxFuture<'static, Result>
    + Send
    + Sync
    + 'static,
>;

pub type ActionHandlerLUT = Arc<
  dyn Fn(&Action) -> ActionHandlerFunction
    + Send
    + Sync
    + 'static,
>;

What we’ve done here is decouple the logic for performing an action (in this case an HTTP request) into a dynamically dispatched function that we can then call independently of other actions. This leaves things like test scheduling and resource management as higher-level operations that someone implementing a module doesn’t need to worry about. All the author needs to focus on is the logic.

pub async fn query(
  action: Action,
  ctx: Arc,
  cfg: InterpreterConfig,
) -> Result {
  let Action::Query {
    method,
    url,
    parameters,
  } = action
  else {
    bail!("Invalid action for module-http::query: {action:?}");
  };
  ...
}

pub async fn execute_module(
  ctx: Arc,
  cfg: &InterpreterConfig,
  handler_lut: F,
) -> Result
where
  F: (Fn(&Action) -> ActionHandlerFunction),
{
  let func = handler_lut(action);
  let action_out = (func)(action.clone(), ctx.clone(), cfg.clone()).await?;
  ...
}

Using Flamingo to probe DNS

The adage says that when issues arise, it’s always DNS. Like many jokes, there is always a kernel of truth behind it. DNS is an incredibly important piece of the Internet, and since it relies on a complex network of interconnected sources of truth, it can become easy for a single misstep to cause a storm of failures.

DNS can be a particularly finicky system due to its hierarchical nature. When you change a DNS record for a Cloudflare zone, for example, said record needs to be propagated to the authoritative servers such that the updated record becomes widely available. To reduce latency, records are stored in physically closer caches. These records have a time to live (TTL) associated with them that tells the local DNS cache how long before it needs to refetch that record from the authoritative server. Any delays will impact time-sensitive operations like certificate issuance and traffic failover.

We’ve already mentioned that we built Flamingo for extensibility. One of the first and most impactful modules in use today was built specifically for this use case. Our team was able to add code that extended Flamingo such that instead of sending HTTP requests, we send DNS queries. By doing so we got everything else for free. No need for the DNS team to worry about managing a new probing service. No need for them to have to integrate with our reporting pipelines. It all just worked.

To probe DNS, we measure how quickly customer record changes propagate to authoritative nameservers and the public resolver (1.1.1.1). The test continuously updates a TXT record with a timestamp and queries three authoritative nameserver IPs and 1.1.1.1 from every data center, asserting freshness within 90s (authoritative) and 600s (resolver).

TEST test-propagation-delay-direct-108-162-193-62
MOD dns

SET $hostname "some.probe.domain"
SET $authNs 108.162.193.62:53 # amir.ns.cloudflare.com

QUERY $hostname TXT
TARGET $authNs

ASSERT DNS.RCODE IS NOERROR
ASSERT DNS.FLAGS CONTAINS AA
ASSERT DNS.ANSWERS[0] GT SUBTRACT(TIMESTAMP(), "90")

Catching bugs (SLO and steady)

To ensure that our many systems are operating within expectations, we define what are called service-level objectives (SLOs) for observing things like availability or latency. SLOs are a percentage of some metric that is used as a target. Additionally, SLOs are measured through service-level indicators (SLIs) which are the actual series of measurements focused on the end-to-end experience that a user has when interacting with a system.

By constantly sending synthetic Flamingo traffic through our production systems, we can begin to then use that information to build a picture of what our actual end users are experiencing — and provide that data for our SLOs. When that synthetic traffic encounters issues then we can be pretty confident that Cloudflare customers are also hitting issues and triage accordingly.

SLI showing DNS probes that successfully completed below the required threshold as a function of time.

Once we have this information, it allows us to make informed decisions when releasing a service. SLOs operate in terms of error budgets and burn rates. An error budget is the percentage of downtime that a service is willing to tolerate while the burn rate is the rate of change in that budget at any given time. This allows for an automated system to understand the severity of an issue. For example, burning 10% of your error budget over a three-day period might be some long running issue that, while not urgent, is affecting customers and needs to be dealt with. But if you were to burn 10% of your error budget within an hour, that means an incident is occurring and customer impact will be substantial if not fixed immediately.

Using these numbers, we can look at our SLOs while deploying and make informed decisions on the health of a service. Based on that information, we can tell our releasing systems to either promote a change or roll it back.

img2

The road ahead

By moving DNS monitoring to Flamingo, we’ve created a system that can proactively detect DNS issues before they have the chance to spread to the rest of Cloudflare’s edge. If Flamingo detects a spike in propagation latency in a specific canary data center, we can automatically halt the rollout of a new software version before it impacts the rest of the Internet.

DNS is just the start for extending Flamingo. We currently have modules for testing TCP, UDP, WebSockets, and several more. Having a tool for quickly testing and monitoring services has enabled teams to deploy large changes safely without the need for a human to keep a constant watch.

If this kind of reliability engineering interests you, check out our careers page for open roles.



Source link