12-04 更新 实时
首页/ 技术栈/ 正文

Cloudflare 的 DNS 探测实践

技术栈 来源:Cloudflare Blog 2026-11-23 22:00 3 阅读 机器翻译
Cloudflare 的 DNS 探测实践

想象一下:你刚刚推送了一个发布。所有单元测试都通过了,仪表盘一片绿色。你往后一靠准备放松,但突然手机开始响个不停:生产环境出故障了。

这是 Cloudflare DNS 团队亲身经历过的事情。在一次将 DNS 记录发布到我们边缘网络的服务上线中,一个调度 bug 导致部分记录变更数小时未能发布。服务保持运行且状态健康,但新主机名的解析很慢,并且在 bug 被修复之前证书无法签发。

DNS 故障很难被发现,因为它们发生得缓慢、分布在整个网络中,而且造成影响的范围是局部的。我们需要找到一种方法来按照客户体验 DNS 的方式测试 DNS:持续进行、从每个数据中心发起,并且针对生产环境。

对我们来说,答案就是扩展 Flamingo,这是我们已经在用来每天针对 Cloudflare 边缘网络运行数亿次测试的端到端测试框架。这篇文章将介绍 Flamingo 的模块化设计如何让我们添加 DNS 支持,我们如何测量传播,以及这些测量结果现在如何决定一次发布是继续推进还是回滚。

在 Cloudflare,我们致力于为客户提升性能和安全性。我们的代码必须持续接受测试,既要大规模测试,也要针对用户实际使用的真实 Cloudflare 边缘网络进行测试,这一点至关重要。这也是我们创建名为 Flamingo 的工具的原因之一:衡量生产环境的行为,并确保较低层级环境中的代码按预期运行。

我们此前已经简单介绍过这个工具如何被用于我们的 CDN 技术栈升级。不过,这只是我们在内部使用 Flamingo 的一小部分场景。Flamingo 的特性之一是它的模块化架构,让各团队能够扩展该工具的能力,使其支持其他网络协议。在我们的场景中,我们希望利用这些模块化能力来测试 DNS。

测试很难。而当面对一个广泛分布的系统时,大规模测试更是难上加难。请求会经过许多复杂的路径,每个网络请求在抵达源站之前都必须穿越多个系统。仅靠单元测试远远不够。我们需要对真实系统持续运行自动化测试,并衡量这些请求的结果,从而对服务的健康状况做出有依据的判断。

于是 Flamingo 登场。它最初是围绕复杂的多步骤 HTTP 测试构建的,多年来其能力和适用范围已大幅扩展。Flamingo 从设计之初就以 Cloudflare 的基础设施为考量。我们构建了一个控制平面和调度器,让各团队能够将目标对准特定环境、数据中心或一定比例的 metal 服务器。我们需要与自定义报表、指标和分析工具集成。此外,它还必须是一个性能可预测的工具,并能在资源受限的环境中于裸金属服务器上良好运行。

在构建这样的内部工具时,我们力求打造令人愉悦的开发者体验。内部工具应尽可能易于使用,但也要足够强大,能够处理超过 80% 的所有用例。而为了让一个新的边缘验收测试框架取得成功,它的构建方式必须迫使团队遵循通用准则,并在一个稳定、可扩展且能管理复杂性的环境中构建可复用的脚本。

有一件事并不令人愉悦,那就是调试测试。如果你允许用户用传统编程语言编写测试,那么当他们的测试失败时,他们既需要调试被测试的上游系统,也需要调试测试本身。这就是我们构建 Flamingo 时让它使用一种自定义的领域特定语言(DSL)的原因,这种语言由简单的 setup-request-response 格式组成。

例如,假设我们想确保将所有未加密流量重定向到其加密版本。

TEST test-redirect SET $hostname www.cloudflare.com GET "http://$(hostname)/" ASSERT STATUS IS 301 ASSERT HEADER Location IS "https://$(hostname)/" 在这里我们可以看到 DSL 的强大之处。用五行代码,我们就有了一个脚本,它可以在 Cloudflare 边缘的任何地方运行,并可扩展到每分钟数千个请求。我们可以把由此产生的数百万个数据点所产生的数据,转化为一张图表,用来描绘我们的服务在现实世界中的实际表现。

沿用上文的 setup-request-response 测试格式并稍作调整,我们就能让 Flamingo 不只用于 HTTP 测试。中间步骤不再是一个请求,我们现在可以把它看作一个动作。现在,我们已经把系统从发出 HTTP 请求的东西,变成了能够执行任何我们想要衡量其结果的动作的东西。

在 Flamingo 中,我们把这些称为模块,并投入了巨大精力让任何人都能尽可能轻松地编写它们。Flamingo 用 Rust 编写,因为 Rust 具有一致的性能特征和强大的类型系统。类型系统尤其适合这种模块化设计,它允许我们在 Flamingo 动作运行器中使用强类型枚举来表示输入和输出:

pub enum Action { Query { method: String, url: Expression, parameters: Vec<http::QueryParameters>, }, DnsQuery { query_name: Expression, query_type: Expression, parameters: Vec<dns::DnsQueryParameters>, }, } pub enum ActionOutput { Http(http::FetchResponse), Dns(dns::QueryResponse), } pub type ActionHandlerFunction = Arc< dyn Fn( Action, Arc<Ctx>, InterpreterConfig, ) -> BoxFuture<'static, Result<ActionOutput>> + Send + Sync + 'static, >; pub type ActionHandlerLUT = Arc< dyn Fn(&Action) -> ActionHandlerFunction + Send + Sync + 'static, >;我们在这里所做的是,将执行一个动作(在这个例子中是 HTTP 请求)的逻辑解耦为一个动态分发的函数,之后我们可以独立于其他动作来调用它。这样一来,测试调度和资源管理之类的事情就留作更高层的操作,实现模块的人不必操心。模块作者只需要专注于逻辑即可。

pub async fn query( action: Action, ctx: Arc<Ctx>, cfg: InterpreterConfig, ) -> Result<ActionOutput> { let Action::Query { method, url, parameters, } = action else { bail!("Invalid action for module-http::query: {action:?}"); }; ... } pub async fn execute_module<F>( ctx: Arc<Ctx>, cfg: &InterpreterConfig, handler_lut: F, ) -> Result<ActionOutput> where F: (Fn(&Action) -> ActionHandlerFunction), { let func = handler_lut(action); let action_out = (func)(action.clone(), ctx.clone(), cfg.clone()).await?; ... }使用 Flamingo 探测 DNS 俗话说,问题出现时,总是 DNS 的锅。和许多笑话一样,这背后总有一点道理。DNS 是互联网极其重要的一部分,由于它依赖一个由相互连接的真相来源构成的复杂网络,因此一步走错就很容易引发一连串故障。

DNS 由于其分层特性,可能是一个特别难以伺候的系统。例如,当你更改某个 Cloudflare 区域的 DNS 记录时,该记录需要传播到权威服务器,以便更新后的记录能够被广泛获取。为了降低延迟,记录会被存储在物理位置更近的缓存中。这些记录带有生存时间(TTL),它告诉本地 DNS 缓存需要过多久就要从权威服务器重新获取该记录。任何延迟都会影响证书签发和流量故障转移等对时间敏感的操作。

我们之前已经提到,我们构建 Flamingo 时就考虑到了可扩展性。如今投入使用的首批模块中,影响最大的一个正是专门为这个用例构建的。我们的团队得以添加代码来扩展 Flamingo,使其不再发送 HTTP 请求,而是发送 DNS 查询。这样一来,其他一切都无需额外付出。DNS 团队不必操心去管理一个新的探测服务,也不必与我们的报表流水线做集成。一切就这么顺畅运行了。

为了探测 DNS,我们测量客户记录变更传播到权威名称服务器和公共解析器(1.1.1.1)的速度。该测试持续用一个时间戳更新一条 TXT 记录,并从每个数据中心查询三个权威名称服务器 IP 和 1.1.1.1,断言其新鲜度在 90 秒(权威服务器)和 600 秒(解析器)以内。

原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(Probing DNS at Cloudflare)

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<http::QueryParameters>,
  },
  DnsQuery {
    query_name: Expression,
    query_type: Expression,
    parameters: Vec<dns::DnsQueryParameters>,
  },
}

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

pub type ActionHandlerFunction = Arc<
  dyn Fn(
      Action,
      Arc<Ctx>,
      InterpreterConfig,
    )
      -> BoxFuture<'static, Result<ActionOutput>>
    + 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<Ctx>,
  cfg: InterpreterConfig,
) -> Result<ActionOutput> {
  let Action::Query {
    method,
    url,
    parameters,
  } = action
  else {
    bail!("Invalid action for module-http::query: {action:?}");
  };
  ...
}

pub async fn execute_module<F>(
  ctx: Arc<Ctx>,
  cfg: &InterpreterConfig,
  handler_lut: F,
) -> Result<ActionOutput>
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.

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.

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.

正文保留英文原文,标题与摘要由机器翻译。

本文由采集器自动同步

原文发布于 Cloudflare Blog(Probing DNS at Cloudflare),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗