Summary#
Cloudflare sits in front of a large share of the web. Every data center announces the same IP addresses, and every server in a data center runs the same software. Almost every Cloudflare post is about one of two consequences of that design. The first is leverage: one fleet, one code base and one config system can serve DNS, caching, the firewall, DDoS defence, serverless code and storage in hundreds of cities at once. The second is blast radius: a bad regex, a bad route or a bad config file can also reach every city at once. This page reads 55 Cloudflare engineering posts, written between 2011 and 2026, through the four lenses used across this part of the handbook: the assumptions the engineers made, the architecture they built, the constraints that are easy to miss, and what Cloudflare gave up.
The posts fall into seven families: the edge network (anycast, the uniform server, Unimog, Maglev, Traffic Manager), the proxy (Pingora), configuration and storage (Quicksilver, Workers KV, Durable Objects, Queues, Waiting Room), caching and purge, counting and analytics (rate limiting counters, Bloom filters, ClickHouse, Kafka), security and protocols (l4drop, autonomous DDoS defence, HTTP/2 Rapid Reset, SYN handling, Keyless SSL, QUIC and HTTP/3, the 1.1.1.1 resolver, RPKI) and a long series of public outage reports. All Cloudflare facts below come from the fetched posts. Math, analogies and general engineering context are the handbook's own explanation, and invented numbers are marked as the handbook's illustration.
Why It Exists#
Most system design material describes a single region with a load balancer, some app servers and a database. Cloudflare is the opposite shape: hundreds of small and large sites, each serving the same addresses, all controlled by a few global control planes. That shape forces problems that a single-region design never meets:
- The network chooses the data center, not you. With anycast, BGP routing decides which city gets a packet. Cloudflare must make every city able to serve every request, and must cope when routing shifts traffic without warning.
- Attacks are part of normal traffic. A volumetric DDoS of hundreds of millions of packets per second is a routine event, so filtering must be cheap enough to run on every packet before any real work.
- Configuration is a global, real-time system. A customer's firewall rule must reach every server in seconds. The same pipe that ships a fix in seconds ships a mistake in seconds.
- Outages are public and instructive. Cloudflare publishes detailed postmortems, often within a day. They are the best free library of real distributed systems failures.
The textbook pages (CDN, load balancing, DNS, rate limiting) explain each component. Cloudflare's posts show how those components behave when they all run on the same machine, in 300+ cities, under constant attack.
For each post the page asks:
- Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
- Production architecture. What did Cloudflare actually build?
- Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
- Sacrifice. What did Cloudflare give up to get the benefit?
How It Works#
The diagram groups the posts by where they sit on a packet's path. A packet reaches a city by anycast, is filtered and balanced in the kernel, is handled by a proxy that reads globally distributed config, may touch edge storage or the cache, is counted and logged, and is protected by protocol and routing security. The outage reports cut across every layer.
Lesson 1: A brief primer on anycast#
Assumptions. The 2011 post answers a reader question: how can one name server address be a whole cluster of machines in many cities? It assumes most of the internet uses unicast, where every address belongs to one machine and routers forward packets hop by hop along the shortest known path. A traceroute to a unicast origin always ends at the same server, wherever you start. At the time Cloudflare had 12 data centers and answered about 75% of requests from the edge without touching the customer's origin.
Production architecture. With anycast, many machines in many places announce the same IP address. Routers send each packet to the "closest" announcement, where closest means best by BGP routing policy, which usually but not always tracks physical distance. The post's traceroute from Northern California ends in San Jose at about 9.5 ms, while the origin in Dallas was about 50 ms away. The post names three benefits:
- Speed. Users reach a nearby data center, and Cloudflare placed its sites in major interconnection buildings that traffic would have crossed anyway, so even cache misses add little latency.
- Resilience. If a whole data center is taken offline, its routes are withdrawn and traffic flows to the next closest site with no DNS change.
- Attack absorption. A botnet is spread around the world, so each data center receives only the share of attack traffic that originates near it. More data centers means more total capacity to soak up an attack.
The post is honest about the cost: anycast needs your own hardware, direct relationships with upstream carriers, and route tuning so that traffic does not flap (switch back and forth) between locations.
Overlooked constraints.
- Anycast suits stateless or short exchanges best. A DNS query is one packet in each direction, so a route change between queries does no harm. A TCP connection is many packets. If routing shifts mid-connection, the new site has no record of the connection and resets it. Cloudflare's whole edge design (uniform servers, consistent hashing inside a site) exists partly to make anycast safe for TCP.
- "Closest" is a routing decision, not geography. BGP chooses by policy and path length, so a user can land in a distant city because of how their ISP peers. Lessons on Traffic Manager and the outage reports show how much engineering goes into steering this.
- Every site needs the full product. If any packet can land anywhere, every site must be able to serve every customer, which pushes toward the uniform server described in Lesson 2.
What Cloudflare sacrificed. Anycast gives up fine-grained control over where each user goes. A unicast-plus-GeoDNS design can steer individual users, while anycast hands that choice to thousands of other networks' routing policies. Cloudflare also took on the operational cost of owning hardware and running BGP with many carriers, in exchange for latency, failover without DNS changes, and attack absorption that grows with the network.
Deep Dive: why anycast dilutes a botnet, in numbersShow
Attack per site. Suppose a botnet of 200,000 hosts sends a total of 1 Tbps, spread roughly in proportion to internet population. With one unicast site, that site needs more than 1 Tbps of headroom. With anycast across 100 sites, a site serving 3% of the world's users sees about 30 Gbps. The largest site might see 10% (100 Gbps), which a site with several hundred gigabits of capacity can absorb (handbook's illustration).
Failover without DNS. With unicast plus DNS failover, clients keep using cached DNS answers until the TTL expires. A 300 s TTL means up to five minutes of errors for some users, and some resolvers ignore TTLs. With anycast, withdrawing a route converges in BGP within seconds to tens of seconds, and no client-side cache is involved.
Where anycast hurts. If the closest-by-routing site is not the closest-by-latency site, users pay the difference on every request. A user routed 2,000 km away instead of 200 km pays about 18 ms extra round trip (light in fibre travels about 200 km per ms, so 1,800 extra km each way is about 9 ms each way). That is why anycast operators measure real user latency, not just route tables.
Lesson 2: Cloudflare architecture and how BPF eats the world#
Assumptions. The 2019 Netdev talk describes two kinds of data center: large core sites that process logs, analyse attacks and compute analytics, and the edge fleet in about 180 locations at the time. The edge assumes anycast, so every site announces the same addresses, and Cloudflare carries that uniformity inside the site: every server runs every service. The full HTTP stack, Workers, authoritative DNS, the DNS resolver, Spectrum (a TCP/UDP proxy for any port) and WARP (a consumer VPN) all run on all servers. The edge must survive DoS attacks, so the early stages of packet handling must be cheap.
Production architecture. The talk walks a packet through five stages:
- The router uses ECMP (equal-cost multipath routing) to hash each packet to one of at least 16 servers per target IP. This is a crude first spread.
- On the server, an XDP program runs first. XDP (eXpress Data Path) is a Linux hook that runs a small, verified eBPF program on every packet in the network driver, before the kernel allocates its usual packet structures. The first XDP stage drops packets from large layer 3 floods.
- Still in XDP, a layer 4 load balancer redirects the remaining packets to the right server in the site. This fixes ECMP's weaknesses and lets servers leave service gracefully (Lesson 3 covers it).
- The chosen server's normal Linux network stack takes over: iptables firewall, then socket dispatch.
- The application receives the packet. HTTP connections go to a "protocol" server that terminates TLS and speaks HTTP/1, HTTP/2 and QUIC.
The talk lists six layers of BPF on the edge:
| Layer | What it does |
|---|---|
| XDP eBPF | Volumetric DoS drops (l4drop) |
iptables xt_bpf running classic BPF | Application-layer attack matching on packet payloads, with connlimit, hashlimit and ipsets |
SO_ATTACH_BPF socket filter | Per-IP rate limits on one shared UDP socket |
| XDP load balancer | Spreads connections across the site |
| SOCKMAP and TCP-BPF | TCP splicing and per-flow TCP measurements |
ebpf_exporter | Per-application kernel metrics exported to Prometheus |
Several details show the cost of running thousands of addresses on one box:
- UDP flood isolation. An unmitigated UDP flood can overflow a socket's receive buffer, and then good and bad packets are dropped alike, which is fatal for DNS. Cloudflare once ran one UDP socket per IP so a flood on one IP could not starve others. With more than 30,000 DNS IPs that no longer scaled. The modern design runs one UDP socket with an eBPF filter that keeps per-IP packet counts in an eBPF map and rate limits each IP. While building it the team found a bug in the eBPF verifier.
- Concurrency limits in eBPF. Early eBPF had no locks, so race-free token buckets were hard to write. The
bpf_spin_lockhelper, added in early 2019, fixed that. - Socket dispatch. Linux lets a program
bind()to one IP or to all IPs (0.0.0.0). Cloudflare needed several applications to share port 80 or 53, each on its own IP range, so it wrote a kernel patch adding aSO_BINDTOPREFIXsocket option. Spectrum needed all 65,535 ports, and opening that many listening sockets is a bad idea, so it uses the iptables TPROXY module instead. The team wanted to replace both with eBPF-based socket lookup. - Metrics. Kernel counters like
TcpExtListenDropsandTcpExtListenOverflowsare global. Cloudflare needed them per application, so it wroteebpf_exporterto pull the numbers out with eBPF probes.
Overlooked constraints.
- Order matters. Attack filtering must run before load balancing. If the load balancer forwarded attack packets first, every flood packet would cost two servers' work instead of one.
- Uniformity moves complexity into the kernel. Because every server hosts every IP and every service, Cloudflare hit corners of Linux that few others reach: shared ports across IP ranges, 30,000 DNS addresses, all 65,535 ports.
- eBPF is safe but limited. The kernel verifier rejects programs it cannot prove safe, which caps loop and memory patterns. That safety is what lets Cloudflare upgrade filtering logic like any userspace deploy, without recompiling a kernel module.
What Cloudflare sacrificed. The uniform server gives up specialisation. A dedicated DNS box or load-balancer box could be tuned for one job, and its failures would be contained to one role. Cloudflare instead accepted that every server's kernel is a crowded, heavily customised place, and that a bug in a shared layer touches every service. In return it never has to size how many load balancers or DNS boxes each site needs, and any spare server capacity can absorb any workload or attack.
Deep Dive: why drop in XDP and not laterShow
Cost per packet. The handbook's rough figures for a modern core: the full Linux path from driver to a socket costs on the order of a few microseconds per packet, while an XDP drop costs on the order of tens to a hundred nanoseconds, because the packet is discarded before the kernel allocates a socket buffer. At 10 million attack packets per second on one server, 2 µs each needs 20 CPU-seconds per second, which is 20 fully busy cores. At 50 ns each it is 0.5 cores (handbook's illustration).
Per-IP UDP rate limiting. With one socket and an eBPF filter, the state is a map from destination IP to a counter. Each packet does one map lookup and one increment. With 30,000 DNS IPs the map is small (30,000 entries of a few bytes). The old alternative, 30,000 sockets, needs 30,000 receive buffers and 30,000 file descriptors per process, plus a wake-up path per socket.
Why a race-free token bucket needs a lock. A token bucket reads the current tokens, adds refill based on time elapsed, subtracts one, and writes back. Two CPUs doing that read-modify-write at once can both see "1 token left" and both let a packet through. Per-CPU maps avoid the race but split the budget across cores, so a 1,000 pps limit on a 32-core box becomes 32 separate buckets of about 31 pps each, which is unfair when traffic hits one core. bpf_spin_lock allows one shared, correct bucket.
Lesson 3: Unimog, Cloudflare's edge load balancer#
Assumptions. By 2018, spreading load inside a site with router ECMP alone was not good enough. The 2020 post lists the conditions Unimog had to meet:
- Data centers in 200+ cities, the largest with a hundred times more servers than the smallest.
- Any server can serve any connection for any service on any anycast IP.
- Servers come and go for maintenance and failed health checks, and draining must not break existing connections.
- A site mixes up to ten hardware generations, with very different CPU power, so equal connection counts do not mean equal load. Other work on the server also uses CPU.
- Some connections live for days (WebSockets, Spectrum TCP proxying).
- Hundreds of thousands of customer IPv4 addresses must be handled as ranges, not one by one.
- It must integrate with the existing l4drop DDoS system and use the same XDP technology.
Production architecture. Unimog is a layer 4 load balancer (L4LB): it routes packets using only IP and TCP/UDP headers, without reading the payload. That makes it cheap but means it cannot take part in TLS or HTTP. The post compares it with Google's Maglev, Facebook's Katran and GitHub's GLB, and names GLB as the strongest influence.
-
Every server is a load balancer. The usual L4LB layout puts a tier of dedicated balancer boxes between the router and the servers. Unimog runs on every server instead: the router ECMP-hashes a packet to any server, and that server's XDP program forwards it to the right one. This keeps servers uniform and lets l4drop filter attacks before any forwarding happens.
-
Why XDP. The alternatives were kernel bypass such as DPDK (best when the box is dedicated to networking, and the main reason GLB did not fit) or kernel modules such as IPVS (hard to develop and deploy). XDP code deploys like a userspace service, weekly if needed. A Go daemon called xdpd builds the chain of XDP programs (l4drop, Unimog and others), fills their maps (shared key-value tables between userspace and eBPF) from control planes, patches constants into the bytecode before loading so lookups do not cost a helper call, exports metrics to Prometheus, and upgrades without interrupting traffic. The l4drop program is generated on the fly by xdpd from attack detection output. The team co-developed the open-source
cilium/ebpfGo library along the way. Unimog costs under 1% of CPU compared with no load balancing, and the core XDP C code is about 1,000 lines (Katran's is similar, so reuse would not have saved much). -
Encapsulation. Clients connect to a VIP (virtual IP, shared by all servers). Rewriting the VIP to the server's DIP (direct IP) would hide the original address the server needs, so Unimog wraps the whole packet in a new header using GUE (Generic UDP Encapsulation), chosen to reuse GLB's redirector. A 1,500-byte packet becomes 1,536 bytes, so Cloudflare enabled jumbo frames inside its sites.
-
The forwarding table. Each balancer hashes the connection's 4-tuple (source IP, source port, destination IP, destination port) and uses the low N bits of the hash to pick a bucket in a power-of-two array. Each bucket holds a DIP. The control plane builds the table and broadcasts it, so every balancer makes the same choice without talking to the others, and ECMP rehashes at the router no longer matter. There are more than 100 buckets per server, so tens of thousands in a big site, and adjusting a server's share of buckets adjusts its share of new connections. Each trafficset (a service and its VIP ranges) has its own tables.
-
Keeping old connections: Beamer daisy-chaining. Changing a bucket from server A to server B would make B receive packets for A's existing connections, and B would answer with a TCP reset. Following the paper "Stateless Datacenter Load-balancing with Beamer" (Olteanu et al., NSDI 2018), each bucket has two slots: the current DIP and the previous DIP. The balancer sends packets to the first-hop DIP and writes the second-hop DIP into a GUE extension header. A redirector on the receiving server then applies three rules:
- A SYN (new connection) is always handled on the first-hop server.
- A packet that matches a local socket is handled locally.
- Anything else is forwarded to the second-hop server, where its connection probably lives.
Fewer than 1% of forwarded packets take the second hop. Unimog first used GLB's
glb-redirectkernel module, then replaced it with cls-redirect, an eBPF program on the Linux TC (traffic control) layer that also does decapsulation. TC was chosen over XDP because tcpdump can see packets at TC but not before XDP, and the redirector passes most packets through, so XDP's speed did not matter. cls-redirect was contributed to the kernel test suite. -
Load-balancing trick. Swapping a bucket's first and second slots changes only where new connections go and never breaks an established one. Most of Unimog's balancing is done with swaps like this, and when buckets must be reassigned the control plane picks the least recently modified ones.
-
Control plane. A conductor process per site (one active, standbys elected with Consul distributed locks) reads server inventory, node and service health from Consul, load from Prometheus, and IP ranges from internal APIs. It publishes tables through the Consul key-value store, which xdpd watches with blocking queries. The balancing loop compares each server's CPU-based load metric with the site average and moves buckets in proportion to the deviation, so all servers converge on the average.
-
UDP. Request-response UDP such as DNS uses one-slot buckets. UDP flows use daisy-chaining too, but UDP has no SYN, so new flows go to the second-hop server and services must use connected UDP sockets so the redirector can match them. QUIC and WARP carry a session ID, and Unimog supports custom flow dissectors that hash that ID instead of the 4-tuple, so a phone moving from Wi-Fi to cellular keeps its server. Cloudflare extended WireGuard in a backwards-compatible way to carry such an ID for WARP.
Overlooked constraints.
- A misdirected packet is worse than a dropped one. TCP recovers from loss by retransmitting. A packet sent to the wrong server triggers a reset, and the user sees an error. All the two-slot machinery exists because of that asymmetry.
- Two hops cover only one change per bucket. Beamer allows longer chains. Unimog keeps two and relies on careful update order (swaps, least-recently-modified buckets) to preserve multi-day connections. Unimog also skipped Beamer's generation numbers, judging the race between an ECMP rehash and a table update too rare to justify them.
- Feedback loops can trap a site. Soon after launch, an overloaded site marked many servers unhealthy, so Unimog moved new connections to the rest, which then became unhealthy while the first group recovered. The site oscillated even after demand fell. The conductor now tells an isolated sick server apart from a site-wide overload. Restarting a Consul agent can also briefly report false health changes, which the conductor learned to ignore.
- UDP costs more. For TCP, second-hop traffic fades as old connections close. For UDP flows every new flow takes two hops, which is why the TCP case uses SYN detection.
What Cloudflare sacrificed. Unimog gives up per-connection control: a bucket covers many connections, so balance is statistical, not exact. It costs a second hop for a small share of packets and 36 extra bytes per packet, and it requires jumbo frames inside every site. Most of the engineering went into the control plane, which is itself a critical system: a stale or wrong forwarding table can black-hole a whole data center. In return Cloudflare got even CPU use across mixed hardware, graceful drains, and a load balancer that costs under 1% of the CPU it balances.
Deep Dive: bucket counts, balance precision and drain timeShow
Precision from bucket count. With 100 buckets per server, the smallest change Unimog can make to a server's share is one bucket, or 1% of its traffic. In a site of 300 servers with 32,768 buckets (the next power of two above 30,000), each server holds about 109 buckets, and one bucket is about 0.9% of a server's load (handbook's illustration). The post notes that buckets do not hold exactly equal connection counts because hashing is statistical, but the bucket-to-load relationship proved strong enough in practice.
Proportional control. Suppose the site average CPU is 50% and server X runs at 60%. With a gain of k = 0.5, the controller removes about 0.5 × (60 − 50)/60 ≈ 8% of X's buckets, about 9 of 109, by swapping their slots so new connections go elsewhere. Because only new connections move, X's load falls gradually as old connections end, which damps oscillation (handbook's illustration).
Drain time with long connections. If connection lifetimes are heavy-tailed, say 90% end within a minute but 0.1% last more than a day, a draining server still holds some connections for a day. With two slots, a bucket can change only once without risk to those connections, so a second change within that day would break them. Choosing the least-recently-modified buckets maximises the time since each bucket's last change.
Second-hop overhead. If 1% of forwarded packets take a second hop, and forwarding costs under 1% of CPU, the second hops cost roughly 0.01% of site CPU. The overhead that matters is latency, a few extra microseconds inside the site, which is negligible next to internet round trips.
Lesson 4: How the architecture scales to stop the largest attacks#
Assumptions. The 2016 post was written after several legacy DNS and DDoS-mitigation services had public outages under very large botnet attacks. Cloudflare's customers asked whether the same could happen to it. The post's core assumption: attack size will keep growing, because attackers use hacked devices that cost them nothing, so any defence with a hard per-box ceiling will eventually be exceeded.
Production architecture. The post draws an analogy with databases. From the 1980s to the 2000s companies scaled databases by buying a bigger box, until some workloads (Google's index is the post's example) could not fit in any box, and the answer became many cheap servers acting as one system. Legacy DDoS defence was still in the big-box era: clusters of appliances from vendors such as Cisco, Arbor Networks and Radware in a few scrubbing centers. That model has three limits:
- The box is the ceiling. The packets a box can absorb cap what the service can mitigate.
- Few locations mean upstream bottlenecks. In a huge attack, much of the traffic never reaches the scrubbing center because the ISPs in between saturate first.
- It is too expensive to put everywhere. A DNS provider attacked occasionally cannot justify appliances in every site, and a mitigation vendor provisions only a margin above the largest attack it has seen.
Cloudflare's early racks had only a router, a switch and servers. Later the router was often dropped, with switches that hold enough of the routing table for the region. There are no load balancers or scrubbing appliances to become bottlenecks. BGP spreads load across cities and within each site, and every server can answer every type of request, so a large attack is spread across tens of thousands of servers. Capacity grows in small steps: if Frankfurt needs 10% more, it gets 10% more servers rather than a new giant box.
The post also explains the bandwidth economics. Transit is billed monthly at the 95th percentile of the larger of ingress and egress. A cache sends out far more than it takes in, so normal egress is many times ingress. Attacks raise ingress, which stays below egress even in very large attacks, so the attack bandwidth is effectively free. This is why Cloudflare can charge a fixed fee regardless of attack size and protect at-risk sites for free through Project Galileo.
Overlooked constraints.
- Costs, not just capacity, decide an arms race. The attacker's cost per gigabit is close to zero. A defender who pays per gigabit of attack, or buys hardware sized to the largest past attack, loses over time. Cloudflare's model works because attack traffic falls under bandwidth it already pays for.
- The free-bandwidth argument depends on the traffic mix. It holds because the network is mostly egress-heavy caching. A pure security service with no egress-heavy product would pay for every attack gigabit.
- No box means software must do everything. Lessons 2, 3, 28 and 29 show how much kernel engineering it takes to make commodity servers drop packets as efficiently as appliances.
What Cloudflare sacrificed. It gave up the simplicity of buying mitigation as a product and took on building and running its own filtering software on every machine. Every server shares its CPU between customer traffic and attack filtering, so a big enough attack does consume capacity that would otherwise serve users. The post is careful to say every service has limits. The bet is that a distributed network that grows with customer demand also grows its defence for free.
Deep Dive: 95th-percentile billing and why attacks are nearly freeShow
How 95th-percentile billing works. The provider samples traffic every 5 minutes, which is 8,640 samples in a 30-day month. It sorts them, drops the top 5% (432 samples, 36 hours) and bills at the highest remaining sample. Bursts shorter than 36 hours a month in total are not billed at all.
Worked example (handbook's illustration). A site normally sends 400 Gbps out and receives 80 Gbps in, so the bill is based on max(400, 80) = 400 Gbps. A 200 Gbps attack raises ingress to 280 Gbps for a few hours. The billed figure is still the larger value, egress at 400 Gbps, so the attack costs nothing extra. Only an attack that pushed ingress above 400 Gbps, for more than about 36 hours in the month, would raise the bill.
Step-function cost versus linear cost. Say a scrubbing appliance handles 100 Gbps and costs a large fixed sum. A provider that has seen at most 300 Gbps attacks buys 4 boxes. A 450 Gbps attack exceeds them, and the next step is another box, months of lead time away. With commodity servers, each server adds a few Gbps of filtering, so capacity rises with every server added for normal growth.
Lesson 5: High-availability load balancers with Maglev#
Assumptions. This 2020 post is about Cloudflare's backend (core) data centers, not the edge. They host the services behind the dashboard, the APIs and many edge features. Traffic used to pass through several layers of stateful TCP proxies and NATs. Each load balancer kept its own connection table, so whenever the set of balancers changed the router sent some connections to a balancer that had never seen them, and those connections were reset. Maintenance on balancers was risky toil. The goals for the replacement were:
- Preserve the client source IP all the way to the server, without
X-Forwarded-Forheaders or the PROXY protocol. - Support backends spread across many racks and subnets.
- Allow any balancer to be removed at any time with no resets.
- Use common, well-tested Linux features that operators who are not load-balancer experts understand.
- No connection synchronisation between balancers, because that coordination added complexity and failure modes.
- Allow gradual, per-service migration from the old system.
Production architecture.
- BGP and ECMP. Each balancer announces service IPs to the routers over BGP. Routers spread packets across balancers with ECMP. The team made sure the routers hash only the 5-tuple (protocol, source IP and port, destination IP and port), since router hash functions are fixed in firmware and bad inputs give uneven load or break protocol assumptions.
- Stateless balancers with Maglev. Every balancer uses the Maglev consistent-hash scheduler, from Google's paper "Maglev: A Fast and Reliable Software Network Load Balancer" (Eisenbud et al., NSDI 2016). Given the same 5-tuple and the same backend list, every balancer picks the same backend, so it does not matter which balancer a packet hits. Losing a balancer no longer resets connections.
- IPVS plus Foo-over-UDP. Linux's built-in L4 balancer, IPVS, has supported the Maglev scheduler (
mh) since kernel 4.18. Backends sit in other subnets, so packets are encapsulated with Foo-over-UDP (FOU), which adds an outer IP and UDP header. The receiving kernel strips it and processes the inner packet as if it had arrived directly. FOU was chosen over IPIP, GUE and GENEVE as a balance of features and flexibility. Direct server return (servers reply straight to clients, skipping the balancer) falls out of the design, since the server sees the original client address. IPVS cannot emit FOU itself, so the team created FOU tunnel interfaces and used IPVS's direct-routing mode plus the routing table to send packets down the right tunnel. Servers had to disable reverse path filtering on the tunnel interface, because Linux drops packets that arrive on a different interface from the one it would reply on. - MTU. Internet packets are up to 1,500 bytes, so internal MTUs were raised to fit the extra headers. The team underestimated this: every router, switch, bonded interface, VXLAN interface and tunnel had to change, and MTU bugs in switches and the server stack first showed up as problems in other parts of the network.
- Node agent. A Go agent on each balancer syncs with a control plane that tracks where services run, and configures IPVS and routes over netlink (Cloudflare open-sourced its IPVS netlink package). iptables has no API, so the agent computes the ideal rules, stores a hash of each rule and its position as an iptables comment, and reconciles live rules against the ideal set, ignoring unmanaged rules on shared chains.
- Kubernetes. The same system acts as the cloud load balancer for internal Kubernetes clusters: a controller assigns VIPs to
LoadBalancerservices, and traffic goes to cluster nodes for kube-proxy, or straight to pods withexternalTrafficPolicy: Local. Ingress controllers, API gateways and databases in those clusters see real client IPs.
Overlooked constraints.
- Stateless is not the same as instant failover. A planned withdrawal of a BGP session moves traffic smoothly. A sudden crash (kernel panic, power loss) leaves the router sending packets to a dead box until the BGP hold timer expires. BFD (Bidirectional Forwarding Detection) can detect failure in milliseconds, but router support for BFD was limited in an environment full of link aggregation and VXLANs.
- Consistent hashing protects against balancer changes, not backend changes. When the backend list changes, Maglev moves a small share of flows, and those connections reset because there is no connection state to fall back on. Unimog's two-slot buckets (Lesson 3) solve that harder case; Maglev here did not need to, because backend services are more stable than edge servers.
- MTU changes are network-wide projects. A single device left at the old MTU silently drops or fragments large packets, and the symptoms show up far away.
- iptables was a weak point. Its flat rule priorities and lack of an API make it hard to mix automated rules with operator rules, which is why the team planned to move to nftables.
What Cloudflare sacrificed. The design gives up per-connection state, so it cannot pin a connection through a backend change, and it accepts a short outage window when a balancer dies abruptly. It chose IPVS and FOU, older and more conservative than XDP, trading peak performance and flexibility for predictability for operators. It also took on a fleet-wide MTU change that turned out much harder than planned.
Deep Dive: how the Maglev lookup table is builtShow
The goal. Map any 5-tuple hash to one of N backends, so that (1) every backend gets about the same number of slots, and (2) when a backend is added or removed, few slots change owner.
The algorithm (from the Maglev paper). Pick a prime table size M much larger than N, for example 65,537. For each backend i, compute two hashes of its name: offset_i = h1(name) mod M and skip_i = h2(name) mod (M − 1) + 1. Backend i's preference list is the permutation (offset_i + j · skip_i) mod M for j = 0, 1, 2, …, which visits every slot exactly once because M is prime and skip is non-zero. Then backends take turns: each claims its next preferred slot that is still empty, until all M slots are full. A lookup is table[hash(5-tuple) mod M], a single array read.
Balance. Because backends take turns, each ends up with either floor(M/N) or ceil(M/N) slots. With M = 65,537 and N = 100, every backend holds 655 or 656 slots, within 0.2% of perfect.
Disruption. Removing one backend frees its roughly M/N slots, which must move. The rebuild can also shift some other slots, because backends' turn order changes which empty slot each claims. The paper reports disruption close to the minimal M/N with a large M relative to N. That is the trade Maglev makes against classic ring-based consistent hashing: near-perfect balance and O(1) lookup, in exchange for slightly more than minimal movement on changes.
A small example (handbook's illustration). M = 7, backends A and B. A has offset 3, skip 4: preferences 3, 0, 4, 1, 5, 2, 6. B has offset 0, skip 2: preferences 0, 2, 4, 6, 1, 3, 5. A takes 3, B takes 0, A wants 0 (taken) and takes 4, B takes 2, A takes 1, B takes 6, A takes 5. Table: [B, A, B, A, A, A, B]. A holds 4 slots and B holds 3, the best possible split of 7.
Lesson 6: How Cloudflare built Pingora, the proxy that connects it to the internet#
Assumptions. By 2022 Cloudflare's proxy between its network and customers' origin servers ran on NGINX with Lua. This proxy powers the CDN, Workers fetch, Tunnel, Stream, R2 and more. The post's assumptions are about what limited NGINX at Cloudflare's scale:
- Per-worker processes. In NGINX each request is served by one worker process. Load across CPU cores becomes uneven, and a request that does heavy CPU work or blocking I/O slows every other request on that worker.
- Per-worker connection pools. This was the most critical issue. Reusing an open TCP+TLS connection to an origin skips the handshakes and cuts TTFB (time to first byte). But each NGINX worker has its own pool. Adding workers scatters connections across more isolated pools, so the reuse ratio falls as you scale.
- Hard-to-add features. For example, retrying a failed request against a different origin with different headers was not something NGINX allowed.
- Language risk. NGINX is C, which is not memory safe. Lua is safer but slower and untyped, which hurts in complex business logic.
Production architecture. Cloudflare compared three options every quarter for years: fork and deeply change NGINX, move to another proxy such as Envoy (risking the same cycle again), or build from scratch. It finally built Pingora:
- Rust, for C-like performance with memory safety.
- Its own HTTP library, because the internet is full of non-RFC-compliant traffic. The post's example: RFC 9110 defines status codes 100 to 599, but many servers use 599 to 999. A strict third-party library could reasonably refuse such cases.
- Multithreading with work stealing on the Tokio async runtime instead of multiple processes, so that threads share connection pools and an idle thread can take work from a busy one.
- A "life of a request" phase API similar to NGINX/OpenResty (for example a request-filter phase that can modify or reject a request when its headers arrive), so business logic stays separate from generic proxy logic and NGINX engineers can switch easily.
Results reported in the post:
| Metric | Result |
|---|---|
| Scale | Over 1 trillion requests a day |
| Median TTFB | 5 ms lower |
| p95 TTFB | 80 ms lower |
| New connections per second | One third of the old service |
| One major customer's reuse ratio | 87.1% to 99.92%, 160 times fewer new origin connections |
| Handshake time saved | 434 years per day across users |
| CPU and memory | About 70% less CPU and 67% less memory for the same traffic |
| Crashes from service code | None in a few hundred trillion requests |
The speedup is not from running code faster; the old service already handled requests in under a millisecond. It comes from connection reuse. The CPU saving comes from three things: Rust instead of Lua, no copying of headers from C structs into garbage-collected Lua strings, and shared data behind atomic reference counts instead of NGINX shared memory, which needed a mutex on every access and could hold only strings and numbers. New capability followed: HTTP/2 to origins (and therefore gRPC) and Cache Reserve, which uses R2 as a cache layer. Pingora crashes became so rare that the ones seen were traced to a kernel bug and to faulty hardware.
Load balancer or reverse proxy? The handbook's primer sources draw the line this way. A reverse proxy is a server that sits in front of other servers and gives the public one interface. It is useful even with a single backend: it hides backend details, can block IPs and limit connections per client, lets you change backends without clients noticing, terminates TLS so backends do not need certificates or spend CPU on encryption, compresses responses, caches and serves static files. A load balancer is useful when you have several servers doing the same job, and spreads requests across them. Tools such as NGINX and HAProxy do both. The costs of a reverse proxy are extra complexity, and a single proxy is a single point of failure, while running several for failover adds more complexity. Cloudflare's stack shows the split cleanly: Unimog (Lesson 3) is a pure L4 load balancer that never reads the payload, and Pingora is an L7 reverse proxy that terminates protocols, pools origin connections, caches and runs business logic. The single-point-of-failure risk is handled by running Pingora on every server behind Unimog. See proxies and reverse proxies for the general treatment.
Overlooked constraints.
- Scaling out workers can make latency worse. Splitting a connection pool into P private pools divides the chance of finding a warm connection. This is a general lesson for any pooled resource (database connections, HTTP clients) in a multi-process server.
- Strict standards compliance can be the wrong goal for a proxy. A proxy in front of millions of origins must accept odd but working behaviour, or it breaks customer sites that worked before.
- Rewriting is a recurring decision, not a one-time one. Cloudflare re-evaluated every quarter and stayed with NGINX for years because the cost of leaving was high. The post says Pingora is not the last rewrite.
What Cloudflare sacrificed. It gave up a mature, widely known open-source base and its ecosystem, and took on owning an HTTP library and proxy framework that must handle every strange client and server on the internet. The upfront engineering cost was the highest of the three options. In return it got shared pools, memory safety and a platform it controls, and later open-sourced Pingora's libraries.
Deep Dive: why shared pools raise reuse, with numbersShow
A simple model (handbook's illustration). Suppose a server keeps up to k idle connections to an origin and requests for that origin arrive at rate λ. With one shared pool, a request finds an idle connection whenever any recent request left one. With P private pools, each pool sees only λ/P of the traffic, so idle connections time out before the next request on that worker arrives.
Take an origin that receives 10 requests per second on one server, with an idle timeout of 1 s. One shared pool sees a request every 100 ms on average, so a connection almost never sits idle for a full second: reuse is close to 100%. With 32 workers, each worker sees a request every 3.2 s on average. Most requests arrive after the previous connection on that worker has timed out, so most need a new handshake.
What a handshake costs. A new TCP plus TLS 1.3 connection costs at least 2 round trips before the first byte of the request can be sent (1 for TCP, 1 for TLS). To an origin 40 ms away that is about 80 ms, which lines up with the post's 80 ms p95 improvement. The median improves less (5 ms) because most requests were already reused or go to nearby origins.
Checking 434 years a day. 434 years is about 434 × 365 × 86,400 ≈ 1.37 × 10^10 seconds per day. If each avoided handshake saves about 50 ms, that is about 2.7 × 10^11 avoided handshakes per day, roughly a quarter of 1 trillion requests. That is consistent with the post's figure of a third as many new connections (handbook's back-of-envelope check, not a Cloudflare figure).
Lesson 7: How Pingora keeps count#
Assumptions. The pingora-limits library counts in-flight events and estimates event rates, for example to spot an origin that has become slow, where requests pile up and threaten both Cloudflare's servers and the customer's. The abstract problem is: given an endless stream of event types, report how often a given type has appeared. Two facts make the obvious hash table a poor fit:
- Pingora sees traffic to millions of origins, but only a few misbehave at any time. Storing a counter for every key wastes memory.
- Inserting new keys into a shared hash table needs a lock, and under heavy contention that lock serialises the whole proxy. The library runs on tens of thousands of machines handling more than 20 million requests per second.
Production architecture. pingora-limits uses a count-min sketch, introduced in "An Improved Data Stream Summary: The Count-Min Sketch and its Applications" (Cormode and Muthukrishnan, 2005). It is a matrix of H rows and N counters per row, each row with its own hash function. To count an event, hash it once per row and increment one counter in each row. To read a count, take the minimum of the event's H counters. Collisions only ever add to a counter, so the sketch never underestimates, and taking the minimum picks the least-polluted counter. Two keys collide in every row with probability 1/N^H. Because the work is only hashing, indexing and an atomic increment, the Rust implementation is lock-free: each row's counter is an AtomicIsize updated with fetch_add and relaxed ordering.
The benchmark used 1 million keys and 100 million uniformly distributed events:
| pingora-limits | Mutex<HashMap> | DashMap with atomics | |
|---|---|---|---|
| Single thread, per event | 10 ns | 51 ns | 43 ns |
| Eight threads, per event | 212 ns | 1,505 ns | 212 ns |
| Peak memory | 26,184 bytes | 53,477,392 bytes | 36,211,208 bytes |
The sketch is 5 times faster than the locked map on one thread and uses about 1/2,000 of its memory. With eight threads it matches the sharded DashMap, because both hot paths are just an atomic add. The post suggests a two-stage design where exact counts are required: use the sketch as a cheap first filter and send only keys above a threshold to an exact hash table.
In production it drives the origin connection limit. Each request increments a counter keyed by customer ID, server IP and hostname, and decrements it when done. Above a threshold, new requests get 503 responses, protecting the origin and Cloudflare. The parameters give a theoretical chance of about 1 in 2^52 that two unrelated customers collide, and the threshold is far above healthy traffic, so a false rejection is very unlikely.
Overlooked constraints.
- Bias direction matters. A count-min sketch only overestimates. That is safe for "protect the origin" (a false positive means an occasional unneeded 503) but unsafe for billing or quotas a customer pays for, where an overcount is a wrong charge.
- In-flight counting needs decrements. The connection limit adds on start and subtracts on finish. A request path that forgets the decrement (a panic, an early return) leaks a count forever. In Rust a guard object that decrements on drop handles this.
- The threshold must sit far above normal use. The 1-in-2^52 collision figure is only half of the safety story. The other half is choosing a limit that healthy traffic never approaches, so a collision would still not trigger rejection.
What Cloudflare sacrificed. Exactness. The sketch cannot list which keys are hot (it answers "how many for this key?", not "which keys are big?") and it can overcount. In return it uses kilobytes instead of tens of megabytes and never takes a lock on the request path.
Deep Dive: sizing a count-min sketchShow
The error bound. With width w = ⌈e/ε⌉ and depth d = ⌈ln(1/δ)⌉, the estimate for any key is at most its true count plus ε·T, with probability at least 1 − δ, where T is the total of all counts in the sketch. This is the bound from the Cormode and Muthukrishnan paper.
Worked example (handbook's illustration). A server has about T = 50,000 requests in flight across all origins at once. We want the error to be at most 50 in-flight requests (ε·T = 50, so ε = 0.001) with failure probability δ = 10^-6. Then w = ⌈2.718 / 0.001⌉ = 2,719 columns and d = ⌈ln(10^6)⌉ = 14 rows: about 38,000 counters, or 304 KB with 8-byte counters. If the connection limit is 10,000 in flight per origin, an overestimate of 50 is irrelevant.
Why "collision in every row" is so rare. For two specific keys, the chance they share a column in one row is 1/N. Independent hashes make the chance they share all H rows 1/N^H. With N = 2^13 = 8,192 and H = 4, that is 2^-52, the same order as the figure quoted in the post (the post does not state its exact parameters).
The two-stage filter. If 99.9% of keys are cold, a sketch in front of an exact map means the map holds only about 0.1% of keys. With 1 million keys that is 1,000 map entries instead of 1 million, and the sketch uses kilobytes. Every hot key still gets an exact count.
Lesson 8: Traffic Manager, routing traffic across the globe#
Assumptions. The 2023 post starts from an airport security analogy: when some checkpoints slow down, travellers are sent to another one a little farther away. Cloudflare had over 300 cities and 12,500 peering sessions. Sites sometimes lose capacity through maintenance, a failed link or failed equipment. Before Traffic Manager, an overloaded site returned 499 and 500 errors until a network engineer was paged and withdrew anycast routes for that site by hand, then put them back when it recovered. That did not scale, and users suffered while the human diagnosed the problem.
Production architecture. Traffic Manager automates the move in four parts.
- Traffic Predictor. Anycast lets Cloudflare choose which sites announce a prefix, but not what share of traffic each site gets. To know where traffic goes when a site disappears, Traffic Predictor runs real experiments. For a site such as Christchurch, it pings hundreds of thousands of IPs that recently connected there, using a special anycast range reserved for these tests, and records which replies come back to Christchurch. It then withdraws only that test range from Christchurch, waits a few minutes for routing to settle, and pings again. Where the replies now land is Christchurch's real failover map: about 99.8% to Auckland, which could absorb it all. It also computes second-order scenarios in which several neighbouring sites fail together. Computing all failure paths takes several days. With these maps, Traffic Manager can pre-emptively move traffic out of the failover site too, so a failure does not cause a thundering herd that knocks over the neighbour.
- From sledgehammer to scalpel: Plurimog and Duomog. Withdrawing a prefix is coarse. Many networks filter routes more specific than a /24 (256 addresses) to prevent leaks and hijacks, and Cloudflare maps hundreds of thousands of sites to a single IP, so one /24 might carry 3,000 requests per second. To move 1,000 rps you had to move all 3,000. Moving more traffic than needed is called stranding capacity. Plurimog extends Unimog (Lesson 3) between sites: a site that cannot serve a connection forwards it at layer 4, for example from Philadelphia to Ashburn, where it is decrypted and processed. Because it works per connection, it can move any percentage. Large sites, called multi-colo points of presence (MCPs), are split into independent sections of compute. Duomog moves traffic between sections in one site. When one of Ashburn's nine sections, IAD02, lost capacity on 28 August 2023, Duomog shifted its traffic to the other sections and back with no user impact.
- Measuring in CPU time, not requests. A cached site with the WAF off is far cheaper than an uncached site with every WAF rule on, so requests per second is a poor unit. Cloudflare records CPU time per request and sums it per plan (Free, Pro, Business, Enterprise) in milliseconds per second. The customer-facing signal is cfcheck latency, the time for a request to pass through the front-line servers, and its p95 tracks CPU utilisation closely.
- Three thresholds per site. Maximum is where performance starts to degrade and Traffic Manager acts. Target is the level it tries to bring the site back to. Acceptable is the level below which a site can take forwarded traffic or take back its own moved traffic. When a site passes maximum, the CPU time to move is
CPU time × (1 − target / current). With current 90%, target 85% and 18,000 ms/s of CPU time, the target CPU time is 18,000 × 85/90 = 17,000, so 1,000 ms/s must move. The ratio makes a 10-server site and a 100-server site comparable, assuming load is roughly linear in CPU, which held well enough. - Learning the maximum. Thresholds differ by site and service, so a service fits, per site, a quadratic curve (with linear regression under test) of cfcheck latency against CPU after removing outliers. The SLO is p95 cfcheck latency of 20 ms, and the CPU value where the fitted curve hits 20 ms becomes the maximum threshold. In Lisbon, cfcheck latency spiked constantly under a static threshold. After the learned threshold went live on 29 July, it never reached the SLO.
- Choosing what and where. It moves the lowest-priority plans first (Free, then Pro, then Business), and sends the highest-priority moved traffic to the lowest-latency sites. Reverting an active move always takes priority over accepting traffic from others. Products also ask it directly: Browser Isolation checks whether a site has capacity for a hosted browser, and if not, Traffic Manager names the nearest site that does.
The post's worked example: site A must move 1,000 ms/s and runs Free 500, Pro 400, Business 200 and Enterprise 1,000. It moves all of Free and Pro and half of Business (100). Neighbours B, C and D have 300, 300 and 1,000 ms/s spare at 100, 110 and 120 ms. Business 100 goes to B with half of Pro (200). Then C takes the other half of Pro (200) and 20% of Free (100). D takes the remaining 80% of Free (400).
Overlooked constraints.
- You cannot steer anycast directly. The only lever BGP gives is "announce or don't". Traffic Predictor exists because the effect of pulling that lever depends on thousands of other networks' choices and changes every time a site or peering session is added.
- Failover must not overload the neighbour. Moving traffic from a sick site into one that is already near its limit just moves the outage, so Traffic Manager plans one step ahead.
- Prefix granularity is set by the internet, not by you. The /24 filtering norm exists for routing security (Lesson 36 on RPKI), and it caps how finely BGP can shift load. Fine control had to move up to layer 4.
- Customer priority is a design input. Free traffic moves first and Enterprise last. That is a business decision written into the control loop.
What Cloudflare sacrificed. Moved users pay extra latency, which can be tens of milliseconds between cities, and moved traffic costs backbone or transit bandwidth. Free-plan users get a slightly worse path more often than paying users. Plurimog also means a connection can be handled far from the city it entered, which complicates debugging and data-locality guarantees. In return, hardware failures in one city mostly stop being user-visible errors, and engineers are no longer paged to edit routes.
Deep Dive: the threshold math and why prefixes strand capacityShow
Acceptable capacity of a receiving site. By the same ratio method, a neighbour with CPU time T at current utilisation u and acceptable threshold a can accept T × (a / u − 1). A site at 50% using 10,000 ms/s with a = 70% can accept 10,000 × (70/50 − 1) = 4,000 ms/s (handbook's illustration).
Stranded capacity with prefixes. Suppose a site carries 40 /24 prefixes of about 3,000 rps each (120,000 rps) and must shed 5%, 6,000 rps. With BGP withdrawals it must move 2 whole prefixes, 6,000 rps, which is exactly right only by luck. If it needs 7,000 rps it must move 3 prefixes, 9,000 rps, stranding 2,000 rps of capacity and sending 2,000 rps of users farther than needed. With layer 4 percentages it moves exactly 7,000 (handbook's illustration).
Fitting the maximum threshold. Suppose a site's data fits latency_p95 = 6 + 0.0025 × cpu² with cpu in percent. Setting latency to the 20 ms SLO gives cpu² = 14 / 0.0025 = 5,600, so cpu ≈ 74.8%. That becomes the site's maximum threshold. A site with faster hardware might fit 6 + 0.0018 × cpu², giving about 88%. A single global threshold would either waste the fast site or overload the slow one (handbook's illustration of the method the post describes).
Lesson 9: Introducing Quicksilver, configuration distribution at internet scale#
Assumptions. By 2020 Cloudflare served more than 14 million HTTP requests per second at peak for more than 26 million internet properties. Every customer change, whether a DNS record, a Worker or one of hundreds of other settings, had to reach 200 cities in 90 countries within seconds. The design rule was strict: each data center must keep serving even if cut off from all central control, so configuration must live on every machine, not be fetched on demand. At least one config read was on the critical path of nearly every request: every DNS and HTTP request did several reads, and every TLS handshake loaded certificates from it.
The old system and why it failed. Cloudflare first used Kyoto Tycoon (KT), described by its own authors as a lightweight datastore with auto-expiry, useful for cache data. Central services wrote to root nodes, which replicated to management nodes in each site, which replicated to every server. By 2015 it ran eight sharded instances (Page Rules separate from DNS, for example), about 100 million key-value pairs and about 200 changes per second, as tens of thousands of KT processes. The problems the post lists:
- Writes blocked reads. KT claims record- or page-level locking, but a lock in the read path is also taken by the flush-to-disk code. Reading the same 20 tiny keys in a loop gave p99 9 ms and p99.9 15 ms with no writes, p99 154 ms and p99.9 250 ms with one writer adding 40 kB values, and p99 701 ms and p99.9 1,215 ms with two writers.
- Turning off fsync caused corruption. To cut write cost, Cloudflare disabled KT's per-write fsync. Kernel panics and processor bugs then left corrupt databases. KT's repair tool took too long or never finished on large databases, so SREs copied databases from healthy nodes by hand. Shutting down meant flushing the whole database, which began exceeding systemd's grace period, so KT was killed with SIGKILL, causing yet more corruption. With thousands of servers, corruption happened several times a day.
- Data only grew. Keys went from about 100 million in 2015 to over 200 million in 2017, over 500 million in 2018 and over 1 billion in 2019. The page cache filled, flushes saturated I/O, and reads slowed again.
- Best-effort replication. Replication was based only on timestamps. A server down for days asked for logs since its last timestamp, and if those logs had been garbage-collected it silently skipped them. The timestamp file was written only when the replication loop exited, so a crash could replay days of old changes and briefly expose stale values. Databases also drifted out of sync for reasons never found.
- No zero-downtime upgrades. Only one process could open a database file, and stopping KT took more than 15 minutes, so upgrades waited for quarterly full "CDN releases".
- No automatic failover. "Dual main" replication required all writes to go to one root and a manual promotion if it died.
KT had no maintainer (last release April 2012) and 100,000 lines of C++. Keeping it running cost 48 hours of SRE time per week.
Production architecture: Quicksilver.
- LMDB as the storage engine. LMDB (Lightning Memory-Mapped Database) is a memory-mapped B+tree with copy-on-write pages. It is optimised for read latency over write throughput, which matches tens of millions of reads per second against rare writes. It allows consistent snapshots of a running database, so new machines bootstrap from a snapshot plus a short replay. It lets multiple processes open the same database, which enables zero-downtime upgrades, and has no read-blocking write lock. It never overwrites live data in place, so a crash never leaves a corrupt file and no recovery tooling is needed. After switching, DNS p99 read latency fell by two orders of magnitude.
- A sequenced log. Replication fans out: servers pull from main nodes, which pull from top mains. Every change carries a monotonically increasing sequence number, so a gap is detected immediately. That works because only one data center accepts writes and assigns the counter: the system distributes reads globally but never needs global writes.
- Defence against misconfiguration. Each database has a unique ID that must match in the replication handshake, so a DNS replica cannot apply Page Rules changes. A random per-process ID stops a node replicating from itself. An incremental hash over the log detects lost or reordered entries, and a per-key CRC is checked on read to catch bugs in chunking code. The team admits it normally prefers code quality to defensive checks, but database consistency was too important.
- Batching. Updates in each 500 ms window are committed in one write, which made durable writes affordable.
- Log in the same database. The log lives in another LMDB bucket so a log entry and its change commit in one transaction. The cost was fragmentation: LMDB stores each value contiguously, so as disks filled, finding a big enough free region could take minutes. A full compaction, done with sites offline, helps for about two months. The fix was to split the log, and later large values, into page-sized chunks. Log entries are compressed with Snappy and garbage-collected.
- Offline tolerance. Each node has primary and secondary sources. Secondary mains keep a much longer history, so a machine can be offline for a full week and still resync.
- Upgrades and simplicity. systemd holds the listening socket and hands it to a new process during upgrades, and clients retry automatically. After years of running it, the team concluded that socket hand-off may be more complex than needed, because a restart takes single-digit milliseconds, and noted that "simplicity is often the best true proxy for reliability".
- Observability. Prometheus, Grafana and PagerDuty, with global, per-site and per-server dashboards. Unavailability is easy to detect because many systems alarm at once. Replication lag is harder because everything looks fine until changes do not take effect, so a heartbeat written at the top of the tree is timed on every server.
Scale at the time: 2.5 trillion reads a day at microsecond latency, about 30 million writes a day, more than 90,000 database instances, over three years of LMDB in production with one bug and zero corruption.
Overlooked constraints.
- Read latency on the edge is set by the write path. KT failed because writes and flushes stalled reads on the same box. Any store that sits on every request's critical path must guarantee that replication never blocks a read.
- Timestamps are not a log. Without a gap-free sequence there is no way to know you missed something. This is the same idea as Kafka offsets or database log sequence numbers (see replication).
- Single-writer is a feature. Quicksilver avoids distributed consensus for writes by funnelling them through one site. That is fine for configuration, with about 30 million writes a day, but would not suit a user-facing write path.
- Global config means global blast radius. The same seconds-to-everywhere pipe ships mistakes as fast as fixes. Several outages below (2019 WAF regex, 2025 bot feature file) were bad config delivered quickly. Quicksilver did its job perfectly; the safety must come from the change process.
What Cloudflare sacrificed. Every server stores a full copy of every config database, so disk and replication bandwidth grow with total config size, not with local need. That is the reason Quicksilver v2 (Lesson 11) later had to shard. Writes are centralised and batched, so a change takes at least half a second plus fan-out time and cannot be written at the edge. LMDB's contiguous values brought fragmentation and periodic offline compaction. The team accepted all of this for microsecond reads that never block and never corrupt.
Deep Dive: why copy-on-write B+trees never block readersShow
How LMDB commits. A write transaction copies every page it changes, from leaf to root, into free space, then atomically switches a single meta page to point at the new root. Readers that started earlier keep reading the old root and old pages, which stay valid because nothing overwrites them. A crash before the meta page switch leaves the old tree intact. There is nothing to repair.
Cost of a write. Changing one key in a B+tree of depth 4 with 4 KB pages writes 4 new pages (16 KB) plus the meta page. Writing 200 small keys one by one costs about 800 page writes. Batched into one 500 ms transaction, keys that share upper pages share those copies, and the batch might write a few hundred pages instead (handbook's illustration). This is why the 500 ms batch window made durable writes manageable.
Why free space fragments. Old pages become free only after no reader still needs them. Values larger than a page need a run of contiguous free pages. If the database holds many 1 MB values and free space is scattered in 4 KB to 64 KB gaps, a new 1 MB value cannot be placed even when 30% of the file is free. Chunking values into page-sized pieces removes the need for contiguous runs.
Gap detection. A replica applying entry 24 when its last entry was 22 knows it missed 23 and requests it, or resyncs if 23 has been garbage-collected. With timestamps, a replica that last saw 10:00:00 and receives 10:00:05 cannot tell whether a change at 10:00:02 existed.
Lesson 10: Quicksilver v1.5, replicas, proxies and consistent reads#
Assumptions. By 2025 Quicksilver was no longer just a config store. It had become the base storage system for many products, and storing the full dataset on every server had become too expensive. The 2025 part 1 post describes the setup: a few hyperscale core sites form the control plane and hold dozens of root nodes with terabytes of storage. Each smaller site has intermediate nodes that replicate from roots or other intermediates, and leaf nodes that serve users and replicate from intermediates. Leaf disks were the bottleneck. Every server hosts 10 Quicksilver instances, each an independent database for a product such as DNS, the CDN or the WAF. By this point each instance was stored in an embedded RocksDB (an LSM-tree key-value engine) rather than the LMDB described in 2020.
The key measurement came first. A pipeline sent accessed keys from across the network into ClickHouse. It showed that large sites used about 20% of the keyspace and small sites about 1%. If proxies had needed the whole dataset to perform, the idea would have been dead.
Production architecture. v1.5 introduced two roles. A replica holds a full dataset. A proxy holds a persistent cache of hot keys and asks a replica on a miss. The first rollout simply put five replicas and five proxies on each server (different instances in each role), so every site had at least one replica of every instance, with up to 50% disk savings in theory. Then the team solved four problems.
- A persistent cache. An in-memory cache would need too much RAM with billions of keys and would start cold after every restart. So the cache lives in RocksDB on disk. Eviction runs inside RocksDB compaction filters (custom code that runs on every key during background compaction): an in-memory LRU-like structure records access times, and when free disk drops below a soft limit, least-recently-used keys are dropped during compaction. Below a hard limit, the proxy stops adding new keys, which hurts performance but keeps the server stable.
- Proxy behind the replica: MVCC. Quicksilver has always promised sequential consistency: if A was written before B, nobody can read B without A. Teams relied on every property of earlier versions (the post cites Hyrum's Law: with enough users, every observable behaviour is depended on). Replication is asynchronous, so a proxy at log index 5 might ask a replica already at index 9 and see values from its own future, then ask a replica at index 2 and see keys missing. Both answers differ from what a replica at index 5 would return. The fix is MVCC (multiversion concurrency control, keeping several timestamped versions of each key). Replicas keep the latest value in the default column family and older versions, tagged with the replication index until which each was valid, in a separate MVCC column family. A request carries the proxy's index. If the latest version is not newer than that index it is returned directly, otherwise the MVCC family is scanned. Tombstones mark deletions. History only needs to cover the largest replication gap between machines: two hours was more than enough and cost about 500 MB per server, with old versions removed by compaction filters.
- Proxy ahead of the replica: the sliding window. A replica cannot answer for an index it has not reached. The first version returned an error, which turned out far too frequent in rollout. The insight was that only very recently written keys are affected, and the proxy has already seen those writes. So each proxy keeps every update within a short, rolling sliding window and never evicts them until they leave the window. It never needs to ask a replica about them. The window's bounds live in memory and are rebuilt from the database index and the configured size after a restart.
- Negative lookups. Requests for keys that do not exist outnumber hits about 10 to 1. In v1 they were the fastest requests: RocksDB's per-file Bloom filters answer "definitely not here" from memory 99% of the time. On a proxy every negative lookup would be a cache miss and a network call. Caching negatives fails because the negative keyspace was up to 1,000 times the real keyspace for some instances, and cached negatives would no longer hit the fast filters. Cuckoo filters for 5 billion keys needed about 18 GB for the same false-positive rate that Bloom filters reached in about 6 GB, all of which must sit in memory. The chosen answer was key-value separation: proxies store all keys but values only for cached keys, and eviction deletes the value. Keys alone are about 11 times smaller than the full dataset, the Bloom filters keep working, and range queries become easier.
Discovery. Inside a site, each data center's Consul cluster plus internal DNS lists the replicas. Proxies also need replicas in nearby sites. Cloudflare reused the Network Oracle, a gossip-based overlay of intermediate nodes that probe each other's round-trip times. It had already replaced a static, hand-edited replication tree with a self-organising, self-healing one. Leaf nodes ask intermediates which sites are close, then query those sites' DNS for replicas. Proxies spread requests across a pool of replica connections and temporarily sideline replicas that return errors. Replica request errors almost disappeared after the new discovery. At p99.9 over 24 hours, proxy and replica latency were almost identical, and proxies were sometimes slightly faster, probably because their datasets were smaller.
Overlooked constraints.
- Moving from "full copy" to "cache plus remote" breaks consistency for free. Every server used to read its own consistent snapshot. Once reads cross machines that replicate at different speeds, you must pass a version with each read or clients see time go backwards. This is the read-your-writes and monotonic-read problem in a production setting.
- Misses dominate when most lookups are for absent keys. Many caches are sized and judged by hit rate on real keys. Here the 10-to-1 negative ratio meant the design was really about how cheaply you can say "no".
- Working-set analysis is a prerequisite. The 20% and 1% figures came from a dedicated pipeline into ClickHouse. Without them the team would have been guessing.
What Cloudflare sacrificed. Proxies now depend on the network for misses, so a site's replicas and its internal network are new failure points. Replicas carry two hours of version history and extra lookup work. Storing all keys on proxies limits the disk saving. The even five-and-five split was deliberately simple and later proved unbalanced (Lesson 11). In return the team got about half the disk back with no visible latency cost, and experience running a distributed Quicksilver.
Deep Dive: MVCC lookups at an index, and the filter memory tradeShow
A version lookup, step by step (handbook's illustration of the post's scheme). Key H was written at indexes 4 and 8. The default column family holds H → v8 (written 8). When v8 overwrote v4, v4 moved to the MVCC family with a suffix saying it was valid until index 7. A proxy at index 5 asks for H. The replica sees the default version was written at 8 > 5, so it scans MVCC, finds v4 valid for indexes 4 to 7, and returns v4. A proxy at index 3 asks for H. The default version is too new and the MVCC version starts at 4 > 3, so the answer is "not found", exactly what a replica at index 3 would say.
Why two hours costs only 500 MB. Only keys overwritten or deleted in the last two hours have MVCC entries. If an instance sees 300 overwrites per second with an average entry of 250 bytes, two hours holds 300 × 7,200 × 250 B ≈ 540 MB, close to the post's figure (handbook's illustration; the post gives only the total).
Bloom versus cuckoo filter memory. A Bloom filter needs about 1.44 × log2(1/p) bits per key for false-positive rate p. At p = 1%, that is about 9.6 bits per key, so 5 billion keys need about 6 GB, matching the post. A cuckoo filter's bits per key are about (log2(1/p) + 3) / load factor. With practical settings and the extra fingerprint bits needed to support deletion and dynamic growth, the cost can be several times higher. That is the gap the post measured (18 GB versus 6 GB).
Lesson 11: Quicksilver v2, a cache everywhere and the full dataset in a few places#
Assumptions. The 2025 part 2 post gives the scale: servers in 330 cities in 125+ countries, over five billion key-value pairs totalling 1.6 TB (up 50% in a year), more than three billion keys read per second, 90% of requests under 1 ms and 99.9% under 7 ms. Some requests ask for hundreds of keys. Every byte Quicksilver uses on a server is a byte not available for the content cache, and the cost of a key grows with every server that stores it.
v1.5 had three problems. Instance sizes drifted, because the teams that own the keyspaces change how they use it, and some instances even shrank, so the five-and-five split became unbalanced. The working-set estimate was wrong for some instances: the analysis had taken all keys used within three days as the cache, implying about 20%, but some instances needed far more. Most importantly, a one-time 40% saving does not create scalability: within about two years disk was running low again.
Production architecture. The key insight was cold keys: many keys are almost never read. Some are old and not cleaned up, some are used only in one region, and some are never used at all (a domain nobody queries, a script uploaded but never run). The team considered sharding the full dataset across servers and rejected it as the primary design: it adds many corner cases, and it destroys locality, since a server holding 1 of 4 shards can serve only 25% of keys locally. Cold keys would still take space in some shard. A cache is the structure that keeps hot keys local and never stores unused ones.
- Full data on a handful of storage nodes. Only a few special storage servers keep full replicas. Every other server runs instances as cache-only proxies.
- Relays. Thousands of proxies connecting straight to a few storage nodes would overload them with connections. So in each site, a few servers per instance are elected as relays. Proxies discover the local relays, and all misses go through them.
- Reactive prefetching. Analysis showed that a key that misses on one server in a site is very likely to miss on another server there soon. So relays publish a stream of every resolved miss, and every proxy in the site subscribes and adds those keys to its cache. Predictive prefetching (guessing keys before anyone asks) was tried in several forms and did not help, so it was dropped. With reactive prefetch the worst instance reached about 99.9% hit rate.
- The DNS instance needed more.
dnsv2, which serves DNS answers, was the most latency-sensitive instance (some DNS queries need several Quicksilver lookups, so misses compound) and had the worst cache behaviour. It needed a much longer retention time (days a key stays after its last access), which meant more disk than one server had. - Sharding returns, for the cache. In v1.5 the team had seen that small sites needed less cache and big sites more: big sites serve bigger, more varied populations, but they also have more total disk. So v2 adds a site-wide sharded cache on top of each server's local cache. Key hashes are split by range into 1,024 logical shards, which are grouped by range into physical shards. Each server is assigned one physical shard by hashing its hostname the same way. Shard caches fill from the same prefetch stream, simply keeping keys in their range longer. Doubling the shard count gives each server a physical shard that is a subset of its old one, so no data moves; unneeded keys age out. Shards are balanced because they are uniform random slices of a huge keyspace.
- Cutting corners safely. Cache shards do not keep MVCC history. Each cached value records the index it was written at. If that is newer than the requesting proxy's index (rare, because shard and proxy versions are close), the relay simply asks a storage replica instead. The post's example: a proxy at version 1000 can use
key2written at 994 from a shard, but notkey1written at 1002.
The result is three tiers: L1 is the local cache of recently used keys, L2 is the site-wide sharded cache of keys used less recently, and L3 is the full replicas on a few storage nodes, reached only for cold keys. The worst instance resolves over 99.99% of keys within the site, and every other instance over 99.999%. Hundreds of thousands of live databases were migrated with no interruption, step by step, with every step easy to revert.
Overlooked constraints.
- Shrinking disk use is not the same as scaling. A constant-factor win buys time. Only a design whose per-server cost tracks local demand, not total data, scales with growth.
- A cache beats a shard when access is skewed and locality matters. Sharding the authoritative data would have forced most reads to cross the network. Sharding the cache kept the local fast path and used the site's combined disk for the long tail.
- Range-based hashing makes resharding free. Splitting a range in half yields subsets, so a doubling never moves data. Modulo-N sharding would reshuffle almost everything (compare consistent hashing).
- The tightest client sets the bar. 99.9% looked like success until DNS, with chained lookups, needed more. Tail latency for multi-key requests grows with the number of keys, since one miss stalls the whole request.
What Cloudflare sacrificed. v2 gives up the property that made v1 so robust: every server could answer every key with no network. Now a site depends on its relays, and rare cold keys depend on a few storage nodes in other places. The system has more roles (replica, relay, proxy, shard owner) and more code paths. The team accepted this because it is the only way for per-server disk to stop growing with total data, and because the measured hit rates make the remote path rare.
Deep Dive: multi-key tail latency, and why 99.9% was not enoughShow
The compounding effect. If each key hits L1 with probability h and a request needs k keys, the chance that all k hit is h^k. With h = 0.999 and k = 1, 0.1% of requests go remote. With k = 5, 1 − 0.999^5 ≈ 0.5% of requests wait for at least one remote lookup. With k = 100, 1 − 0.999^100 ≈ 9.5% of requests do (handbook's illustration). A remote lookup that takes 5 to 20 ms then sets those requests' latency.
Raising the site-wide hit rate. With L2 the in-site hit rate reaches 0.9999 for the worst instance. For k = 5 the chance of any cross-site lookup falls to about 0.05%, ten times better. For instances at 0.99999, it is about 0.005%.
Why doubling physical shards moves no data. Hash keys to the range [0, 1024) and give a site with 4 physical shards the ranges [0, 256), [256, 512), [512, 768) and [768, 1024). A server whose hostname hashes to 300 owns [256, 512). Double to 8 shards and the same server owns [256, 384), a subset of what it already caches. The other half of its old range now belongs to another server, which fills it from the prefetch stream over time, while the old copies are evicted. Nothing is copied in bulk.
Lesson 12: Making Workers KV up to 3x faster by removing hops#
Assumptions. Workers KV is Cloudflare's global, eventually consistent key-value store for Workers. It is used for configuration, routing, personalisation, experiments and serving assets. Many Cloudflare products build on it: Pages stores static assets in it, Access stores authentication data, and AI Gateway and Images store configuration. KV latency therefore lands on every request of many applications. The 2024 post announced up to 3x faster hot reads and every KV operation up to 20 ms faster.
Production architecture. KV is itself a Worker sitting in front of central storage, with caching layers in between. A traced read originally went like this: the customer's Worker connects to the KV Worker in the same location (about 5 ms of network), passes through Front Line (FL), the service that processes requests entering Cloudflare (about 10 ms), and does a cache lookup that passes through FL again (another 10 ms). A Pingora-based service then routes the lookup to the right cache backend in the region, and on a miss the request goes to central storage. Flame graphs made two opportunities obvious: remove the FL overhead, and cut misses.
- Skip FL twice. FL exists to handle traffic from outside Cloudflare, which is far more than an internal binding needs. The KV binding now connects directly to the KV Worker in the same location through a C++ subpipeline in the Workers host that loads the right routing and authorisation. The KV Worker uses an internal binding to reach the Pingora cache service directly. Together these saved about 20 ms per operation. The KV Worker's p90 wall time for cache reads fell from 22 ms to under 12 ms.
- Tiered Cache for KV. A regional cache tier sits in front of the storage backends (Lesson 19 covers Tiered Cache). About 30% of local misses are now answered regionally, and those reads are up to 100 ms faster than going to central storage.
- In-memory cache for the hottest keys. Under 0.03% of keys received nearly half of all KV requests, read thousands of times per second, and almost all were under 100 KB. Those keys are now cached in the KV Worker's own process memory, so reads covering over 40% of KV requests worldwide resolve in under a millisecond without any network hop.
Effects downstream: Pages asset fetches improved by up to 68%, and Queues and Access saw KV reads get 2 to 5 times faster.
Overlooked constraints.
- Internal calls often pay external-traffic costs. Reusing the public front door for service-to-service traffic is convenient, but every request pays for parsing, security checks and routing it does not need. Measure the hops with traces before optimising the code.
- Skew is the most valuable fact about a cache. A tiny set of keys taking half the traffic justifies a separate, tiny, in-process tier. This is the same "hot key" idea as in cache eviction and the hot-key pattern.
What Cloudflare sacrificed. Direct bindings bypass the general FL pipeline, so KV must enforce its own routing and authorisation correctly, a special path to maintain. In-process caching adds another copy of a value that can be stale, which KV's eventual consistency model already allows (up to about 60 seconds of global propagation, as Lesson 13 notes). The gain was a large drop in median and tail latency for little new infrastructure.
Deep Dive: expected read latency across four tiersShow
Model a read as falling through tiers with these shares and latencies (handbook's illustration, shaped by the post's figures): 40% in-process at 0.5 ms, 50% local cache at 6 ms, 3% regional tier at 25 ms, 7% central storage at 125 ms. The mean is 0.4 × 0.5 + 0.5 × 6 + 0.03 × 25 + 0.07 × 125 = 0.2 + 3 + 0.75 + 8.75 ≈ 12.7 ms. The 7% of central reads contribute about 70% of the mean. Add the 20 ms of removed FL hops back to every read and the mean jumps to about 33 ms, so removing fixed per-request overhead was the single biggest change. Moving another 10% of reads from central to regional would save about 0.1 × 100 = 10 ms on average, which is why the tiered cache mattered even though it caught only a minority of misses.
Lesson 13: Workers KV after the June 12, 2025 outage, owning the storage layer#
Assumptions. KV launched in September 2018, before Cloudflare had its own storage products such as Durable Objects and R2. So it was built on object storage from two third-party cloud providers, run active-active. A Storage Gateway Worker (SGW) wrote each key to both providers. Deletes wrote a tombstone that was garbage-collected later. Cache misses raced reads against both providers and took the first answer.
The scale requirements in the 2025 post are: hundreds of billions of key-value pairs, petabytes stored, millions of GETs per second, tens of thousands of PUTs and DELETEs per second, tens of Gbit/s of throughput, and low single-digit-millisecond internal latency. The median value is only 288 bytes.
What went wrong. Keeping two independent providers in sync was hard, and consistency edge cases were more frequent than users wanted. The providers had different limits, failure modes and APIs. KV traffic also outgrew the IOPS of the local cache infrastructure that writes went into directly, forcing a switch to ordinary pull-through caching, which exposed more edge cases. Early in 2025 Cloudflare deliberately moved to one provider to reduce complexity, accepting the higher risk as a temporary state while it built its own storage. On June 12, 2025 that provider had a global outage. A large share of KV requests failed for over two hours. Access could not do identity logins, Gateway was down, WARP clients could not connect, and dozens of other services were disrupted (the outage itself is in Lesson 47).
Production architecture after the fix.
- Not just turning the old provider back on. Its dual-backend infrastructure was gone, the code had bit-rotted, and that provider had often had high error rates and low throughput limits. The new second backend had to be Cloudflare's own.
- A database, not object storage, for tiny values. A private beta of KV on R2 taught the team that billions of sub-1 KB objects carry too much per-object overhead for object storage. KV moved to a distributed database already used behind R2 and Durable Objects, with in-house expertise and automation. Data is sharded across several clusters, each with three-way replication. Several clusters rather than one huge one keep the blast radius small.
- KV Storage Proxy (KVSP). Databases speak binary protocols over long-lived TCP connections, which do not fit Cloudflare's HTTP-based global paths. KVSP exposes HTTP to SGW and hides connection management, authentication and shard routing. It stripes namespaces across clusters with consistent hashing to avoid hot spots and noisy neighbours. Values up to 25 MiB are poor fits for the database, so KVSP routes large values to R2, a size-based hybrid that SGW never sees.
- Racing writes. Writes go to both backends at once, and success is returned as soon as either confirms. A failed side is queued for reconciliation.
Consistency machinery, three layers.
- On write: a write that fails on one backend is captured, deduplicated and synchronised in the background.
- On read: reads now race both backends every time. If the answers differ, the same sync runs. The old system raced only during a learning period, then read from the faster provider, so divergence could persist indefinitely unseen.
- Crawlers: background crawlers scan both backends, fix what the first two layers missed, and measure the drift rate.
Every write carries a version: a high-precision timestamp plus a random nonce. Sync copies the newer version over the older using conditional writes that check the stored timestamp is older, so a late sync never overwrites a newer value. Clock skew could misorder writes only milliseconds apart, and Cloudflare's time service keeps clocks tight. A delete is a tombstone with a newer timestamp, and keys are physically removed only after both backends have the tombstone. Otherwise sync would treat a key deleted on one side as missing data and copy it back. The post names the choice: AP under CAP and PA/EL under PACELC (see CAP and PACELC). Most mismatches resolve within seconds.
Rollout. The steps were:
- Background writes to the new backend, to validate it under real load.
- Copy existing data through KVSP. From this point a manual failover took minutes, removing the single point of failure.
- Active-active for internal namespaces first, dialled up slowly. SGW compared both backends' responses after answering the user.
Testing found a regression. KV is eventually consistent (up to about 60 seconds for global propagation as caches expire), but users had come to rely on read-your-own-write within one PoP. That was never documented, and it had come from writing PUTs straight into the local cache. The change was rolled back briefly. An adversarial test framework that interleaves reads and writes to a few keys from several locations measured the violation rate, and a new cache population and invalidation scheme restored the behaviour.
Results. p99 internal reads through KVSP were under 5 ms. Uncached reads to the third-party store from the closest location were about 80 ms at p50 and 200 ms at p99, after normalising for transit.
Overlooked constraints.
- Removing redundancy to cut complexity is a risk decision, and it can come due. Dropping to one provider was made knowingly as a temporary state. The outage happened inside that window.
- Dormant fallbacks rot. The old dual-provider path could not be revived quickly because its infrastructure was gone and the code was stale. An untested failover path is not a failover path.
- Object size decides storage type. At a 288-byte median, the per-object overhead of object storage dominates. Databases suit tiny values and blob stores suit large ones (compare handling large blobs).
- Undocumented behaviour becomes a contract (Hyrum's Law again). Per-PoP read-your-writes was never promised, but breaking it broke users.
- Reading only from one replica hides divergence. Racing reads cost more but turn every read into a consistency check.
What Cloudflare sacrificed. Racing every read and write to two backends roughly doubles backend load and cost. "Success on first ack" means a write can be durable on only one backend for a while, closed by reconciliation rather than by a quorum. Last-writer-wins by timestamp can drop one of two nearly simultaneous writes. The gains were availability that survives a whole provider failing, much lower latency, and a path to removing the third-party dependency entirely.
Deep Dive: why first-ack writes plus reconciliation converge, and when they do notShow
Convergence argument. Let each key's state on each backend be a (timestamp, nonce, value) triple. The sync rule replaces a triple only with one whose (timestamp, nonce) is strictly larger, so each backend's version of a key can only move forward. The three detectors (failed write, mismatched read, crawler) eventually examine any divergent key. When they do, both backends end at the maximum version. Once writes to a key stop, both sides therefore converge to the same last-writer-wins value. This is the same reasoning as a last-writer-wins register in CRDT terms.
Where it can lose data. Two writes to one key 2 ms apart from different PoPs. If the clocks are skewed by 3 ms, the later real-world write can carry the smaller timestamp and lose. With tight clock bounds this window is tiny. It is the price of avoiding a consensus round per write.
Tombstone necessity, with numbers (handbook's illustration). A delete succeeds on backend A and fails on B. Without tombstones, A has no key and B has v7. The crawler sees "missing on A" and copies v7 back, so the delete is undone. With a tombstone at t = 100 on A, the crawler sees t = 100 > v7's t = 90 and writes the tombstone to B. Only once both sides hold it is the key physically removed.
Racing read cost. At 1 million uncached reads per second, racing both backends doubles backend reads to 2 million per second, but p99 becomes the minimum of two p99 latencies, not one. If the backends fail independently 0.1% of the time each, a read fails only 0.0001% of the time.
Lesson 14: Cloudflare Queues on Durable Objects, from one object to sharded storage and consumers#
Assumptions. Cloudflare Queues let a producer Worker publish events and a consumer Worker process them, for example to decouple a shop's checkout from sending confirmation emails. The team rejected running Kafka or Pulsar because operating them for a huge number of isolated tenants would be too hard. Instead Queues was built on Durable Objects (DOs, single-threaded objects with their own storage and a globally unique name, covered in Lessons 15 and 16).
v1 (beta). One DO per queue, placed in Western North America (WNAM) near the configuration API.
- Sending: a broker Worker near the client authenticated the request, used the DO naming API to route to the queue's object, and the object persisted the message before acknowledging.
- Consuming: the DO kept an alarm set whenever undelivered messages existed. It fired immediately when a full batch was available, or after the user's max wait time for a partial batch. It then sent batches to a Dispatcher Worker, which called the user's
queue()handler through Workers for Platforms dynamic dispatch.
One DO per queue gave near-unlimited queues with isolation and no servers to run. It also hit three limits:
- Latency: distant senders crossed the globe to WNAM.
- Throughput: a single-threaded object capped a queue at 400 messages per second.
- Consumer concurrency: a DO's subrequest limits capped a queue at 20 concurrent handler invocations.
v2 (GA) production architecture. Each queue is now made of many DOs.
- Storage Shards live in every region, several per region. The broker reads a shard map from Workers KV, picks a shard in its region at random, and the shard persists the message.
- Consumer Shards are a separate, horizontally scaled DO class. When notified, a consumer sets an immediate alarm, reads the shard map (which includes each shard's available message count), picks a random shard that has messages, takes a batch, dispatches it, then acks or retries it on that shard.
- One Coordinator DO per queue is the control plane. It handles queue creation and settings and holds the shard map with each shard's region, backlog and load. It writes the shard map to KV periodically so it is cached globally. Every shard heartbeats its message count and request rate. The Coordinator autoscales: it adds storage shards in overloaded regions and adds consumer shards when the backlog grows.
Results: p50 send latency fell from about 200 ms to 60 ms. Per-queue throughput rose from 400 to 5,000 messages per second. Consumer concurrency rose from 20 to 250.
Overlooked constraints.
- A single-threaded actor is a throughput ceiling. A simple "one object per entity" design is great until one entity is hot. Then you shard the entity itself, exactly as with hot keys.
- Random shard choice gives up FIFO. Messages to different shards have no global order. That is acceptable because the product promises at-least-once delivery with batches, not a total order (see delivery semantics).
- Separate the control plane from the data plane. The Coordinator sits only on the management path, and the hot path reads a cached map. If the Coordinator is slow, messages still flow on the last map.
- Build on your own primitives. Using DOs avoided building routing, durability and service discovery, the same "build on the platform" choice as KV moving to Cloudflare's own database in Lesson 13.
What Cloudflare sacrificed. Ordering across shards, simplicity (three DO classes plus a KV-published map), and immediate scaling (the map in KV is eventually consistent, so new shards take effect after it propagates). In return a queue scales horizontally and stores data near its producers.
Deep Dive: shard count from throughput, and random choice versus power of two choicesShow
How many storage shards? If one DO sustains about 400 writes per second (the v1 ceiling), a target of 5,000 messages per second needs at least 13 shards. Running at 70% utilisation for headroom gives 5,000 / (400 × 0.7) ≈ 18 shards across all regions (handbook's illustration).
Is random choice balanced enough? With n shards and m messages placed uniformly at random, each shard's load is roughly binomial. For m = 5,000 per second and n = 18, the mean is about 278 per shard and the standard deviation is about the square root of 278 ≈ 17, so even a 3-sigma shard sees about 329, well under 400. At high rates, randomness balances well. Picking the less loaded of two random shards ("power of two choices", Mitzenmacher, 2001) would tighten the worst case further, but it needs fresh load data. Here, load is only as fresh as the KV map, and stale load data can make "least loaded" choices herd onto one shard. Plain random choice avoids that risk.
Consumer concurrency. If a queue() handler takes 200 ms per batch of 100 messages, one invocation processes 500 messages per second. Consuming 5,000 per second needs 10 concurrent invocations, and a backlog drain at 25,000 per second needs 50. The old cap of 20 would make drain time grow without bound under bursts. The Coordinator's backlog-driven scaling up to 250 removes that.
Lesson 15: Durable Objects, one authoritative object per unit of state#
Assumptions. In 2020, Workers could run code at the edge, and KV offered eventually consistent edge storage. There was still no way to keep strongly consistent state, or to make two clients coordinate in real time, without an origin server. Ordinary serverless requests are load-balanced at random, so there is no way to send two users to the same instance. Kenton Varda's 2020 post introduced Durable Objects to fill that gap.
Production architecture. The name breaks down into three parts.
- Object: an instance of a class you write (for example in JavaScript), with methods as its interface and private state.
- Unique: each object has a globally unique ID and exists in one location in the world at a time. Any Worker anywhere that knows the ID can send it messages, and they all arrive at the same instance.
- Durable: each object has private, persistent storage that lives with it. Because nobody else can touch that storage, the object can safely keep a consistent copy of its state in memory. Idle objects are shut down and recreated on demand.
Two abilities follow: transactional, strongly consistent storage split into many small units, and coordination, routing everything about one topic to one place. Cloudflare picks the data center for each object and can migrate it. The post calls this "Region: Earth": you model objects on your app's logical units (one per document, chat room or shopping cart), not on geographic regions. Millions or billions of objects are fine because each has minimal overhead. WebSocket support for Workers shipped at the same time, because coordination needs a stable place to hold a socket. A message for a user can be addressed to the object holding that user's socket.
Example uses from the post:
- Collaborative editing: one coordinator per document relays keystrokes and resolves conflicts in memory, writing to storage asynchronously.
- Chat: one object per room relays messages directly, with storage only for history.
- A per-IP rate limiter with no durable storage at all: it is acceptable if it occasionally resets.
- Shopping carts, game sessions, IoT homes, per-user feeds and per-article comment widgets.
Versus KV: KV is eventually consistent with last-write-wins, good for rarely changing data read everywhere. DOs sit at the other end: transactional and immediately consistent. Versus CRDTs (conflict-free replicated data types, which merge concurrent edits deterministically): the post argues CRDTs are overly complex and limited for most apps, and one authoritative point per document is simpler. CRDTs can still be layered on top by replicating an object per region (see OT and CRDTs). The longer-term vision is edge databases whose shards are Durable Objects, with no home region.
Overlooked constraints.
- Strong consistency costs distance. A transaction must be coordinated in one place, so a user on the far side of the planet pays round-trip latency. Migration toward users helps, but an object used from two continents must sit somewhere.
- A single thread caps throughput per object. A chat room's limit is far above what humans can type. A global counter for a whole product is a hot spot, so shard it (Lesson 14 did exactly this for Queues).
- Cross-object queries are your problem. Each object sees only its own data. Joins, global indexes and multi-object transactions need application work.
What Cloudflare sacrificed. Generality for a simple model. Durable Objects are not a database. They provide one authoritative actor per key, which pushes the system design choice (what is the unit of state?) onto the developer. In exchange, scaling and placement become the platform's problem.
Deep Dive: the actor model, single-writer ownership and latency placementShow
Actors. A Durable Object is an actor in the classic sense (Hewitt, Bishop and Steiger, 1973): a unit with private state that handles one message at a time and talks to others only by messages. Because only the actor touches its state, there are no locks. Ordering comes from the actor's single queue.
Single-writer ownership. Strong consistency usually needs consensus or locking among replicas. Here only one live instance may own an object's state, which reduces consistency to "the owner's view". The hard parts move into the platform: making sure two instances never both believe they are the owner, which needs leases or fencing (see concurrency control), and replicating writes durably before confirming them (Lesson 16).
Placement math (handbook's illustration). Two editors, one in London and one in Singapore, about 170 ms round trip apart. With the object in London, London edits take about 5 ms and Singapore edits about 170 ms. With it in Mumbai, both take about 100 ms (London to Mumbai about 110 ms, Singapore to Mumbai about 60 ms). Minimising the worst case picks a midpoint. Minimising the average for an active London user picks London. A platform that migrates toward the busiest user follows the second policy.
Lesson 16: Input gates, output gates and the storage cache, correct by default#
Assumptions. Each Durable Object runs in one location, on one thread. Developers reasonably assume single-threaded code cannot race. But storage calls are asynchronous: every await lets other events run, and many apps written against the storage API had subtle races and were slow. The 2021 post ("Easy, Fast, Correct — Choose three") fixed the runtime model instead of asking every app to change, with no code changes required.
The two bugs in naive code.
async function getUniqueNumber() {
let val = await this.storage.get("counter");
await this.storage.put("counter", val + 1);
return val;
}- Race: two requests interleave at the
awaits. Both read the same counter before either writes, so both return the same "unique" number. This happens only under concurrent load, which makes it hard to test for. - Slowness: a get takes a couple of ms. A durable put must reach disk, on several machines and in several Cloudflare locations, so it takes tens of ms. Awaiting it makes everything slow.
The wrong fixes. Transactions fix the race but are slower. They retry under contention, which is worst under high load. Their callbacks may run several times, so any in-memory side effect must be idempotent, a foot-gun tests rarely catch. Manual in-memory caching (keep the counter in a field, fire the put without awaiting it) is fast but still races during initialisation. Worse, a crash can lose un-awaited writes, so numbers already handed out are handed out again after restart.
Production architecture: three runtime rules.
- Input gates. While a storage operation is running, no new events are delivered to the object except storage completions. Incoming requests and even replies to the object's own outgoing
fetchcalls wait. The naive code is now race-free. One caveat remains: if a single event starts two calls without awaiting the first, they still run concurrently. That bug is deterministic and easy to catch in tests, so it was accepted. - Output gates. While a write is pending, every new outgoing message (responses and outgoing fetches) is held until the write is confirmed. If the write fails, the held messages are dropped, replaced with errors, and the object restarts. So code need not await puts: nobody outside can see a "success" before the data is durable.
- Automatic in-memory cache. Each object keeps up to several megabytes of its data in process memory. Cached gets return without leaving the thread. Puts write to the cache instantly, and output gates prevent premature confirmation. Writes are coalesced, so the output gate waits for one round of replication, not one per write. Because gets and puts now finish almost instantly, the input gate is rarely closed, which removes most of its throughput cost.
Bonus guarantees. Several puts and deletes issued without an await between them are committed atomically, so a "move key foo to bar" can never lose the value in a crash. Operations also run in the order they were started, regardless of when they finish. Escape hatches exist for experts who need them:
this.storage.get("foo", { allowConcurrency: true, noCache: true });
this.storage.put("foo", "bar", { allowUnconfirmed: true, noCache: true });Overlooked constraints.
- "Single-threaded" does not mean "no races". Async code interleaves at every await, so the real unit of atomicity is the code between awaits.
- Hiding latency is not the same as removing durability. Output gates keep the durability promise (nothing external sees unconfirmed state) while letting the code run ahead. It resembles group commit in databases and write-ahead logging with delayed acknowledgement.
- Correct by default beats documentation. Cloudflare chose to change the model over educating every developer, because experts get concurrency wrong too.
What Cloudflare sacrificed. Some concurrency: requests to one object queue behind storage operations, a real cost for objects that could safely overlap work (hence the opt-outs). Memory: several MB of cache per active object. Runtime complexity: the gates live inside the Workers runtime. In return, the most natural code is both correct and fast.
Deep Dive: latency arithmetic of output gates with write coalescingShow
Suppose a confirmed replicated write takes 30 ms and a request performs 5 dependent increments, each needing the previous value (handbook's illustration).
- Awaited puts, no cache: 5 × (2 ms get + 30 ms put) = 160 ms.
- Transactions under contention: the same 160 ms, plus retries. With 3 concurrent requests and a 30% conflict rate, the expected attempts are about 1 / 0.7 ≈ 1.43, so about 230 ms, and it gets worse under load.
- Cache plus output gate: the first get may miss (2 ms). The other 4 gets and all 5 puts complete in memory in microseconds. The 5 puts coalesce into one replicated write of 30 ms, which overlaps with any remaining compute. The response is released after about 32 ms, five times faster, and still durable before anyone sees it.
Throughput under the input gate. If a request holds the gate for t ms, the object handles at most 1000 / t requests per second. When storage was always remote (about 2 ms per get), a request with 3 gets capped the object near 1000 / 6 ≈ 166 requests per second. With cache hits taking microseconds, t falls to well under 0.1 ms and the cap rises past 10,000 per second, so the single-thread limit, not the gate, becomes the bottleneck.
Lesson 17: SQLite inside every Durable Object, and the Storage Relay Service#
Assumptions. Traditional cloud storage is slow for two reasons. It is reached over a network, and it must coordinate many clients touching the same data. Durable Objects remove both: code runs where the data lives, and only one object owns it. The 2024 post (Kenton Varda) added a full SQL interface by embedding SQLite, the most widely deployed database in the world, inside each object. SQLite runs as a library in the same thread as the application, so a query with the data cached takes microseconds. Objects are meant to scale out, not up: one object is one thread on one machine. Heavy contention on one piece of state, such as a vote counter for a million users, needs many objects that replicate to each other (with CRDTs over gossip, or fan-in to a primary).
Programming model.
- Synchronous queries.
sql.exec(...)returns results with noawait. Data is usually in memory, and even a disk read is a local SSD ("L5 cache", as the post jokes). Synchronous calls are faster than async ones when the data is in memory, and they remove interleaving bugs because code runs uninterrupted in the order written. - Writes do not wait, thanks to output gates (Lesson 16). The response is held until the relevant writes are confirmed. If confirmation fails, the response becomes an error and the object restarts. Requests run to completion one after another, so latency drops without losing throughput.
- N+1 queries are fine. One query for 100 documents plus 100 lookups for author names costs about 505 ms with 5 ms of network latency per query. In-process, the simple loop performs about the same as a join. Application logic can stay in ordinary code.
- Point-in-time recovery to any moment in the last 30 days, on by default.
- The post's example is an airline seat map with one object per flight. The check "is the seat free?" and the update need no lock, because no
awaitseparates them and the database is private to the object. This is the ticket booking contention problem solved by single ownership. - Storage was limited to 1 GB per object in beta and 10 GB at GA. D1, Cloudflare's managed serverless SQL database, is itself built on SQLite-in-DO. D1 suits the classic "stateless app talks to a database" model. Raw DOs give more control: a front Worker routes requests to an object co-located with its data.
Production architecture: Storage Relay Service (SRS). The original key-value DO storage sat on an off-the-shelf database with regional instances. SRS replaced it from scratch, and it had already powered D1 for over a year. The idea is to use local disk as a cache over object storage: local disk is fast but expensive and fails, while object storage (such as R2) is cheap and durable but slow and suited only to whole large blobs.
- Upload a log, not the database. SQLite always runs in WAL mode (write-ahead log: changes go to a separate log file first and are later checkpointed into the main file). SRS hooks SQLite's VFS (virtual file system layer) to capture WAL frames. It batches them for up to 10 seconds or 16 MB, whichever comes first, and uploads each batch as one object.
- Snapshots bound recovery. SRS uploads a full snapshot whenever the logs since the last snapshot exceed the database size. So rebuilding needs at most 2x the database size in downloads, and stored data is capped near 2x, since data older than the latest snapshot can be deleted. The idea was inspired by Litestream, though the implementation differs.
- Relay to followers for durability now. Every commit is sent immediately to five followers in five different data centers. A write is confirmed (opening the output gate) once three acknowledge it. Followers buffer changes on local disk until SRS reports them uploaded. If that notice never comes, a follower uploads the change itself after a timeout. Losing a confirmed write would take at least four machines in at least three buildings failing at once.
- Fencing with followers. If an object's host is unreachable, it might still be alive and confirming writes. Cloudflare contacts the followers, and once three of five agree to stop confirming writes for the old instance, a new instance can safely start. This is quorum-based fencing.
- PITR for free. Old logs and snapshots are marked for deletion 30 days later instead of immediately, so any point in that window can be replayed. Keeping already-written data an extra month costs less than writing it in the first place.
Overlooked constraints.
- Object storage cannot be the write path for a database. Its latency is tens to hundreds of ms and it wants large blobs. Batches give efficient uploads, and followers give fast durability. Each covers the other's gap.
- Failover needs fencing, not just detection. "Unreachable" is not "dead". Without fencing, two instances could confirm contradictory writes (split brain).
- Bounded recovery cost needs a rule. The "snapshot when logs exceed the DB size" rule caps both download and storage at about 2x the database size, so recovery time stays predictable.
What Cloudflare sacrificed. Every write crosses the network to three of five followers, so confirmation latency is the round trip to the third-nearest follower data center. The 10 GB per-object cap and the single-thread model keep each object small, so large datasets must be sharded by the developer. Building SRS from scratch was a large investment compared with reusing an off-the-shelf database. In return the system gets microsecond reads, cheap durable storage and PITR at no extra effort.
Deep Dive: durability probability and the 2x snapshot boundShow
Loss probability (handbook's illustration). A confirmed write is lost only if the host and at least three of the five followers that hold the change (or every follower that acked) fail before an upload. Suppose each machine independently fails within a 10-second window with probability p = 1e-6. The chance that the host plus all three acking followers fail in the same window is about p^4 = 1e-24. Correlated failures dominate real risk, which is why the followers sit in different buildings.
Why snapshots bound downloads at 2x. Let D be the database size. A snapshot is taken when the total log size L since the last snapshot exceeds D. So at any time L is at most D, plus at most one batch of 16 MB. Recovery downloads the snapshot (size at most D) plus the logs (at most D), so about 2D in total. Without snapshots, a 1 GB database receiving 10 GB of updates a day would need 300 GB of logs replayed after a month.
Confirmation latency. If the five follower data centers are 2, 4, 6, 15 and 30 ms away, the third ack arrives after about 6 ms. A write quorum of 3 out of 5 tolerates two slow or failed followers without hurting latency, the same reason Raft and Paxos quorums use a majority.
Lesson 18: Waiting Room on Workers and Durable Objects, global admission control#
Assumptions. Waiting Room was first offered free through Project Fair Shot for COVID-19 vaccination sign-ups. It works like a shop's door limit: it keeps the number of users on a customer's site under the configured limits during surges, puts the rest in an orderly queue with an estimated wait, and admits them automatically. Three requirements: respect the limits worldwide, add little latency, and keep the experience seamless. The customer configures Total Active Users, New Users Per Minute and Session Duration (a session ends after that many minutes of inactivity). Traffic arrives at hundreds of data centers via anycast, and the hard part is a global counter without a slow global round trip on every request.
Production architecture.
- Ticket in an encrypted cookie. Each user gets a cookie holding
bucketId,acceptedAtandlastCheckInTime. The site stores no per-user server state. An accepted user's cookie expires Session Duration minutes after they were last seen. - Time buckets for fairness. Users are grouped by the minute of their first visit (everyone arriving from 19:51:00 to 19:51:59 shares bucket 19:51:00). This avoids tracking every user and still gives first-come, first-served order across the globe.
- User slots. Slots available = the configured limit minus the users already let through. With a limit of 200 and 201 active users there are no slots. When active users fall to 148 there are 52 slots, which go to the oldest buckets first (2 from 15:54 and 50 from 15:55).
- Per-data-center limits from history. Rather than a global counter, each data center gets a share of the slots in proportion to its traffic two minutes ago. History cannot change, so every location computes the same split even when current data is delayed. Example: if Nairobi and Dublin had 50/50 traffic at 16:31, then for 16:33, 1,000 slots split 500/500. With 45/55 at 16:32, the next minute splits 450/550. A delay can only cause a small, local overshoot. When a bucket is only partly eligible (20 of 60 slots), the eligible slots are split by the same past ratio (for example 5 to Nairobi and 15 to Dublin).
- Estimated wait = users ahead of your bucket ÷ average users admitted per minute. With 60 users ahead at 30 per minute, the wait is 2 minutes.
Coordination options considered.
- Workers KV (March 2020): each Worker writes its own key and lists the namespace. Rejected, because KV is built for reads, so this write-heavy use was expensive, and eventual consistency was too slow to react to spikes.
- Central Redis in core data centers behind a proxy: workable, but a lot of operational work and a global dependency on the core. If the core fails, every waiting room fails, while edge-based state survives a site loss through anycast.
- Durable Objects (then in closed beta): one object per waiting room gives sharding and isolation between customers for free, and runs at the edge.
Two-level aggregation. One DO per room cannot absorb every Worker's updates, since it is single-threaded. So:
- Each Worker decides admit-or-queue locally from worker user slots = the data center's slots ÷ the number of Workers there (10 slots and 2 Workers give 5 each), and counts what it admitted and queued.
- A Data Center DO (chosen by the request's
cf.colo) aggregates its Workers, tracks the Worker count, and writes state to the Cache API. Workers read the cache on the hot path, not the DO. Workers report to the DO at an adaptive rate based on how many Workers exist. - A Global DO holds every data center's state in memory and answers each data center with the whole world's state. It backs up its memory to the Cache API to survive restarts. Persistent storage was not needed because the state rebuilds within moments from fresh reports.
Results: Verto Health served over 4 million people in Canada, Ticket Tailor cut peak resource use from 70% to 10%, San Luis Obispo County survived surges of 23,000 users, and Latvia stayed up through surges of thousands of requests per second.
Overlooked constraints.
- An exact global counter is the wrong goal. A global limit enforced exactly needs consensus on every request. Splitting the budget by stable history turns it into local decisions with a bounded error, the same idea as Lesson 8's per-location budgets and distributed rate limiting.
- Fairness needs a global order without global state. Minute buckets carried in the user's own cookie provide it. This is the classic virtual waiting room in ticketing.
- Hierarchy keeps a single-threaded coordinator alive. Hundreds of thousands of Workers reporting to one actor would overload it. Workers to data center DO to global DO, with cached reads, scales by fan-in.
- Soft state can live in a cache. Because counts are refreshed every few seconds, losing the backup only costs a short warm-up.
What Cloudflare sacrificed. Precision. During a sudden shift in where traffic comes from, the two-minute-old split can let a few more users in than the limit at one location, while another location queues people who could have entered. The customer's limit is a target, not a hard guarantee. Minute-level buckets give coarse fairness: within a bucket, order is not first-come, first-served. In return, there is no central database and no per-request global round trip, and each room is isolated from other customers.
Deep Dive: bounding overshoot from stale traffic shares, and the admission rateShow
Overshoot bound (handbook's illustration). Let S be the slots for the next minute and let r_i be each data center's share from two minutes ago. If data center i's true share this minute is q_i, it admits min(r_i × S, q_i × demand). The total admitted never exceeds S, because each location stays under its own budget r_i × S. The error is under-admission: when traffic moves suddenly from Dublin to Nairobi, Nairobi queues users while Dublin's slots sit unused. Overshoot comes only from propagation delay inside a data center, such as Workers that started since the last count, each spending a full worker budget. If 20 new Workers appear between reports and each has a budget of 2, the overshoot is at most 40 users at that one site.
Admission flow. With Total Active Users = 10,000, a Session Duration of 10 minutes, and users who leave after 6 minutes on average, about 10,000 / 6 ≈ 1,667 slots free up each minute. A queue of 50,000 therefore drains in about 30 minutes, and the estimate shown to a user in the last bucket is 50,000 / 1,667 ≈ 30 minutes. New Users Per Minute also caps admission: if it is 1,000, that cap wins and the drain takes 50 minutes.
Lesson 19: Tiered Cache and Smart Topology, picking the one best upper tier#
Assumptions. In a plain CDN, every data center is a separate reverse proxy for the origin. The data centers know nothing about each other, so one asset can be fetched from the origin once per data center, hundreds of times. A miss is a miss even if a neighbour has the file. You cannot ask every data center on every miss, and you cannot predict demand perfectly, so the practical rule is: after the first miss, store a copy in a known location that others can check. That is Tiered Cache: some data centers act as reverse proxies for others. The topology says which proxies which.
Production architecture (2021 post).
- Custom topologies are tuned by enterprise teams with Cloudflare engineers. The customer knows the latency-versus-hit-ratio balance they want, while Cloudflare knows the network.
- Generic topology (the default): several upper-tier data centers spread worldwide, with smaller sites proxied by large sites in the same region. Upper tiers do not know about each other, so more of them means shorter detours but a lower hit ratio. If an upper tier goes offline, sites use a fallback or behave as if tiering were off.
- Smart Topology assumes the origin is in one place and picks the single best upper tier, the data center with the lowest latency to the origin, without the customer saying where the origin is.
- IP geolocation was rejected. Commercial databases lack coverage and accuracy, and physical distance approximates Internet latency poorly.
- Probing: each data center times TCP handshakes to the origin IP.
- A leaderboard: every hour, eligible data centers (only those large enough) compete on 24-hour median latency to each origin. A faster one can knock another off. Records only improve, so the choice converges and stabilises. Stability matters because every change of upper tier causes a burst of misses. The board keeps the best and second-best, the second as a fallback during maintenance.
- Detecting anycast origins with physics. If the origin is behind another provider's anycast network, the probe measures the distance to that network's edge, not to the origin. Cloudflare knows the distances between its own data centers. Placing the origin as a stop between two of them gives the minimum latency pair that the speed of light in fiber allows. If observed latencies are faster than light, the "single origin location" assumption is false. Even one impossible observation anywhere makes the zone fall back to the generic topology.
- Choices are stored per origin CIDR block. Until a choice exists, the generic topology is used.
Overlooked constraints.
- Hit ratio and latency pull in opposite directions. One upper tier maximises hits, because every miss converges on one cache. Many upper tiers minimise detour latency. Smart Topology chooses one, placed next to the origin, so a miss costs about the same as with no tiering at all.
- Measurement assumptions must be checked. Probe latency equals origin latency only if the IP is in one place. Using the speed of light as a sanity check is a neat, general trick for detecting anycast or proxies.
- Choose for stability. A choice that flips between near-equal candidates churns the cache. A monotonic leaderboard with a fallback trades a bit of optimality for steadiness.
What Cloudflare sacrificed. A single upper tier concentrates load and cache misses on one data center, which must have the capacity, and a failure there causes a burst of misses at the fallback. Origins behind anycast do not benefit. The design accepts these to get the highest hit ratio with near-zero extra latency.
Deep Dive: origin load with and without tiering, and the speed-of-light testShow
Origin load (handbook's illustration). An asset is requested in 250 data centers within its TTL. With no tiering, the origin sees up to 250 misses per TTL. With 10 regional upper tiers it sees up to 10. With one smart upper tier it sees 1. For a site with 100,000 hot assets and a 1-hour TTL, that is 25 million versus 1 million versus 100,000 origin fetches per hour.
Latency cost of the detour. A Sydney user's miss goes Sydney to upper tier to origin. If the origin is in Virginia and the upper tier is at Ashburn, Sydney to Ashburn is about 200 ms and Ashburn to origin is about 2 ms, close to the direct 200 ms. A badly placed upper tier in Frankfurt would add about 90 ms on every miss.
Light test. Light in fiber travels about 200 km per ms, so the round trip covers about 100 km per ms of RTT. If data centers A and B are 8,000 km apart, then for any single origin location O, the distance A to O plus O to B is at least 8,000 km. So RTT(A,O) + RTT(B,O) must be at least about 80 ms. If probes report 5 ms from A and 6 ms from B, the sum is 11 ms, which is physically impossible, so the "origin" is anycast.
Lesson 20: Coreless purge, moving cache invalidation out of the core#
Assumptions. Purging (invalidating cached content) is hard for three reasons.
- Scale: a popular asset may be cached in hundreds of cities, and every one must get the purge, including sites that are offline or unreachable at the time.
- Speed: while a purge propagates, some users see new content and some see old. A non-backward-compatible JavaScript upgrade can break a site. Even light alone takes over 180 ms from Tokyo to Cape Town over real cable paths.
- Scope: purge too much and a thundering herd hits the origin, and costs rise. Purge too little and users see stale data. The purge types are everything, by prefix, by hostname, by URL (single file) and by tag (
Cache-Tagresponse headers).
The 2022 benchmark (48 hours of real user monitoring data, about 90 cities): purge by URL had a p50 of about 0.84 to 0.95 s by region (1.31 s globally), a p99 around 6.3 s, and flexible purges had a p50 of about 1 to 1.4 s (1.57 s globally). The goal was the speed-of-light limit for a network that size, about 200 ms.
Old architecture. Any data center received the purge and sent it to a core data center for authentication, authorisation and filtering. From there it was fanned out worldwide through the distribution service. The core was the bottleneck, and the message queue still ran on bare metal.
Production architecture: coreless purge (2023 part 2).
- Local receipt. An API Gateway worker in the nearest data center does authentication and route authorisation for this non-central endpoint, then forwards to a Purge Ingest worker in the same data center.
- Test locally. The ingest worker validates the URLs and purges them from the local cache first, using the same ownership checks normal traffic uses. Over 50% of requested URL purges could never have been cached by that zone (a customer asking to purge a domain it does not own, or a URL its rules bypass). These are dropped instead of being broadcast. Local purge also returns the computed cache key, which is the same everywhere, so other data centers do not have to recompute it.
- Queue in a Durable Object. A Purge Queue DO keeps a durable queue of purges plus a pointer per data center showing how far each has processed. A site that was offline or partitioned replays from its pointer to catch up. One global DO would just recreate the core, so there are dozens of DOs per region, picked from a regional load-balancing pool.
- The "goldilocks zone". A DO must load topology and health data at startup, so it needs steady traffic to stay warm, but too much overloads its single thread. Regional purge traffic changes with time of day, so DOs report their load and a Regional Autoscaler worker resizes the pools to stay in the efficient band.
- Fanout per region. Queue DOs push directly to data centers in their own region. For other regions they hand off to one Purge Fanout worker per region. Fanout workers are plain Workers with in-memory queues and pointers, reported back to the DOs that persist them. They run in the data centers with the most reliable links, so a retry to a remote region crosses the ocean once, and retries within the region are cheap. This alone cut end-to-end latency by 50% and tripled throughput.
Purge by URL ran on this path from July 2022. Flexible purges at first only used the new edge entry (with authentication and validation at the edge, and faster error feedback) before going to the core for fulfilment, because removing many objects needed a different mechanism (Lesson 21).
Overlooked constraints.
- Validate at the edge, before fanning out. Half of purge requests were useless, and broadcasting them would have cost the whole network. Filter work before you multiply it.
- Compute once, ship the result. Sending the cache key instead of the URL saves hundreds of identical computations, one per data center.
- Per-receiver pointers make broadcast recoverable. A durable log with a cursor per data center is the same idea as Kafka consumer offsets. Offline sites catch up instead of missing purges.
- Hierarchical fan-out beats a flat broadcast. Retries are the expensive part of long-distance delivery, so keep them regional.
What Cloudflare sacrificed. The central core's simplicity: purge now spans gateways, ingest workers, many queue DOs, fanout workers and an autoscaler. State is persisted only in the queue DOs, so a fanout restart means re-sending from the DOs' pointers. The team also accepted shipping purge by URL first and leaving flexible purges partly core-based for a while.
Deep Dive: why per-region fanout halves latency, in numbersShow
Flat broadcast (handbook's illustration). One queue DO must send to 330 data centers. If each send takes 0.5 ms of DO CPU, the last data center is reached after about 165 ms plus its network delay. If 1% of long-distance sends need a retry with a 300 ms round trip, the p99 adds 300 ms.
Two-level fanout. The DO sends to about 12 nearby data centers plus 8 regional fanout workers, 20 sends taking 10 ms of CPU. Each fanout worker sends to about 40 data centers in its region (20 ms), in parallel with the others. Transit becomes one inter-region hop plus one intra-region hop, and a failed intra-region send retries in about 20 ms instead of 300 ms. Serial CPU work drops from about 165 ms to about 30 ms, and retry cost falls more than tenfold, consistent with the post's 50% latency cut and 3x throughput.
Pointer catch-up. If a data center is offline for 10 minutes while purges run at 2,000 per second, it misses 1.2 million purges. On return, the DO replays from that site's pointer. At 50,000 purges per second, catch-up takes 24 seconds. During that time the site may serve stale content, which is why offline sites are taken out of rotation until they have caught up.
Lesson 21: Instant Purge, from lazy purge to per-machine CacheDB indexes#
Assumptions. By 2024 the goal was a global p50 under 150 ms for purge by tag, hostname and prefix across 330 cities. A cache key is computed from the request (URL plus some headers), and that key decides which machine in a data center stores the file. A URL purge carries everything needed to compute the key. A tag purge does not, because tags are response headers, and matching files could be on any disk of any machine anywhere.
First flexible purge design: lazy purge on Quicksilver.
- No files were scanned. Instead, the timestamps of purges were kept. On a cache hit, the proxy compared the file's insertion time with recent matching purges, and if a purge was newer, it pretended the file was missing.
- Purge history had to be kept longer than the maximum cache eviction age, so that every matching file would either expire naturally or be forced to miss.
- Purges were distributed through Quicksilver hub-and-spoke from the core. That took under a second, and hot-path lookups took low hundreds of microseconds. The team called Quicksilver "a hammer that makes everything look like a nail".
- It stopped scaling. Purge history for millions of API calls a day took disk on every machine, space that would otherwise cache content. Quicksilver's write rate became a limit. Kafka queues in front of it to absorb spikes, and more batching, added latency. Customers far from the core, such as in Australia, paid a trans-Pacific round trip. And Quicksilver cannot accept writes from "spoke" data centers, so it could not serve coreless distribution.
Production architecture: active purge with CacheDB.
- Where to put an index? A global index for trillions of files would be the old bottleneck again. A per-data-center database cluster (up to several hundred machines) would need its own team. A per-machine index won. The proxy talks to it over Unix domain sockets with no network in the hot path, and it needs no distributed database: if the machine dies, its index and its cache die together, which is fine. Its maximum size is predictable from the disk size.
- Feasibility was checked by measuring representative disks: assets per TB, tags per asset, and MISS, REVALIDATED and EXPIRED rates to estimate write load. Several relational and non-relational databases were benchmarked, and RocksDB won once tuned.
- CacheDB is a Rust service on RocksDB that runs beside the cache proxy. It adds index entries when a file is cached or updated and removes them on eviction or purge. It keeps a local queue of purge operations. A background process looks up matching files, deletes them from disk, then clears the indexes and dequeues the operation.
- Immediate effect before deletion finishes. On every cache hit, the proxy asks CacheDB whether any pending purge matches. So a purge takes effect the moment it reaches the machine, even if deleting millions of matching files takes a while.
- Distribution. The coreless pipeline (Lesson 20) now broadcasts flexible purges to CacheDB on every machine. CacheDB handles the last-mile fan-out within a data center, using Consul for peer health.
Results. Long-lived lazy purge history was gone, saving 10x storage and freeing disk for longer cache retention. Purged content is now deleted at once. The global p50 is 149 ms versus 1,570 ms in May 2022 (90.5% better). Regionally it ranges from 115 ms (WNAM) to 303 ms (Africa). The clock starts when the request enters the local data center and stops when every data center has executed it. Single-file purge was at a 234 ms p50, with a target below 200 ms. The new capacity let Cloudflare plan flexible purges for all plans.
Overlooked constraints.
- Lazy invalidation's cost is hidden in retention. Lazy purge looks free, but history must outlive the longest cache lifetime, and at scale that history eats the cache itself.
- The best general system is not the best for every job. Quicksilver's strength (hub-and-spoke, read-optimised) made it wrong for a write-heavy, edge-originated workload.
- Co-locate the index with what it indexes. A sidecar index that shares its machine's fate needs no replication, consensus or failover.
- Make the effect immediate, and let the work be eventual. Checking pending purges on hit separates correctness (no stale content served) from the slow physical deletion. This is a general cache invalidation pattern.
What Cloudflare sacrificed. Every cache hit now makes an extra local call to CacheDB, which costs microseconds on the hottest path. Every machine runs an extra stateful service and carries an index whose writes track the cache's churn. In return, purges are an order of magnitude faster, storage use falls tenfold, and purge throughput no longer grows with Quicksilver's limits.
Deep Dive: sizing a per-machine tag index, and lazy purge historyShow
Index size (handbook's illustration). A machine with 20 TB of cache disk and an average object of 200 KB holds about 100 million objects. With an average of 3 tags per object and about 60 bytes per index entry (tag hash, cache key and overhead), the tag index is about 100M × 3 × 60 B ≈ 18 GB, under 0.1% of the disk. Hostname and prefix indexes add similar amounts. Write load follows misses and revalidations: at 2,000 new or updated objects per second, the index takes about 6,000 writes per second, easy for a tuned RocksDB.
Lazy history cost. Lazy purge must keep every purge record for longer than the maximum eviction age. If that is 30 days and customers issue 50 million purge calls a day at about 200 bytes compressed, every machine stores 30 × 50M × 200 B = 300 GB of history, read on every hit. Active deletion lets a record be dropped once its deletion pass finishes, typically within seconds to minutes, which matches the post's 10x saving in order of magnitude.
Lesson 22: Putting unpopular assets in memory, a transient cache to save SSDs#
Assumptions. The cache storage layer serves millions of hits per second from high-IOPS NVMe SSDs. Two facts drove the 2020 post. First, hit tail latency was dominated by SSD I/O capacity. Second, flash wears out from writes, and replacing dead SSDs (device, shipping, labour, downtime) across 200 cities was a real cost. A typical edge server in the post had 256 GB of RAM: services used about 88 GB of resident memory (RSS, the memory a process actually holds), and about 129 GB served as the Linux page cache, with about 42 GB of that holding cached web assets.
Why the obvious idea was already done. Linux's page cache keeps recently used file pages in RAM, roughly LRU, so popular assets are already in memory. It also buffers writes, but cached web assets are written once and rarely updated, so every page still reaches disk eventually. The cache service knows more than the kernel (content type, access frequency, TTL) and can make smarter choices.
The insight: avoid writing one-hit wonders. Many assets are one-hit wonders: cached once and never read again, or evicted before being read. An experiment on a sample of traffic cached assets only on their second sighting. Disk writes halved and disk hit tail latency fell by about 5%, because SSD program/erase operations block reads on the same flash chips. Fewer one-hit wonders also leave more effective space for real content, so hit ratio and retention rise.
Two designs considered.
- Remember but do not cache (the experiment's method): track sightings in a hash table, Bloom filter, counting Bloom filter or count-min sketch, and cache from the Nth sighting. Rejected, because every asset would miss at least twice, multiplying origin bandwidth and server load for customers.
- Transient cache in memory (chosen): every asset bound for disk goes first into a RAM transient cache. It is promoted to the SSD-backed permanent cache after a number of hits. Otherwise it ages out of RAM. Each asset is missed only once, and disk writes go only to proven-popular assets. This is the admission filter idea, the same as TinyLFU-style admission in modern caches.
Trade-offs managed in production.
- Transient size: too small, and new assets evict old ones before they earn promotion, which shortens retention and causes more misses.
- Competition with the page cache: every GB for the transient cache is a GB the page cache cannot use for popular assets.
- Competition with process memory, which is a hard requirement. Some services briefly double their RSS during zero-downtime upgrades (old and new versions run side by side). Without enough RAM, page cache shrinks and I/O pressure makes the whole system slow.
So it was enabled conservatively: only on newer servers with more RAM, and only for a subset of assets. Results: disk write bytes fell 25% at peak and 20% off peak, and hit tail latency fell measurably. Experiments applying it to all traffic in some data centers showed up to 70% fewer writes and up to 20% lower user-visible tail latency at peak. Future ideas: promotion that considers TTL (do not promote an asset with seconds to live), demotion from SSD to RAM, and HDDs as another tier with no wear-out problem.
Overlooked constraints.
- Writes hurt reads on flash. A write-heavy cache slows its own hits. Reducing writes is a latency optimisation, not only a cost one.
- Memory is shared by three users: processes (a hard need), page cache (popular data) and the transient cache (unpopular data). Tuning one starves another.
- The rollout was hardware-gated. The right answer differs by server generation, so the feature is a knob, not a constant.
What Cloudflare sacrificed. RAM that could have been page cache, so some popular-asset reads may go to disk. An asset seen only once is not on disk if it is requested again after leaving the transient cache. More logic in the cache path. The gains were longer SSD life, lower tail latency and better effective capacity.
Deep Dive: when a transient cache pays, a simple modelShow
Let a fraction f of new assets be one-hit wonders (handbook's illustration). Without admission, every new asset is written to SSD: W writes per second. With a transient cache that holds assets long enough for a second hit, only the (1 − f) re-requested assets are written. With f = 0.5, writes halve, matching the second-hit experiment. SSD lifetime (rated in drive writes per day) grows by about 1 / (1 − f), so 2x at f = 0.5.
The window problem. If the transient cache holds C bytes and new assets arrive at R bytes per second, an asset survives about C / R seconds in RAM. With C = 16 GB and R = 200 MB/s, that is 80 seconds. An asset whose second request comes 5 minutes later is never promoted and becomes a repeat miss. So a bigger C saves more writes but takes page cache. The post's conservative rollout was a search along this curve.
Lesson 23: Rate limiting millions of domains at the edge, the sliding-window counter#
Assumptions. In 2017 Cloudflare offered rate limiting to every customer. A rule matches requests (failed logins, expensive API calls), counts them per client IP, and blocks above a threshold, protecting the origin from brute force and layer 7 DoS. There were millions of domains and even more rules. NGINX's stock limit_req works per server, but traffic for one client is spread over many servers. A central store would add global latency and a global dependency.
Production architecture.
- Anycast narrows the problem. Under normal conditions, packets from one IP reach the same PoP consistently. Only the server inside the PoP varies by connection. So counting can be isolated per PoP, fixing latency and availability.
- Per-PoP memcache via Twemproxy. Cloudflare already ran a Twemproxy cluster in each PoP (for TLS session data), sharding a memcache-compatible store (Twemcache) across servers with consistent hashing, so resizing moves few keys.
- Algorithm choice under protocol limits.
- A fixed window counter lets bursts through at window boundaries.
- Storing every timestamp is accurate but needs too much memory and processing.
- A leaky bucket has two hard-to-tune parameters (rate and burst) and needs several operations that memcache cannot do atomically. CAS (compare-and-set) retries would collapse under attack-level contention.
- Only GET, SET and INCR were available.
- The sliding-window counter. Keep two counters, the previous and the current window. Estimate rate = previous × (time remaining in the window ÷ window length) + current. Example: limit 50 per minute, 15 s into the current minute, 42 requests last minute and 18 this minute, so 42 × 45/60 + 18 = 49.5, and one more request trips it. Across 400 million requests from 270,000 sources, 0.003% of requests were wrongly allowed or blocked, the estimate was off by 6% on average, 3 sources slipped through while less than 15% over the limit, and there were no false positives. It costs two numbers per counter, one INCR to count and one GET to read both counters.
- Keep the hot path free. Increments run asynchronously. When a client crosses the threshold, a mitigation flag is written that all servers in the PoP check. The mitigation's end time is known, so each server caches it in memory and stops querying for that client until it expires. It handled several billion requests a day and attacks of 400,000 requests per second against a single domain.
Overlooked constraints.
- Routing can partition the problem for you. Anycast's per-PoP stickiness turns a global counting problem into many local ones. Look for natural affinity before building global state.
- The store's API shapes the algorithm. With only atomic INCR, the sliding-window counter is the best accuracy you can get without transactions.
- Never let the limiter slow legitimate users. Async counting plus a cached block decision keeps the per-request cost near zero even during attacks.
This is the algorithm the rate limiting and rate limiter case study pages call the sliding-window counter, here with production accuracy numbers.
What Cloudflare sacrificed. Exactness: the estimate assumes an even rate in the previous window, and async counting lets a few extra requests through before a block lands. Global limits: a client spread over many PoPs (for example a botnet) is counted per PoP. Anycast route changes can split one client's count. These were accepted for speed and resilience.
Deep Dive: worst-case error of the sliding-window counterShow
The estimate assumes the previous window's N_prev requests were spread evenly. The worst case is when they all arrived at the very end of the previous window. At time t into the current window, the true count over the last W seconds is N_prev + N_cur, but the estimate is N_prev × (W − t)/W + N_cur. The undercount is N_prev × t / W. For a limit L = 50 per minute, at t = 30 s with N_prev = 50 bunched at the end, the estimate is 25 + N_cur, so up to 25 extra requests are allowed in that half-minute, a 50% overshoot in that adversarial pattern. Real traffic is rarely that skewed, which is why measured error was only 0.003% of decisions. If adversarial bunching matters (for example login brute force), use a shorter window or a stricter limit, because tightening the window shrinks the absolute overshoot.
Lesson 24: When Bloom filters do not bloom, memory access beats memory size#
Assumptions. While researching IP spoofing, Marek Majkowski had about 1 billion lines of "IP seen at data center N" data to de-duplicate. Even sort | uniq on a 600 MB, 40-million-line sample took about two minutes. He knew the cardinality roughly and could tolerate rare losses, so a Bloom filter (Burton Bloom's 1970 bit-array set with k hash functions, false positives but no false negatives) looked perfect.
What happened.
- mmuniq-bloom used k = 8 hashes and a power-of-two bit array (a bitwise AND instead of a slow modulo). It ran in 12 s, against
wc -lat 0.45 s. Hashing with SipHash-2-4 cost only about 2 s, so where were the other 10? - Profiling (
strace, thenperfandperf annotate): nearly all cycles were spent in onemovinstruction, the memory load of the filter word. - The memory wall. A random RAM access costs about 100 ns. 40 million lines × 8 hashes × 100 ns = 32 s in theory. The filter was 128 MB, bigger than the L3 cache, and uniform hashing makes every probe a cache miss. Some caching helped, so it was 12 s, not 32.
- Fewer hashes made it worse. With k = 1, the same false-positive target (1 in 10,000) needed a 64 GB filter. Fewer loads, but each still missed cache, and the kernel spent 22 s just preparing memory.
- A plain hash table won. mmuniq-hash stores 64-bit hashes in an open-addressing table with linear probing: about one cache miss per item, and neighbouring slots are prefetched. Collision odds by the birthday bound n²/2m are about 1 in 23,000 for 40M items, better than the Bloom filter's error rate. The final mmuniq, with dynamic resizing and batched prefetch hints (35–40% faster), took 2.1 s, down from 2 minutes.
Lessons the post draws: Bloom filters optimise memory size, not memory access. They are great while they fit in L3 and terrible once they do not. Prefer fewer random loads to less memory. Hash-function cost rarely matters next to cache misses. Start profiling with perf stat -d and look at IPC (instructions per cycle): below 1 usually means waiting on memory. In the words of a colleague, CPUs are infinitely fast until they hit the memory wall.
Where Bloom filters do fit. The Tinder-style feed in the dating app case study shows the right use. A per-user filter of profiles already swiped on is small (around 120 KB for 100,000 swipes), lives in a cache and is checked during feed building. False positives only hide a few profiles a user never swiped, and there are never false negatives, so nobody is shown twice. Its cost is upkeep: the filter must be updated on every swipe and rebuilt from swipe history if the cache node is lost, which is expensive at scale. That is why it is used only for users with long histories, while recent swipes are filtered on the client. Quicksilver (Lesson 10) relies on RocksDB's per-file Bloom filters for the same reason: each filter is small and hot in memory. The probabilistic data structures page covers the math.
Overlooked constraints.
- Big-O ignores the memory hierarchy. Two O(1) structures can differ 10x in real time because of cache misses per operation.
- Measure before theorising. The author first blamed the hash function, and the profiler showed otherwise.
- The right structure depends on the working set's size relative to cache, not only on n and p.
What was sacrificed. The hash table uses more memory than an equivalent Bloom filter and needs resizing logic, both acceptable when memory is plentiful and time is the constraint.
Deep Dive: cost model for membership structuresShow
Let L be the cost of one cache-missing load (about 100 ns) and H the cost of hashing (about 50 ns for SipHash on a short line).
- Bloom, k = 8, filter bigger than L3: H + 8L ≈ 850 ns per item, so 34 s for 40M items in the worst case (the real 12 s reflects partial caching).
- Hash table, linear probing at 50% load: H + about 1.5 probes, mostly in one cache line, ≈ H + L ≈ 150 ns per item, so 6 s for 40M, near the post's measured 4 s plus 2 s.
- With batched prefetch: issue loads for a batch of 16 items, then process them. Memory-level parallelism overlaps about 10 misses, so the effective cost is about H + L/10 ≈ 60 ns per item, so 2.4 s, close to the post's 2.1 s.
Blocked Bloom filters (Putze, Sanders and Singler, 2007) put all k bits for a key in one cache line, giving about one miss per lookup at a small false-positive cost. This is the standard fix when a Bloom filter must exceed cache.
Lesson 25: Kafka for a trillion inter-service messages, a paved road#
Assumptions. Cloudflare has run Kafka since 2014. The 2022 post counts 14 clusters, about 330 nodes and over a trillion messages in eight years, used to decouple microservices by announcing the creation, change or deletion of resources. That is separate from logging clusters, which handle over a trillion messages a day. The Application Services team builds shared tooling so product teams can focus on products.
Production architecture: Messagebus and its tools.
- Messagebus, the general-purpose cluster, aims to prevent data silos, make integration nearly free, and use a self-documenting message format.
- Messagebus-Client, a Go library wrapping Shopify's Sarama with opinionated defaults and mTLS certificate rotation. Its success hid Kafka concepts too well: a small config change caused partition skew, with most messages landing on one partition. Since Kafka allows one consumer per partition in a group, you cannot simply scale out during an incident. Do the throughput math before production, or you will need to add partitions later. The library was changed to make this harder to do.
- Connector framework (based on Kafka Connect ideas) generated by Cookiecutter: choose a reader, transformations and a writer with environment variables (for example read topics from Kafka, transform protobuf to a Quicksilver request, write to Quicksilver), with metrics and alerts built in. The Communication Preferences Service used it to propagate marketing opt-outs and language settings to every system.
- Strict schemas. Messagebus Schema is a registry of protobuf messages. JSON had made forward and backward compatibility hard to enforce, and its messages were much larger. prototool checks for breaking changes and generates Go and Rust code. Each message type maps to an owning team and its chat room for escalation. There is one message type per topic, which made adoption easy but created many low-traffic topics, each with several partitions at replication factor of at least 3, a compute cost to optimise later.
- Observability by default. Topics are created through GitOps with Salt: a few lines of YAML in a PR. On merge, the topic plus a consumer lag alert are created automatically. Lag catches a stopped consumer, a consumer that cannot keep up, an unusual production spike, and a consumer that does not acknowledge. Prometheus and Grafana show production rate, consumption rate and partition skew per topic, and the alert links to that dashboard.
- Alert Notification System (ANS), the backend of the dashboard's Notifications tab. A team adds a YAML entry (validated in CI with CUE), imports the client, and emits to the alert topic. Customers then get Slack, Google Chat, webhook, PagerDuty and email delivery with retries and dead-letter handling included.
Overlooked constraints.
- Abstractions leak where the scaling unit is. Hiding partitions made skew easy to cause. The partition count is a capacity decision (see Kafka).
- Schemas are the contract between teams. Protobuf with automated breaking-change checks replaces out-of-date docs.
- One default alert catches most failures. Consumer lag covers dead, slow and stuck consumers, and spikes.
- Platform teams scale through paved roads. Templates, defaults and automatic alerts let dozens of teams adopt Kafka without each becoming Kafka experts. This is event-driven architecture as an organisational tool.
What Cloudflare sacrificed. Flexibility: one message type per topic and opinionated defaults limit power users and multiply small topics. Compute: each topic carries replicated partitions even at low traffic. In return, adoption is fast, failures are visible and ownership is clear.
Deep Dive: the napkin math for partitions before productionShow
The post urges doing throughput math before launch, because adding partitions later reshuffles key-to-partition mapping and breaks per-key ordering. A worked example (handbook's illustration):
- Peak production: 20,000 messages per second, 1 KB each.
- One consumer instance processes 1,500 messages per second (it calls a database).
- Required parallelism: 20,000 / 1,500 ≈ 14 consumers, and Kafka allows at most one consumer per partition per group, so at least 14 partitions. Plan 2 to 3x headroom for growth and catch-up after an outage: 32 to 48 partitions.
- Catch-up check: after a 30-minute consumer outage, the backlog is 20,000 × 1,800 = 36 million messages. With 32 consumers at 1,500 each (48,000 per second) while production continues at 20,000, the net drain is 28,000 per second, so the backlog clears in about 21 minutes. With only 14 partitions, the net drain is only 1,000 per second and catch-up takes 10 hours.
- Skew check: if one key produces 30% of traffic, its partition receives 6,000 per second, four times one consumer's capacity, and no number of partitions fixes it. Re-key, for example by adding a suffix to the hot key.
Lesson 26: HTTP analytics for 6 million requests per second on ClickHouse#
Assumptions. By 2018 the analytics dashboard and Zone Analytics API served 7M+ domains. That meant 6M HTTP requests per second on average, peaks of 8M, 2.5 billion monthly unique visitors and 1.5 trillion monthly page views. Customers needed breakdowns (totals, by data center, status code, content type, country, threat type, browser, IP class) at minute, hour, day and month granularity for any range in the last 365 days. Average log size was 1,630 bytes in Cap'n Proto, with about 104 fields.
The old pipeline (2014), and why it split at the seams. Edge log forwarders sent Cap'n Proto logs to a Kafka cluster (106 brokers, 106 partitions, replication factor 3). Each partition had a dedicated Go consumer that pre-aggregated per partition, zone and minute, then wrote into a single PostgreSQL instance (RollupDB). Cron jobs rolled minute data into hour, day and month tables. Another cron copied tables into a Citus cluster (1 coordinator, 11 workers) behind the Go API, which was fronted by a PHP API and NGINX. Its problems:
- Two single points of failure (SPOFs): RollupDB had no replicas or backups, and the Citus coordinator handled every query.
- Thousands of lines of Bash, SQL and Go.
- A chain of dependencies, where any link stopping halted everything.
- Frequent, long incidents.
- 15 queries per second of API capacity, enforced with hard rate limits on the biggest customers.
Traffic had grown from under 1M to 6M requests per second since the design. The post's general lesson: re-engineer a system when its requirements have changed.
Rejected first: Apache Flink. The team used Flink elsewhere, but it could not keep up with the per-partition ingestion rate at 6M per second. The DNS team's ClickHouse pipeline (1.5M messages per second at 130 bytes, 40 columns) gave a nearby proof point, though HTTP was 4x the rate, 12x the message size and 2.6x the columns.
Why aggregate and not keep raw logs (the napkin math). At 6M per second for a year, assuming $100 per TiB:
| Format | Bytes per record | Storage per year | Cost per year |
|---|---|---|---|
| Cap'n Proto raw | 1,630 | 273.93 PiB | $28M |
| Cap'n Proto with zstd | 360 | 60.5 PiB | $6.2M |
| ClickHouse columns (RF 3) | 36.74 | 18.52 PiB | $1.9M |
Columnar compression made raw storage about 15x cheaper, but a year of raw logs was still too much. Aggregates stay the long-term product, with raw logs considered for a month or more.
Schema design, two iterations.
- Eight materialized views (one per breakdown) using AggregatingMergeTree. Joining them took a 300-line query, because ClickHouse joins were only pairwise. Querying them in parallel was only slightly faster than Citus. Rejected.
- SummingMergeTree with nested "Map" columns, which are key-to-values structures summed per key on merge. They match the old Postgres hstore columns, so one table can hold many breakdowns. Two gaps had to be closed. Cross-shard final aggregation of maps needed a function that did not exist, so Cloudflare wrote and upstreamed
sumMap. Unique-visitor HyperLogLog states (AggregateFunction columns) are not merged by SummingMergeTree, so uniques live in a separate AggregatingMergeTree view. The rarely used per-data-center endpoint (5% of queries against 95% for the dashboard) got its own view, so its wider key does not slow the main table.
Tuning. ClickHouse keeps a sparse primary index: one entry per granule of rows (8,192 by default).
- Raw table: granularity 16,384, because queries read millions to billions of rows anyway.
- Aggregate tables: granularity 32, because API queries read only a few rows. This cut latency 50% and roughly tripled throughput.
They also sped up SummingMergeTree map merges 7x (contributed upstream) and disabled min_execution_speed, so tiny scans are not killed as "too slow".
New pipeline. The same Kafka, with 106 Go consumers that now only parse and prepare 100+ columns, with no aggregation. These feed a 36-node ClickHouse cluster at replication factor 3 that ingests raw rows and builds aggregates through materialized views, behind a rewritten Go API with health checks and failover. It removed both SPOFs, a Postgres instance, a 12-node Citus cluster, the PHP hop and tens of thousands of lines of code. The API went from 15 to about 40 queries per second in production, load-tested to 150, and the hard rate limits were lifted. Cluster-wide, all pipelines inserted 11M rows per second at 47 Gbps. History was moved with a goroutine-based ETL of 60+ billion rows in a couple of days, with consistency checks.
Overlooked constraints.
- Push aggregation into the database. Materialized views replaced consumer logic and crons. Fewer moving parts means fewer incidents.
- Index granularity follows the query shape. Point-ish reads want small granules. Scans want big ones.
- Mixed hardware is a hazard. ClickHouse handled heterogeneous clusters badly, so all 36 nodes had to be replaced with the new generation. ClickHouse did not throttle recovery, so each replacement was a full-speed re-replication.
- Stream processors have per-partition limits. Flink failing at this rate was a partition throughput problem, not a cluster-size problem.
What Cloudflare sacrificed. Raw-data retention (aggregates only beyond a short window), so new breakdowns cannot be computed for old periods. Dependence on a then-young database, offset by contributing fixes upstream. Query scaling to hundreds of nodes was not proven at the time.
Deep Dive: reproducing the storage napkin mathShow
6M records per second × 86,400 s × 365 days = 1.892 × 10^14 records per year.
- Raw at 1,630 bytes: 3.08 × 10^17 bytes ≈ 274 PiB (1 PiB = 1.126 × 10^15 bytes). At $100 per TiB, that is 280,000 TiB, so $28M.
- ClickHouse at 36.74 bytes per row: 6.95 × 10^15 bytes ≈ 6.2 PiB per copy, × 3 replicas ≈ 18.5 PiB, so $1.9M.
Why columns compress about 44x here: each column holds one type with low entropy along the sort order (status codes, country codes, data center IDs repeat in long runs). LZ4 or zstd on a run of 8,192 near-identical values beats compressing whole rows, where every field type is interleaved. Rows sorted by the primary key (zone, then time) cluster values even more.
The aggregation win: a zone with 1,000 requests per second yields 60,000 raw rows per minute but one row per minute per breakdown key in the aggregate table. That is why 32-row granules suit API queries: a 24-hour chart for one zone reads 1,440 minute rows, a few dozen granules.
Lesson 27: Moving error logs from Elasticsearch to ClickHouse#
Assumptions. By 2022 the network handled 35 to 45 million HTTP requests per second. 500,000 to 800,000 per second failed (bad requests, origin errors, misconfigurations, network problems). Those error logs are the support team's first step in triage and must be kept for a few weeks. In Elasticsearch they were heavily sampled because full retention needed hundreds of TB, and the aggregating dashboards were slow. The post lists four traits of logs that shape any log store:
- Unpredictable volume: constant deploys, autoscaling, forgotten debug levels.
- Semi-structured: mixed formats, timestamps and multi-line stack traces.
- Contextual: the lines around an event and across services matter, so source order must be kept.
- Write-heavy: over 99% of logs are never read, but the 1% that is read is critical.
Production pipeline. Producers write Cap'n Proto logs locally. An in-house shipper streams them to Kafka, Logstash consumed them into Elasticsearch, and Kibana or Grafana visualised them.
Elasticsearch limits at this scale.
- Mapping explosion: too many field keys use heap and cause frequent garbage collection. A strict schema drops lines, and a semi-strict one makes unknown fields unsearchable.
- Weak multi-tenancy: a query cannot be capped on documents, indexes or memory, so one bad query degrades the cluster even after it ends.
- Operational weight: template changes need reindexing, the daily hot-to-cold (SSD to HDD) moves hurt performance, and recovery from degradation is slow.
- JVM GC tuning: ZGC shortened pauses but did not improve throughput.
The ClickHouse design.
- Columnar storage gives fast sequential scans even on older hardware, and wide tables are fine.
- Sparse primary index (one entry per thousands of rows), plus data-skipping indexes built on Bloom filters to skip blocks that cannot match non-key columns.
- Per-column codecs: LZ4 by default, Double-Delta for timestamps, Gorilla for floats (Facebook's XOR-based time-series compression), LowCardinality for repeated short strings. Compression also makes the page cache hold more.
- Linear scaling: shards for writes, replicas for reads, no special nodes. Replication metadata moved from ZooKeeper to clickhouse-keeper. Distributed tables act as proxies over the shards.
- Inserter: Cap'n Proto from Kafka, scaled by adding partitions and pods. Big batches matter most, because small inserts create many small parts that background merges must combine.
- Three schema options for logs.
- Strict columns: fastest, and drops unknown fields.
- Automatic JSON columns: flexible only below about 1,000 fields with tight control, because one noisy app can bring the cluster down.
- Arrays per data type (all string fields in one array of keys and one of values, and so on), queried with array functions. Hot keys are promoted to materialized columns. This option is recommended, because it caps column count no matter how many fields apps log.
- Partition by
toStartOfHour(dateTime): time-filtered queries prune to the right hours and retention becomes dropping old partitions. Avoid overly fine partition keys. The primary key cannot change after creation, and does not need to be unique. - ABR (Adaptive Bit Rate): dashboards hit per-query memory limits. Anomaly spotting does not need exact counts, so each row is written to tables at several sample rates (100%, 10%, 1%, 0.1%). Each query picks the coarsest table that is accurate enough, the way video streaming picks a resolution.
Results. Inserter CPU and memory fell 8x, a 600-byte Elasticsearch document became a 60-byte row, 100% of events are kept with no sampling, and p99 query latency improved sharply. The post's summary: Elasticsearch for full-text search, ClickHouse for analytics.
The array-per-type layout, as a sketch (handbook's illustration):
CREATE TABLE requests_error
(
dateTime DateTime CODEC(DoubleDelta, LZ4),
service LowCardinality(String),
string_keys Array(String),
string_vals Array(String),
number_keys Array(String),
number_vals Array(Float64),
-- a hot field promoted to its own column
colo String MATERIALIZED string_vals[indexOf(string_keys, 'colo')],
INDEX idx_vals string_vals TYPE bloom_filter GRANULARITY 4
)
ENGINE = ReplicatedMergeTree
PARTITION BY toStartOfHour(dateTime)
ORDER BY (service, dateTime)
TTL dateTime + INTERVAL 21 DAY;Overlooked constraints.
- Design for the 1% read path, cheaply store the 99%. Columnar compression made full retention affordable.
- Schema flexibility is a blast-radius question. Dynamic columns let one app's logging change harm everyone. Array-per-type bounds the damage.
- Approximate answers are a product decision. Sampled tables trade exactness for dashboards that load.
What Cloudflare sacrificed. Full-text search quality (inverted indexes are Elasticsearch's strength). The primary key and schema choices are fixed early. Array access is slower than real columns until a field is materialized. The ABR tables cost extra storage. See observability for where logs fit next to metrics and traces.
Deep Dive: why ABR sampling keeps anomaly charts honestShow
If a data center logs 10,000 errors per minute, the 1% table holds about 100 rows per minute. The count estimate is 100 × 100 = 10,000 with a standard error of about √100 / 100 = 10% (Poisson). For spotting a jump from 10,000 to 30,000, a 10% error is plenty. For a data center logging 100 errors per minute, the 1% table holds about 1 row, which is useless, so the query layer must pick the 100% or 10% table. The rule is to choose the coarsest table where the expected matching rows stay above a floor (say 100 rows per time bucket, about 10% error). Storage cost of the extra tables: 10% + 1% + 0.1% ≈ 11% on top of the full table, a small price to make dashboards read 10 to 1,000x less data.
Lesson 28: L4Drop, dropping DDoS packets in the driver with XDP and eBPF#
Assumptions. Packet dropping is the core of layer 3 and 4 DDoS mitigation. The 2018 pipeline had four parts:
- Gatebot analyses sampled traffic and deploys rules.
- bpftools turns DNS query patterns, p0f TCP fingerprints or tcpdump expressions into classic BPF (Berkeley Packet Filter) bytecode.
- iptables with
xt_bpfdrops matching packets. - Floodgate takes over in big attacks: it bypasses the kernel and runs a userspace BPF interpreter.
Floodgate depended on a proprietary Solarflare NIC feature. New Gen9 and ARM servers used other NICs, so Floodgate had to go.
Why XDP. XDP (eXpress Data Path) runs an eBPF program for each packet inside the NIC driver, before the kernel allocates socket buffers. eBPF brings three things:
- maps, key-value structures shared with userspace
- a Clang backend that compiles restricted C
- a verifier that proves programs terminate and stay in bounds (loops were forbidden then)
Kernel bypass needs busy polling and was pinned to one CPU. XDP does not poll, so it can be always on and run on all CPUs.
Design: compile rules, do not interpret them. A single program that checks rules stored in a map (the approach of Facebook's firewall) did not fit. bpftools filters match arbitrary packet bytes across headers (one p0f signature checks IP and TCP options), and without loops you cannot iterate over rules. So L4Drop generates C from the rules and compiles it to eBPF with Clang. The costs: a recompile for each rule change, and the kernel's code-complexity limit caps how many rules fit in one program.
- BPF to C compiler: classic BPF and eBPF are not instruction-compatible (one BPF IP-header-length instruction becomes 6 eBPF instructions in the kernel's converter). Each BPF instruction becomes one C statement, the a, x and m registers become variables, and only the bounds checks the verifier needs are emitted. Clang then optimises the whole program.
- Sample before dropping: Gatebot needs a sample of all traffic, dropped packets included. The program uses
bpf_get_prandom_u32to pick packets andbpf_xdp_event_outputto copy them into a perf ring buffer that a userspace daemon reads. - Geo rules without map lookups: some attacks hit only some locations, but map lookups add code size and so reduce how many rules fit. Instead, each rule is guarded by a 64-bit constant load tied to a named symbol (for example
RULE_0_ENABLED). The loader finds it through the ELF relocation table and patches the constant to 0 or 1 before loading. The kernel then removes the dead branches. It is one compiled program for every location, specialised at load time.
Production result. One server under attack dropped over 8 million packets per second. At first the attack overwhelmed the stack and the NIC dropped some packets, until Gatebot deployed a matching rule. Legitimate traffic passed unchanged before, during and after. Overall CPU rose only about 10%. softirq CPU doubled while incoming packets per second rose over 40x. Next steps were chaining multiple eBPF programs for more rules, and faster detection to shrink the loss at attack onset.
Overlooked constraints.
- Hardware dependencies age. A vendor-specific fast path became a migration blocker when hardware changed. XDP is in the mainline kernel.
- Verifier limits shape the architecture. The no-loops rule forced compile-time specialisation over data-driven rules.
- Observability must survive mitigation. Sampling before the drop keeps the detector seeing the attack it is mitigating. Otherwise the rule would look unnecessary and be removed.
- Detection delay is the remaining gap. Packet loss happened only between attack onset and rule deployment. The autonomous edge in Lesson 29 closes this gap.
What Cloudflare sacrificed. Agility (each rule change is a compile and reload) and rule capacity (complexity limits). The gains were drop rates near line rate on commodity NICs, no busy polling, and protection that is always on.
Deep Dive: the per-packet budgetShow
A 10 Gbps link carrying minimum-size 64-byte frames (84 bytes on the wire with preamble and gap) delivers 10 × 10^9 / (84 × 8) ≈ 14.9 million packets per second. On one 3 GHz core, that is about 200 cycles per packet. A full kernel path (skb allocation, netfilter, routing) costs several thousand cycles, so it cannot keep up at line rate on one core. An XDP drop costs a few dozen to a hundred cycles: parse headers, run compiled comparisons, return XDP_DROP. With receive-side scaling spreading flows over 8 to 16 cores, the 8M packets per second in the post fits in a small fraction of CPU, matching the reported 10% rise. Keeping rules compiled (no map lookups, constant-folded geo guards) is what holds per-packet cycles in that budget.
Lesson 29: The autonomous edge, DDoS detection on every server#
Assumptions. DDoS attacks are cheap to launch. The 2020 Dark Web Price Index put a one-hour attack at 10,000 to 50,000 requests per second at about $10, while a minute of downtime can cost an e-commerce site tens of thousands of dollars. Cloudflare offers unmetered DDoS protection, so being attacked does not raise the bill. Large and small attacks must both be stopped, with no human in the loop.
Production architecture: detect at the edge and at the core.
- Gatebot (in the core) sees the whole network and handles large, distributed volumetric attacks that need global coordination. It works on samples shipped to the core.
- dosd (denial of service daemon), live since mid-2019 for L3/4 and extended to L7, runs on every server in every data center. It detects and mitigates without central consensus. Because analysis is local, it samples HTTP at 10x and packets at 81x the core's rate, which lets it catch small, localised attacks too. In the months before the 2021 post, dosd detected 98.6% of L3/4 attacks and mitigated 81% of L7 attacks.
- flowtrackd tracks TCP state for stateful L4 protection (covered in an earlier post).
The life of a packet, which decides where each rule goes:
- BGP anycast brings the packet to the nearest data center.
- Routers spread packets across servers with ECMP (equal-cost multi-path).
- XDP: L4Drop applies the existing rules and samples packets to dosd (Lesson 28).
- Unimog, the in-house L4 load balancer, also runs in XDP. It keeps the packet on this server or forwards it to a better one based on health and load.
- iptables firewall.
- The packet goes to one of three places: the userspace HTTP reverse proxy (WAF, firewall rules, customer config), Spectrum (TCP and UDP proxying), or Magic Transit (routed IP).
Push the rule to the cheapest layer that can match it. HTTP attacks start as block, rate-limit or challenge actions in the proxy. If an L7 attack is very large, the rule moves down the stack: the attacking IPs go into IP Jails in iptables, so the attack is dropped at L4 and never costs TLS and HTTP parsing. L3/4 attacks are dropped by eBPF in L4Drop.
Overlooked constraints.
- Central detection has a latency floor. Shipping samples to the core and pushing rules back takes seconds. Local detection removes that delay for the most common attacks.
- Detection and mitigation must be autonomous. If mitigation needed the control plane, a large attack (or a control-plane outage) would leave the edge unprotected.
- Cost-aware placement. The same attack costs orders of magnitude less to drop in XDP than in the HTTP proxy, so mitigation moves down the stack as volume rises.
What Cloudflare sacrificed. A global view inside each daemon: one server sees only its own slice, so slow, widely spread attacks still need Gatebot. Running detection on every server costs CPU on every server, everywhere. Per-server rules can briefly differ across a data center.
Deep Dive: why local sampling detects smaller attacksShow
Say a server handles 100,000 requests per second and a targeted attack adds 2,000 per second against one zone (handbook's illustration). With core sampling at 1 in 10,000, the core gets about 0.2 attack samples per second from this server. Even summed over 50 servers that are equally hit, that is 10 per second, and with noise it takes many seconds to reach confidence. Local sampling at 10x the rate (1 in 1,000) gives dosd 2 attack samples per second on its own server. It needs no network hop, so a rule can be in place within seconds. More generally, the time to detect an anomaly of rate r at sampling probability p scales roughly as 1/(r × p), because you need a fixed number of samples k to tell signal from noise. Ten times the sampling cuts the time ten times, or finds attacks ten times smaller in the same time.
Lesson 30: HTTP/2 Rapid Reset, when request cancellation becomes the attack#
Assumptions. From 25 August 2023, attacks peaked just above 201 million requests per second, nearly 3x Cloudflare's previous record, from a botnet of only about 20,000 machines. The whole web carries about 1 to 3 billion requests per second. Google and AWS saw the same attack, and the three coordinated disclosure as CVE-2023-44487. Because the weakness is in the protocol, any HTTP/2 implementation could be affected.
The protocol background.
- HTTP/1.1 sends whole messages in strict order on a connection. Cancelling means closing the TCP connection, so browsers keep pools of up to 6 connections per host.
- HTTP/2 splits messages into frames tagged with a stream ID. Client streams use odd IDs, frames from different streams can interleave, and responses can come back in any order. Multiplexing makes it cheap to launch a lot of parallel work.
- The guardrail:
SETTINGS_MAX_CONCURRENT_STREAMScaps how many streams can be open or half-closed at once (for example 100). A stream beyond that is refused withRST_STREAM. - The stream state machine: a GET is sent as HEADERS with END_STREAM, which moves the stream idle → open → half-closed. The response DATA with END_STREAM closes it.
- Cancellation: a client sends RST_STREAM for one stream. This is useful, for example, when images scroll out of view. A cancelled stream goes straight to closed, so it no longer counts toward the limit. The client can open another one immediately.
The attack. Send HEADERS, then RST_STREAM, then HEADERS, then RST_STREAM, without waiting for the server. In a proof-of-concept capture against a server advertising 100 streams, one packet carried 525 requests. After the first request, HPACK header compression made each HEADERS frame only 9 bytes. The server never saw a concurrency violation. The client is limited only by how much it can send, and the concurrency limit cannot stop it, whatever its value. The damage comes from delayed cleanup: proxies dispatch each request upstream asynchronously, so cancellation reaches the upstream only after work has started.
The impact inside Cloudflare.
- Edge requests pass through a TLS-terminating proxy (TLS plus HTTP/1, 2 and 3) and then a business logic proxy (customer config, routing, and the L7 security features). Every request had to cross into the second proxy before it could be blocked. The pipe between them saturated on some servers, and the TLS proxy returned bare 502s: about 1% of requests in the first wave and 12% for seconds at the worst moment on 29 August.
- Analytics were blind to it. HTTP analytics logs are emitted by the business logic proxy, so these 502s did not appear in customer dashboards.
- A self-inflicted 499 problem. Cloudflare lowered max concurrent streams to 64. Most clients do not wait for the server's SETTINGS. They assume 100, the minimum the specification recommends (the default is effectively unlimited, 2^30 odd stream IDs). Pages like image galleries open 100 streams at once, so 36 were reset. Since 2019 Cloudflare had counted server-side resets per connection and sent GOAWAY above a threshold, so these legitimate browsers were disconnected and pages failed. The limit went back to 100.
Mitigations.
- Count client-sent RST_STREAMs and close abusive connections, extending the 2019 reset-counting defences. Legitimate cancellation is unaffected.
- Better frame processing and request dispatch, and better queuing and scheduling in the business logic proxy, so cancellation takes effect sooner.
- Expanded IP Jail. Jailing used to take seconds to become effective, and this botnet had no ramp-up. Now a jailed IP is blocked from the attacked property and also barred from HTTP/2 to every domain on Cloudflare for a while, so it can only use HTTP/1.x, where this abuse is impossible. Legitimate users sharing the IP see only a small slowdown. Jails are short because botnet IPs churn quickly, and long IP blocks would mostly hit innocent users later. It runs in the TLS proxy, early in the pipeline, so it is cheap. Random 502s went to zero.
- Observability: each service will log its own data, not rely on the business logic proxy, and connection-level logging will be improved.
Overlooked constraints.
- Limits on concurrency do not limit rate. Any quota on things in progress must be paired with a quota on how fast they can be created.
- Where security runs is where attacks must reach. With L7 checks after an internal hop, the hop is the bottleneck. Moving cheap checks earlier (IP jail in the TLS proxy) protects the internal hop.
- Defensive changes have interop costs. Going below the de facto 100-stream assumption broke real browsers, because clients assume settings before they see them.
- Errors you cannot see in analytics hurt customer trust. Logging should happen at every layer, not only in the layer that builds dashboards.
What Cloudflare sacrificed. Some HTTP/2 performance for users who share a jailed IP. Slightly stricter connection policing that could, rarely, cut off a buggy but legitimate client. The fix kept protocol compliance and blocked the abuse. The HTTP and HTTPS page covers HTTP/2 multiplexing.
Deep Dive: how 20,000 bots reach 201 million requests per secondShow
201M / 20,000 ≈ 10,000 requests per second per bot. A HEADERS frame compressed by HPACK is about 9 bytes, plus a 9-byte frame header. A RST_STREAM frame is 13 bytes (9 header + 4 error code). So one request-and-cancel costs roughly 30 bytes on the wire. 10,000 per second × 30 bytes = 300 KB/s, about 2.4 Mbps per bot, which a cheap VPS sends easily. In HTTP/1.1, each new request on a connection requires the previous response or a new TCP and TLS handshake (several KB and a round trip), so the same bot would manage perhaps hundreds per second. The amplification comes from the protocol letting the client create server work without waiting for any server traffic. A defence that counts resets per connection bounds the work per connection. IP jails then bound connections per bot.
Lesson 31: SYN packet handling, the two queues behind every listening socket#
Assumptions. Cloudflare's servers face the open Internet and SYN floods of over 200 million packets per second. Linux SYN handling is subtle, and wrong tuning either drops real users or wastes memory on attack packets.
How Linux handles it. Every listening socket has two queues:
- SYN queue: half-open connections (a
struct inet_request_sock, 256 bytes each on kernel 4.14). The kernel sends SYN+ACK and retries it (tcp_synack_retries, default 5, last retransmit at about 31 s and final timeout at about 63 s with a 1 s initial RTO). An arriving ACK is checked against established connections first, then the SYN queue. A match becomes a full socket in the accept queue. - Accept queue: fully established connections waiting for the app's
accept(). - Sizing: both are capped by the
listen(fd, backlog)argument and bynet.core.somaxconn(Cloudflare uses 16,384).tcp_max_syn_backlogno longer caps the SYN queue on modern kernels. - Choosing the backlog: go bigger for high connection rates, long client RTTs (the SYN queue holds roughly "ACKs in flight", that is arrival rate × RTT), and
TCP_DEFER_ACCEPT. Go smaller so a flood does not consume memory.ss -n state syn-recvshows SYN queue use (for example 119 on port 80 and 78 on 443 on one server). - A slow app means a full accept queue. The kernel then drops new SYNs and ACKs and increments
ListenOverflowsandListenDrops. This is deliberate back-pressure: the client retransmits later, when the app may have caught up. Do not settcp_abort_on_overflow.ListenDropsis a global counter and can rise during sub-second stalls thatssmisses (Recv-Q is the current accept queue, Send-Q the backlog). Cloudflare wrote a SystemTap script to print exactly which SYNs were dropped. - SYN floods and SYN cookies. Before 1996, a little bandwidth of spoofed SYNs could fill a SYN queue and deny service to almost any server. SYN cookies make the SYN+ACK stateless: the server encodes the connection in its initial sequence number and verifies it when the ACK reflects it back. In the post, the 32 bits are laid out as 6 bits of time counter (t mod 32), 2 bits of MSS index (only 4 MSS values) and a 24-bit keyed hash of addresses, ports and time. They switch on automatically when the SYN queue is full (
tcp_syncookiesdefault; leave it). Counters:SyncookiesSent,SyncookiesRecv,SyncookiesFailed. - The cookie's cost. There is no room for TCP options (window scaling, SACK, ECN), and only a few MSS values. Performance falls unless TCP timestamps are on, because Linux then hides the options in the timestamp's low bits. Timestamps cost 12 bytes per packet and once leaked uptime. Cloudflare had them disabled at the time. SYN cookies also disable
TCP_SAVED_SYN,TCP_DEFER_ACCEPTand TCP Fast Open. - At Cloudflare scale, avoid cookies entirely. Answering 200M+ attack packets per second with SYN+ACKs would litter the Internet with replies to spoofed addresses. So SYNs are dropped at the firewall using p0f fingerprints compiled to BPF, deployed by Gatebot (Lesson 28). Linux 4.4 removed a lock that made cookies slow, so a well-tuned kernel can now send millions per second. That solves floods for most operators.
Overlooked constraints.
- Dropping is a feature. Dropping on overflow pushes back on the client's retransmit timers and protects a struggling app.
- Global counters hide local stalls. Micro-stalls of a fraction of a second overflow queues without showing in snapshots, so trace them.
- A defence can be a liability at scale. SYN cookies are ideal for one server, but harmful as a reflection source at 200M packets per second.
What Cloudflare sacrificed. By running with timestamps off, cookie-based connections would lose TCP options, which is acceptable because firewall-level dropping means cookies are rarely needed. Firewall dropping needs fingerprinting and automation (Gatebot) that most operators do not have. See TCP and UDP for the handshake itself.
Deep Dive: sizing the SYN backlog with Little's lawShow
The SYN queue holds connections between SYN+ACK sent and ACK received, so by Little's law its average occupancy = arrival rate × RTT. A server accepting 20,000 new connections per second from clients with a mean 150 ms RTT holds about 3,000 half-open entries. A 1,024 backlog would trigger SYN cookies under normal load, losing window scaling and SACK for real users. A 16,384 cap gives over 5x headroom. Memory: 16,384 × 256 bytes ≈ 4 MB per listening socket, which is trivial. Under a 1M SYN per second flood with no ACKs, entries last until the final timeout (about 63 s), so no practical queue survives. That is why floods are answered with cookies on a single server, or by dropping in XDP at Cloudflare's scale, not by growing the queue.
Lesson 32: Keyless SSL, splitting the TLS handshake across the planet#
Assumptions. Banks and other regulated customers wanted Cloudflare's edge (caching, DDoS protection, proximity) but could not hand over their TLS private keys. The 2014 design had to keep the key on the customer's premises, keep security equal to running TLS yourself, and still make connections faster than with no Cloudflare.
The TLS background the design depends on.
- TLS has two goals. Confidentiality comes from a symmetric session key (AES; older clients used 3DES or the now-insecure RC4). Authentication comes from a certificate whose private key the server proves it holds.
- Public-key operations dominate handshake cost. A laptop of that era did a few hundred RSA private operations per second against about 10 million AES operations.
- RSA handshake: ClientHello (version, 32-byte client random, cipher suites, SNI) → ServerHello (server random, chosen suite, certificate) → the client encrypts a random 48-byte pre-master secret with the server's public key → the server decrypts it → both derive the session key with a PRF → Finished messages. It needs one public-key operation and combines key exchange with authentication. But there is no forward secrecy: anyone who records traffic and later steals the key can decrypt it all.
- Ephemeral Diffie-Hellman (DHE or ECDHE) handshake: the server sends DH parameters (g^a) plus a signature over the handshake so far in ServerKeyExchange. The client replies with g^b, and both compute g^ab (the discrete logarithm problem keeps it secret). The key exchange is independent of the long-term key, so it gives forward secrecy. It also allows ECDSA certificates, which can beat RSA on speed. Cloudflare prefers DH whenever it can.
- Cipher suites name four choices: key exchange, authentication, cipher and integrity hash. For example, ECDHE-ECDSA-AES256-GCM-SHA384.
The key insight. The private key is used exactly once per handshake: to decrypt the pre-master secret (RSA) or to sign the DH parameters (DHE). So the handshake can be split geographically. Everything runs at the edge except that one operation, which is sent to a key server on the customer's infrastructure. Cloudflare changed NGINX and OpenSSL so the private-key operation is remote and non-blocking, so NGINX keeps serving other connections while it waits.
Protecting the oracle. A key server signs or decrypts for anyone who can reach it, so it is a cryptographic oracle.
- Mutual TLS: the key server accepts only client certificates from a Cloudflare internal CA, with X.509 Extended Key Usage restricting what each certificate may do. Customers can also allow-list Cloudflare's IP ranges.
- Cipher choice: only ECDHE-ECDSA-AES256-GCM-SHA384 or ECDHE-RSA-AES256-GCM-SHA384, so the channel itself has forward secrecy.
- Resistance to known attacks: constant-size responses defeat Bleichenbacher-style padding oracles. Timing safety depends on the hardened crypto library. HSM integration is optional, for defence against Heartbleed-class bugs.
- Audit: iSEC Partners and Matasano judged it equivalent to on-premise TLS.
- Deployment: key servers are stateless, so customers can run several, load-balance them with DNS and scale linearly.
Why it is faster anyway: geography plus resumption.
- Without Cloudflare, a San Francisco visitor to a London site pays two TLS round trips to London. With Keyless SSL, the handshake runs against the nearby San Jose edge, and only the key operation crosses to London, over a persistent, pre-warmed connection.
- Resumed sessions never touch the key server.
- Session tickets: the session key is encrypted under a ticket key and held by the client. A central generator rotates ticket keys every hour (Twitter was rotating every 12 hours), and each key is kept for a configurable time (default 96 hours) and then deleted. Keys are distributed globally within seconds over Kyoto Tycoon with mTLS replication, so any edge server worldwide can resume.
- Session IDs: the server must keep state, so encrypted session keys are cached in a per-data-center central store. Anycast sends returning browsers to the same data center, which covers about 99.99% of resumptions.
- Advanced resumption was turned on for all SSL customers. Cloudflare open-sourced strict upstream TLS verification and session tickets for NGINX, plus CFSSL (its CA tool) and the reference key server.
Overlooked constraints.
- Find the one step that needs the secret, and move only that step. Splitting at the narrowest point keeps almost all latency local.
- Remote operations need non-blocking I/O. A blocking OpenSSL call per handshake would have stalled the event loop.
- Resumption at scale is a distributed state problem. Ticket keys need secure global distribution and rotation (rotating keys keeps forward secrecy). Session IDs need a shared store per data center.
What Cloudflare sacrificed. The first handshake now depends on a remote key server's availability and latency, so a customer outage at the key server stops new full handshakes. Engineering complexity in NGINX and OpenSSL. A trusted internal CA and certificate controls to run. In return, customers keep custody of their keys. See security fundamentals for TLS basics.
Deep Dive: handshake latency with and without Keyless SSLShow
Use the post's example with RTTs (handshake numbers are the handbook's illustration): visitor to San Jose edge 5 ms, visitor to London 140 ms, San Jose to London 140 ms.
- Direct to London, TLS 1.2: TCP handshake 1 RTT plus TLS 2 RTTs = 3 × 140 = 420 ms before the first request.
- Keyless, first visit: TCP to the edge, 5 ms. TLS 2 RTTs to the edge, 10 ms, plus one key-server round trip on the warm connection, 140 ms. Total about 155 ms, then the request is served from cache, or by origin over a warm, pooled connection.
- Keyless, resumed: the abbreviated handshake is 1 RTT to the edge with no key server, so 5 + 5 = 10 ms.
The single long hop is paid once per new session, not per request. Returning visitors pay only local round trips.
Lesson 33: HTTP/3 from root to tip, semantics versus syntax#
Assumptions. By 2019 people were confused by names: SPDY, gQUIC, "HTTP/2 over QUIC" and then HTTP/3. Lucas Pardue's post builds a "Secure Web Timeline" of HTTP and TLS to explain how standards are actually made, and why HTTP/3 is simply a new HTTP syntax on IETF QUIC.
The key distinction. HTTP semantics are the shared concepts: methods, status codes, header fields and bodies, plus request and response. HTTP syntax is how those are turned into bytes on the wire. HTTP/0.9, 1.0 and 1.1 share text syntax over TCP. SPDY kept 1.1 semantics and switched to binary syntax, and keeping https:// URLs avoided adoption problems. As the IETF said in 2012, "HTTP/2.0" only means the wire format is incompatible with 1.x. The HTTP Core work then reorganised the specs into Semantics, Caching and HTTP/1.1 Messaging, so HTTP/2 and HTTP/3 are clearly just syntaxes of one set of semantics.
The lineage.
- HTTP
- 1991: HTTP/0.9.
- 1996: RFC 1945 (HTTP/1.0).
- 1997: RFC 2068 (HTTP/1.1).
- 1999: RFC 2616.
- 2007 to 2014: the HTTPbis refactor, 6 drafts and 27 revisions, ending in the RFC 723x series ("RFC2616 is Dead").
- SSL and TLS
- About 1995: SSL 2.0.
- 1996: SSL 3.0 (only written up as historic RFC 6101 in 2011).
- 1999: TLS 1.0 (RFC 2246, version number 3.1 because it is a minor SSL update).
- 2000: HTTP over TLS (RFC 2818).
- TLS 1.1 and 1.2 followed, then TLS 1.3, which took 28 drafts and became RFC 8446 in August 2018.
- SPDY and HTTP/2: SPDY v1 and v2 came in 2009–2010. The IETF chose the SPDY proposal in 2012 over two other submissions. After 18 drafts it became RFC 7540 (HTTP/2) in 2015, by then slightly incompatible with SPDY.
- gQUIC: Google's QUIC first carried SPDY v3 syntax in UDP datagrams and blurred the transport and application layers, so it supported only HTTP. It used QUIC Crypto in place of TLS and introduced 0-RTT resumption, later taken into TLS 1.3. Its "HTTP/2 over QUIC" serialised headers differently, so it was never wire-compatible with IETF HTTP/2.
- IETF QUIC: a 2015 Bar BoF, then the 2016 BoF in Berlin with hundreds attending. The IETF decided to separate the transport from HTTP and use a TLS-based handshake. It became a draft set of transport, TLS, loss recovery and HTTP mapping documents. "HTTP over QUIC" was renamed HTTP/3 at IETF 103 (draft 17, late 2018).
How the IETF works, briefly. "Rough consensus and running code". A Working Group is essentially a mailing list. There are three plenary meetings a year, plus interims and hackathons for interop testing. An Internet-Draft expires after 6 months unless revised, and its version resets to 00 on rename. An adopted draft gets an ietf name. RFCs are immutable, so a fix needs a new number that obsoletes or updates the old one. Cloudflare's part is the running code:
- SPDY: 2012 to 2018, deprecated when under 4% of clients wanted it.
- HTTP/2: since December 2015.
- TLS 1.3: since September 2016, two years before the RFC.
- SSLv3: disabled after POODLE.
- Universal SSL (2014) made these TLS-only protocols available to every site.
Overlooked constraints.
- Keep semantics stable while syntax evolves. That is why caches, proxies and apps did not need rewriting for each HTTP version.
- Layering matters for longevity. gQUIC's tight coupling sped early experiments but limited reuse. IETF QUIC is a general transport.
- Standards follow deployment. Experiments at scale (SPDY, gQUIC, early TLS 1.3) produced the data that shaped the RFCs.
What was sacrificed. Standardisation time (years of drafts). Compatibility between the experimental and final versions (SPDY against HTTP/2, gQUIC against QUIC), which forced deployers to run both for years. See HTTP and HTTPS.
Deep Dive: round trips to the first byte across versionsShow
With RTT = 100 ms and a fresh connection:
- HTTP/1.1 or HTTP/2 over TCP with TLS 1.2: TCP 1 RTT + TLS 2 RTT + request 1 RTT = 400 ms to the first response byte.
- Same with TLS 1.3: 1 + 1 + 1 = 300 ms.
- HTTP/3 over QUIC: the transport and TLS 1.3 handshakes merge into 1 RTT, plus the request, = 200 ms.
- QUIC 0-RTT resumption: the request rides in the first flight = 100 ms. 0-RTT data can be replayed, so servers accept only idempotent requests in it (see idempotency).
On a mobile link with 1% loss, TCP's single ordered byte stream stalls every multiplexed HTTP/2 stream when one packet is lost (head-of-line blocking). QUIC's per-stream ordering stalls only the affected stream. That gain, and connection migration across networks, is the subject of Lesson 34.
Lesson 34: The road to QUIC, what a new transport breaks#
Assumptions. QUIC aims to replace TCP plus TLS on the web, starting from the gQUIC that Google ran at scale. IETF QUIC has diverged from it in wire format, handshake and HTTP mapping. Cloudflare had to deploy it on an anycast, ECMP-balanced edge. The 2018 post is about what breaks when a transport changes.
What QUIC improves.
- Security built in, and faster setup. The transport handshake and the TLS 1.3 handshake are merged, so a connection takes 1 RTT where TCP plus TLS 1.3 take 2. QUIC keeps TLS's handshake messages but replaces the TLS record layer with its own framing. It also encrypts metadata such as packet numbers, so on-path observers cannot link a user's activity across paths after migration.
- Encryption against ossification. Middleboxes that parse protocol headers freeze them, which is why TLS 1.3 needed workarounds to get past old boxes. Encrypting almost everything leaves them nothing to depend on.
- No transport head-of-line blocking. HTTP/2 multiplexes streams on one TCP byte stream, so one lost packet stalls them all. QUIC streams are delivered independently, while sharing one handshake and one congestion controller.
What it breaks, and the fixes.
- Runs on UDP: this gets through middleboxes that drop unknown protocols, and lets QUIC live in user space, so browsers ship updates without OS upgrades. But UDP brings routing and abuse problems.
- NATs: a NAT tracks TCP bindings by watching SYN and FIN. For UDP it falls back to short idle timeouts, so a binding can change (NAT rebinding) and the server sees a new source port. Connection migration (for example from cellular to coffee-shop Wi-Fi) changes the 4-tuple on purpose. QUIC carries an opaque connection ID, so endpoints can identify the connection without the 4-tuple.
- Anycast plus ECMP: routers hash the 4-tuple, so after rebinding or migration, packets of one connection can reach a different server and the connection breaks. The fix is a smarter L4 load balancer in software that routes by connection ID (the post cites Facebook's Katran). Cloudflare's Unimog plays this role (Lesson 3).
- HPACK assumes ordered delivery. HTTP/2 header compression keeps a dynamic table that encoder and decoder update in order. QUIC streams can arrive in any order, so a request might refer to a table entry the server has not seen yet. gQUIC sent all headers on one stream, which brought head-of-line blocking back. QPACK gives each request its own stream and adds two unidirectional streams per peer, one for table updates and one for acknowledgements. An encoder may refer to a dynamic entry only after the decoder acknowledges it.
- Reflection and amplification: UDP source addresses can be spoofed. TCP's SYN and SYN+ACK are the same size, but a QUIC server's first flight carries a certificate chain much larger than the ClientHello. Three defences:
- The client's first packet must be padded to a minimum size, so it carries more bytes than it needs.
- Retry with an address-validation token, at the cost of an extra RTT.
- Shrink the response with ECDSA certificates and certificate compression (zlib or brotli, a gQUIC idea not then in TLS).
- UDP host performance: TCP has decades of kernel and NIC offloads, and UDP had few. UDP GSO (generic segmentation offload, many segments per syscall) and zero-copy sockets were in progress.
Overlooked constraints.
- Infrastructure assumes TCP. NAT timers, ECMP hashing and NIC offloads were all built for TCP. A new transport needs changes across the whole path.
- Independence across streams conflicts with shared compression state. QPACK trades some compression for no head-of-line blocking.
- Any UDP service must be designed against amplification from the start (see TCP and UDP).
What was sacrificed. CPU efficiency at first (user space, fewer offloads), an extra RTT when Retry is used, and some compression. The gains are faster setup, resilience to loss, migration and privacy.
Deep Dive: amplification factor and the anti-amplification limitShow
A ClientHello in a QUIC Initial packet is about 300 bytes of content but must be padded to at least 1,200 bytes. A server's first flight with an RSA certificate chain can be 4 to 6 KB. Without limits, the attacker's 1,200 spoofed bytes would trigger about 5,000 bytes toward the victim, an amplification of about 4x. The QUIC RFC caps a server at sending 3x the bytes received from an unvalidated address before it validates it (via a handshake reply or a Retry token). ECDSA chains of about 2 KB, or compressed certificates, keep the first flight under the 3,600-byte cap, so no extra RTT is needed. A large RSA chain hits the cap and stalls the handshake for an extra round trip. Certificate size directly affects handshake latency in QUIC.
Lesson 35: Building the 1.1.1.1 public resolver#
Assumptions. Cloudflare launched its first consumer service, a public recursive DNS resolver, on 1 April 2018. Its addresses were 1.1.1.1 and 1.0.0.1 (from APNIC, under a research agreement) and 2606:4700:4700::1111 and ::1001 for IPv6. The goals were to be the fastest public resolver, aiming to put everyone within 10 ms of a location, and to raise the privacy standard. Every new data center runs the resolver from day one (31 were added in March 2018 alone). Cloudflare already ran fast authoritative DNS for over 7 million properties and anycast for two of the 13 root server letters, and the resolver benefits from those authoritative servers being in the same buildings.
Privacy features.
- QNAME minimisation (RFC 7816): older resolvers sent the full name (www.cloudflare.com) to the root and the .com servers, although the root only needs to know ".com". The resolver now sends only the labels each level needs.
- Encrypted last mile: DNS over TLS (RFC 7858, port 853) and DNS over HTTPS, which lets browsers mix DNS into an HTTPS connection. DNSSEC protects integrity between resolver and authority, but not privacy to the user.
- Data policy: client IPs are never stored, and logs are deleted within 24 hours. Query names are used only for resolver improvements such as cache prefill and APNIC research after obfuscation.
Correctness and load.
- DNSSEC validation wherever zones are signed, with low verification cost.
- Aggressive negative caching (RFC 8198): from cached NSEC records in signed zones, the resolver can prove a name does not exist without asking again. At the time the root and 1,400 of 1,544 TLDs were signed.
- Negative Trust Anchors: DNSSEC is unforgiving, so a domain with a detected and verified DNSSEC error would be unresolvable. Validation is turned off for that domain until its operator fixes it.
Build versus buy. Writing a resolver was rejected for complexity and time to market. After shortlisting open-source options, Cloudflare built on Knot Resolver (CZ.NIC). It had the most needed features and an OpenResty-like modular design, and it adds software diversity to the DNS ecosystem. Its original lead developer worked on Cloudflare's DNS team.
Speed.
- A cache hit costs only the client-to-resolver round trip.
- A miss must walk the hierarchy from the root, and that is slower from places far from authorities, such as Buenos Aires compared with Frankfurt. Popular names are prefilled out of band.
- Cache hit ratio falls as nodes per data center rise: with hundreds of servers, a repeated query probably hits a different, cold cache. The usual fix is a caching load balancer in front, but that is a SPOF, and Cloudflare does not build SPOFs. So it built a distributed cache shared across the data center.
Overlooked constraints.
- Scale-out hurts caches. More nodes means more cold caches unless the cache is shared, and the shared cache must not become a SPOF.
- Privacy has protocol parts and policy parts. Minimisation and encryption limit what leaves, and log policy limits what stays.
- Strict validation needs an escape hatch. Negative trust anchors keep one operator's DNSSEC mistake from cutting off users.
- Famous IPs carry history. 1.1.1.1 was widely misused as a placeholder address in private networks and equipment, which APNIC's research had measured. That is the "adventures" the post hints at.
What Cloudflare sacrificed. Some speed for privacy (minimisation can add queries for deep names), log-based debugging (24-hour deletion, no IPs), and control (it builds on and contributes to an external codebase). See DNS, and Lesson 48 for the July 2025 1.1.1.1 outage.
Deep Dive: why per-node caches hurt hit ratio, and what sharing gainsShow
Suppose a data center has N = 100 resolver nodes and a name is queried q = 50 times per TTL window (300 s) in that data center, with queries hashed randomly to nodes (handbook's illustration). With private caches, each node sees about 0.5 queries per window, so most queries are the first on their node, which is a miss. The expected number of distinct nodes hit is N × (1 − e^(−q/N)) ≈ 100 × (1 − e^(−0.5)) ≈ 39, so 39 misses out of 50, a 22% hit ratio. With a shared data-center cache, there is 1 miss and 49 hits, a 98% hit ratio. A miss that walks root, TLD and authority can cost 50 to 200 ms, while a hit costs the client RTT (a few ms). So sharing the cache cuts mean latency for this name roughly 10x. The same maths motivates consistent hashing of query names onto nodes (see consistent hashing), which turns N caches into one logical cache without a central box.
Lesson 36: RPKI, signing who may originate a route#
Assumptions. BGP (Border Gateway Protocol) lets any network announce any prefix, and checking is done out of band. Leaks and hijacks are common:
- 1997: AS7007 re-announced 72,000+ routes.
- 2008: a Pakistani ISP's internal YouTube block leaked to the world.
- 2017: a Russian ISP leaked 36 prefixes of Mastercard, Visa and banks.
- 2018: Amazon's DNS was hijacked to steal cryptocurrency.
Each one exposed a peer or transit provider that did not filter. In 2018 Cloudflare committed to leading RPKI deployment.
The building blocks.
- ASN: a network's identity (Cloudflare is AS13335). ASNs were 16-bit (65,536 values), and are now 32-bit.
- Prefixes: CIDR blocks (the post's university uses documentation space 10.0.0.0/8 and 2001:db8::/32 with AS65099, behind an NREN upstream AS65001).
- IRR (Internet Routing Registry): route and aut-num objects in RADB, ALTDB or RIR databases. The upstream builds prefix filters from them and lists customers in an as-set. But IRR data is unsigned, often stale or mistyped, and anyone can create objects.
- BGP config does not mention IRR or RPKI. Correctness depends on the upstream filtering.
RPKI (RFC 6480).
- Who signs: the five RIRs (AFRINIC, APNIC, ARIN, LACNIC, RIPE NCC) are the trust anchors (TAs). A resource holder logs into its RIR and signs a ROA (Route Origin Authorization): "this prefix may be originated by this ASN".
- Format: ROAs are CMS-wrapped objects built on X.509 certificates with RFC 3779 IP and AS extensions.
- The key difference from IRR: the same body that allocated the resource holds the CA, so you can only sign your own resources. If the allocation lapses (for example dues are not paid), the ROA is lost.
- Coverage: because of inter-RIR transfers, each RIR's TA now covers all address and AS space, with RIR-specific certificates below it.
- Deployment pattern: routers do no cryptography. A validator server processes the TAs, certificate tree and ROAs, and answers the router's valid or invalid queries over the lightweight RTR protocol (RFC 6810, updated by RFC 8210). Tools then included rtrlib, the RIPE validator (Java) and NLnet Labs' Routinator (Rust). The post judged operational software still immature.
- Limits: RPKI secures only the origin, not the path (a forged path with the right origin still passes, and path security needs BGPsec or later work).
- Legal friction: there are five roots, since a single IANA root never happened. ARIN required indemnification. Some RIPE members feared a Dutch law-enforcement order could revoke a non-Dutch network's certificate.
- Industry norms: MANRS (Internet Society) promotes filtering, anti-spoofing, coordination and validation, but Cloudflare judged it "too polite". IXPs were starting to filter route servers with RPKI, and Dutch operators were early adopters.
Overlooked constraints.
- Filtering is done by your neighbours. Your own signatures help only if others validate, so adoption is a collective-action problem, and that is why Cloudflare campaigned publicly.
- Keep crypto off the router control plane. The validator plus RTR split puts trust maintenance on servers.
- Who runs the trust anchor is a governance question with legal consequences, not only technical ones.
What Cloudflare sacrificed. Effort and risk: strict validation means dropping invalid routes, which can cut off a real network whose ROA is wrong. Unknown routes (no ROA) are still accepted, so protection is partial until adoption grows. Lesson 53 shows a route leak that RPKI-style filtering would have contained.
Deep Dive: what origin validation does and does not stopShow
Take a prefix 203.0.113.0/24 with a ROA allowing AS64500 with a maximum length of /24.
- Accidental mis-origination (AS64511 announces 203.0.113.0/24): RPKI-invalid. Validating networks drop it, and the hijack is contained to the ones that do not validate.
- More-specific hijack (AS64511 announces 203.0.113.0/25): invalid, because it is longer than the max length. This is important because more-specific routes win in routing.
- Path forgery (AS64511 announces the /24 with path "64511 64500", pretending to be a neighbour): valid origin, not caught. Path validation (BGPsec, or later approaches like ASPA) is needed.
- Route leak (a customer re-announces a provider's routes to another provider with the original origin): valid origin, not caught by ROAs, which is why leaks like the one in Lesson 53 need max-prefix limits and customer filters too.
Origin validation therefore removes the most common accidents. Coverage grows with both ROA creation (signers) and drop-invalid policy (validators), and you need both.
Lesson 37: The July 2, 2019 outage, one regular expression and eleven contributing causes#
Assumptions. WAF (web application firewall) Managed Rules must respond to new vulnerabilities within hours. A proof of concept is often on GitHub soon after disclosure (for example a SharePoint vulnerability in May 2019). The team handled 476 rule change requests in 60 days, about one every 3 hours. Rules are shipped through Quicksilver, which distributes about 350 changes per second with a p99 of 2.29 s to every machine (Lesson 9). The Lua WAF used PCRE, a backtracking regex engine with no runtime limit.
What happened.
- 13:42 UTC: an XSS rule change was deployed in simulate mode, which logs and does not block, but still executes the rule on all traffic. The regex contained the pattern
.*(?:.*=.*). - Within seconds, CPU reached nearly 100% on every core serving HTTP and HTTPS worldwide. Front-line servers that still had spare CPU returned 502s because they could not reach the busy HTTP processes. 80% of traffic was lost.
- 14:00: the WAF was identified (CPU profiles, strace, error logs), and an attack was ruled out.
- 14:02: a global terminate, a built-in kill switch for one component worldwide, was proposed. But Cloudflare Access was down, so engineers could not log into the internal control panel. Some had been locked out by a security feature that disables credentials not used recently. Jira and the build system were also reachable only through a rarely used bypass.
- 14:07: the kill was executed. 14:09: traffic and CPU were back. The outage lasted 27 minutes.
- 14:52: the WAF was re-enabled after negative and positive tests in one city, with paying customers' traffic moved away first.
How the release process normally works, and why the WAF skipped it. Software goes from BitBucket to TeamCity build and tests, then review and a Change Request approved by a manager. It then rolls through DOG (an employee-only PoP), PIG (some free-customer traffic) and three Canary PoPs (free and paid), and only then goes global. This takes hours to days. WAF rules were exempt by design because of urgency, and the SOP allowed a global push even for non-emergency rules. Every step that did happen was "correct": PR, approval, CI green, Change Request with rollout and rollback plans.
The contributing causes, as listed in the post:
- A regex that could backtrack enormously.
- A CPU-limit protection removed by mistake weeks earlier in a refactor meant to reduce WAF CPU use.
- An engine with no complexity guarantee.
- A test suite that could not detect excessive CPU.
- An SOP that allowed a global push for a non-emergency rule.
- A rollback that needed two full WAF builds.
- A global-traffic-drop alert that fired too slowly.
- A status page that was updated late.
- Internal tools that depended on the broken edge, with a bypass nobody practised.
- Expired credentials.
- A customer dashboard and API that also ran through the edge.
Fixes.
- Restore the CPU protection.
- Manually review all 3,868 rules.
- Add performance profiling to the rule test suite.
- Move to RE2 or the Rust regex engine, which run in linear time.
- Staged rollouts for rules, keeping an emergency global path for active attacks.
- An emergency way to run the dashboard and API off Cloudflare's edge.
- An automated status page.
- Replace the Lua WAF with the new firewall engine.
Why the regex exploded. Simplify the pattern to .*.*=.*. Matching x=x takes 23 steps with backtracking. With 20 x's after the "=" it takes 555 steps. Twenty x's with no "=" fail after 4,067. Add a trailing semicolon (.*.*=.*;) and x= followed by 20 x's takes 5,353 steps, growing super-linearly with input. Lazy quantifiers help the first case (11 steps) but not the catastrophic one. The real fix dates to Ken Thompson's 1968 paper "Regular expression search algorithm": compile the expression to an automaton and track all active states at once, so each input character is processed once, in linear time with no backtracking.
Pattern simplified from the rule: .*.*=.*
Input Backtracking steps (PCRE-style)
x=x 23
x=xx 33
x=xxx 45
x= + 20 x 555
20 x, no = 4,067 (fails)
With trailing ';' .*.*=.*; on x= + 20 x: 5,353
Thompson NFA simulation: one pass, steps proportional to input lengthOverlooked constraints.
- Fast config is deployment. A rule is code that runs on every request, so it needs the same staged rollout as software. The speed that makes Quicksilver valuable made the bad rule global in seconds.
- "Simulate" is not "safe". Observation modes still use resources.
- Your recovery tools must not depend on the thing that is broken. Access, Jira and the dashboard all ran through the failing edge.
- Performance is a correctness property for rules. Tests checked only that rules matched and blocked correctly, not how much CPU they cost.
- Removed guardrails are invisible. A refactor deleted the protection without anyone noticing.
What Cloudflare sacrificed. Some response speed for non-emergency rules (now staged), and some regex expressiveness (RE2 and Rust regex do not support backreferences or lookaround). In return, matching has a guaranteed cost. See incident management and postmortems for the blameless-postmortem method this post exemplifies.
Deep Dive: why backtracking is exponential and Thompson's construction is linearShow
A backtracking engine explores one path at a time through the pattern and retries on failure. For .*.*= on n characters, the two stars can split a prefix in about n²/2 ways, and each split rescans the rest, giving roughly cubic work for this pattern. Nested quantifiers like (a+)+ give 2^n. Thompson's method keeps a set of NFA states (at most m, the pattern length) and advances the whole set by one character at a time, so the cost is O(n × m) with no input-dependent blow-up. For a WAF scanning a 2 KB header with a 100-state pattern, that is at most 200,000 steps, about 0.1 ms. The 2019 pattern on a long attacker-chosen input could take seconds per request, and an attacker could have triggered that on purpose. A linear-time engine is therefore a security property, not only a performance one: it removes ReDoS (regular-expression denial of service) as an attack.
Lesson 38: The July 17, 2020 backbone outage, one line that attracted everything to Atlanta#
Assumptions. Cloudflare runs a private backbone of leased lines between data centers, for example carrying traffic from San Jose to a New York origin, avoiding congested public paths. Routers exchange routes over iBGP, and local preference (a BGP attribute shared within the network, where higher wins) decides which path is preferred.
What happened (UTC).
- 20:25: the Newark–Chicago link failed, and Atlanta–Washington started to congest.
- To relieve Atlanta, an engineer edited the Atlanta router's export policy. In place of deactivating a term, the change deactivated the term's prefix-list match condition.
- With no condition, the term matched all routes. Atlanta then advertised every BGP route it knew into the backbone with local preference 200, while each site's own server routes had local preference 100. Higher wins, so traffic from across the backbone for local servers went to Atlanta.
- 21:12 to 21:39: Atlanta was overwhelmed. About 50% of network traffic dropped, across about 20 locations in North America, Europe, Russia and Brazil. Data centers off the backbone were unaffected.
- 21:39: the Atlanta router was removed from the backbone. Service was restored by 21:47.
- Until 22:10: core congestion dropped some logs and metrics, while the edge served normally.
policy-statement 6-BBONE-OUT term 6-SITE-LOCAL
from prefix-list 6-SITE-LOCAL <- this line was deactivated
then local-preference 200
community add SITE-LOCAL-ROUTE ATL01 NORTH-AMERICA
accept
Intended: deactivate the whole term.
Actual: term now matches every route -> all routes exported at pref 200.Fixes.
- A maximum-prefix limit on backbone BGP sessions: a session that suddenly receives far more routes than normal shuts down. That would have isolated Atlanta, and the network is designed to work without the backbone.
- Change the local preference of local server routes so no remote site can outrank them.
Overlooked constraints.
- Removing a condition widens a rule. In policy languages, deleting a match line makes the rule match everything, the opposite of the intent.
- Preference values are a global contract. One site exporting a higher preference than local routes can capture the whole network. Local routes should win by design.
- Blast-radius limits belong in the protocol session. A max-prefix limit is a circuit breaker on routing.
- Emergency changes made under congestion skip normal review. Most config outages happen during a response to another problem.
What Cloudflare sacrificed. The convenience of free-form manual router edits during incidents. Max-prefix limits can, rarely, tear down a session when legitimate route counts grow, so they must be maintained.
Deep Dive: how local preference makes a single router a black holeShow
BGP best-path selection on Junos and most vendors compares, in order: highest local preference, then shortest AS path, then origin, MED, and eBGP over iBGP. Local preference is compared first and is carried on all iBGP sessions in the AS. So when Atlanta exported a server prefix of San Jose's at preference 200, San Jose's own router compared 200 (via Atlanta) with 100 (direct from its compute nodes) and chose Atlanta. No later tie-breaker could rescue it. The fixes stop either the cause or the spread. Raising local-route preference above any value a backbone peer can export removes the capture. Max-prefix limits stop the spread: if a session normally carries 500 prefixes, a limit of 1,000 trips within milliseconds of a full-table leak of tens of thousands of routes. The same pattern appears in the 2022 outage (Lesson 39) and the 2019 Verizon leak (Lesson 53).
Lesson 39: The June 21, 2022 outage, term order in the busiest 4% of locations#
Assumptions. Over 18 months Cloudflare converted its 19 busiest data centers (Amsterdam, Atlanta, Ashburn, Chicago, Frankfurt, London, Los Angeles, Madrid, Manchester, Miami, Milan, Mumbai, Newark, Osaka, São Paulo, San Jose, Singapore, Sydney, Tokyo) to the Multi-Colo PoP (MCP) design. This is a Clos network with an added spine layer, so parts of a data center can be drained for maintenance. These sites were 4% of locations but about 50% of requests.
What happened. A change standardised BGP communities on site-local prefixes. Site-local prefixes let servers talk to each other and reach customer origins, and give engineers direct access. The change had a dry run, a staged rollout and peer review. On the leaf routers it simply added communities. On the spines, the diff also reordered terms in the AGGREGATES-OUT policy: the 4- and 6-ADV-SITE-LOCALS terms moved below the REJECT-THE-REST term. Policy terms are evaluated in order, so site-local prefixes were now rejected and withdrawn from the Internet.
- 03:56: the first locations got the change (old architecture, no impact). 06:17: busy non-MCP sites, no impact.
- 06:27: the rollout reached the MCP spines, and all 19 locations went offline.
- 06:32: incident declared. 06:58: root cause understood. Engineers had to use backup access because the withdrawn prefixes included their own access paths.
- 07:42: reverts complete. It took longer because engineers walked over each other's reverts, undoing previous reverts and briefly bringing the problem back. 08:00: incident closed.
- A second effect: without site-local prefixes, Multimog (the MCP version of Unimog) could not forward between servers. Small compute clusters received as much traffic as the largest ones and overloaded.
policy-statement AGGREGATES-OUT (spines, after the change)
term ... ADV-FREE, ADV-PRO, ADV-BIZ, ADV-ENT, ADV-DNS
term REJECT-THE-REST then reject <- evaluated first now
term 4-ADV-SITE-LOCALS (moved below) <- never reached
term 6-ADV-SITE-LOCALS (moved below) <- never reached
In the diff, "!" marks reordered terms, easy to misread as unchanged.Fixes.
- Process: staged rollouts must include an MCP site early, not only at the last step.
- Architecture: redesign the policy so the terms cannot be misordered.
- Automation: enforce stagger rules for network config, plus an automatic commit-confirm rollback. The router reverts a change unless an operator confirms it within a time window, so a change that cuts off access reverts itself.
Overlooked constraints.
- A staged rollout is only as good as its order. Stages that leave out the new architecture until last test nothing about the risky part.
- Order-sensitive config needs a semantic diff. A reorder looked like a no-op in the text diff. Check the evaluated result, meaning which prefixes would be advertised.
- Concentrating traffic concentrates risk. The resilience project made 4% of sites carry half the load.
- Coordinate during incident response. One person owns the change log, otherwise parallel reverts collide. See incident management.
What Cloudflare sacrificed. Rollout speed for network changes (more stages, MCP-first), and some flexibility in policy structure. Commit-confirm adds operator steps.
Deep Dive: commit-confirm as an automatic dead-man's switchShow
With commit-confirm, an operator commits a change with a timer (for example 5 minutes). If the operator does not issue a confirming commit before it expires, the router rolls back by itself. In 2022, the change that withdrew site-local prefixes also cut engineers' direct access, so they could never have confirmed it. With commit-confirm the spines would have reverted about 5 minutes after the 06:27 push, cutting the incident from 75 minutes to under 10 for every site at once, and with no humans racing each other's reverts. The general principle: any change that can sever your ability to undo it needs an automatic undo. Pair it with "known-good" verification, where automation checks the advertised prefix count after a commit and refuses to confirm if it drops.
Lesson 40: Cloudbleed (February 2017), a dormant parser bug woken by a migration#
Assumptions. Many edge features rewrite HTML as it streams through NGINX. They insert analytics tags, rewrite http links to https, obfuscate email addresses and hide parts of a page from bad bots. They used an old HTML parser generated by Ragel, a state-machine compiler that emits C. A new streaming HTML5 parser, cf-html, was gradually replacing it. Both run as NGINX filter modules that pass buffers along a chain.
What happened. On 17–18 February 2017, Tavis Ormandy of Google Project Zero reported corrupted pages coming back through Cloudflare. Edge servers were reading past the end of a buffer and returning adjacent memory: cookies, auth tokens, POST bodies, API JSON, OAuth tokens. Because the infrastructure is shared, the leaked data could come from other customers' requests. Search engines had cached some of it.
- Peak exposure: 13–18 February, about 1 in 3,300,000 requests (0.00003%).
- Earliest possible leak: 22 September 2016, when Automatic HTTPS Rewrites moved to cf-html.
- Mitigation: the first fix took 47 minutes, using the Email Obfuscation "global kill" flag. Every feature has one, and it works worldwide in seconds. The full fix was done in under 7 hours, against an industry norm of about three months for such fixes.
- A feature with no switch: Server-Side Excludes was so old it had no kill switch. One had to be built and deployed, which took about three hours.
- Clean-up: with Google, Yahoo, Bing and others, the team found and purged 770 cached URIs across 161 domains. Public disclosure was held back until the caches were scrubbed.
- What did not leak: customer TLS private keys, because TLS was terminated in a separate NGINX instance with its own heap. What did leak was the key used for machine-to-machine encryption (Cloudflare had encrypted all internal links since 2013) and a few internal auth secrets.
Root cause. Ragel's generated code tests for the end of the buffer with an equality check. In an error action for a malformed attribute at the end of a page (for example, a document that ends inside a script type= tag, seen on about 0.06% of sites), the handler jumped to the next state without first stepping the pointer back one character (Ragel's fhold). The pointer moved to one past the end, the equality test never matched, and parsing continued into unrelated memory. A check with greater-or-equal would have caught it.
/* generated end-of-buffer test: equality only */
if ( ++p == pe )
goto _test_eof;
/* error action missing fhold (p--): p reaches pe + 1, test never fires */
/* hardening added afterwards: every pointer read checked */
#define SAFE_CHAR (... if (!(p < pe)) { log "tried to access char past EOF"; return NGX_ERROR; } *p ...)Why it appeared after years. The bug had been in the old parser for years. The error branch only runs when the parser knows it is on the last buffer (NGINX's last_buf flag). With only the old parser, the last data buffer arrived with last_buf = 0, followed by an empty final buffer that the parser never saw. So the error branch never ran. When cf-html was added to the same chain, the buffering changed: the final data buffer now carried last_buf = 1. A leak needed all of these at once:
- the page ends in a malformed script or img tag;
- the buffer is under 4 KB (otherwise NGINX crashed);
- Email Obfuscation is on, or another new-parser feature is combined with an old-parser feature.
Email Obfuscation was partly moved to the new parser on 13 February, which is why exposure peaked after that date.
Response pattern.
- Fuzz the generated code.
- Build test cases from malformed pages seen in the wild.
- Manually review the generated code.
- Add checks on every pointer access, logged centrally, so each log line counts a request that would have leaked.
The post cites IBM research from the 1960s and 70s on "error-prone modules": bugs cluster, so one serious bug in a module means you should look for more there.
Overlooked constraints.
- Migrations change the environment of old code. The new parser was carefully reviewed. The old parser broke because its assumptions about buffers changed.
- Shared memory means a shared blast radius. In a multi-tenant process, one tenant's bug can expose another tenant's data. Process isolation (the separate TLS heap) is what kept private keys safe.
- A kill switch per feature is a key incident tool, and features that predate the practice are the gap.
- Disclosure has a duty-of-care order: clean up third-party caches before announcing, or attackers will search them.
What Cloudflare sacrificed. Some performance (bounds checks on every character) and the reuse of old generated code. A fuzzing programme for legacy software costs ongoing engineering time. See security fundamentals.
Deep Dive: why equality bounds checks are fragile and what fixes themShow
A loop that advances a pointer by exactly one each step can safely stop on p == end. Any path that advances by two, or skips a decrement, jumps over end, and the check never fires again. Defences, from weakest to strongest:
- Use
p >= endeverywhere, so any overshoot stops. - Wrap each dereference in a checked macro, as with SAFE_CHAR. This costs one predictable branch per byte, under 1% on modern CPUs thanks to branch prediction (the macro used
__builtin_expect). - Use a memory-safe language, where slices carry their length and every index is checked or proven safe. This is one reason Cloudflare's later HTML rewriter (lol-html) and proxy work moved to Rust (Lesson 6).
- Isolate secrets in separate processes, so even a successful over-read sees only that process's heap.
In numbers: 1 in 3.3 million requests sounds tiny, but at roughly 5 million requests per second in 2017 (handbook's illustration) it is more than one leaking response per second.
Lesson 41: The November 2023 control plane and analytics outage, a data center that failed in an untested way#
Assumptions. The control plane (dashboard, APIs) and analytics ran mostly in three independent data centers around Hillsboro, Oregon. They were far enough apart to avoid shared disasters, and close enough to run active-active clusters that sync continuously. The design target was that losing any one facility is survivable. Logging was deliberately not in the HA cluster, because logs queue at the edge, and delayed analytics was considered acceptable. The data plane (the edge network) does not depend on the core for serving traffic.
What happened.
- 08:50 UTC, Nov 2: a utility (PGE) maintenance event took down one power feed to PDX-04, the largest facility, run by Flexential. PDX-04 held the biggest analytics cluster and more than a third of the HA cluster's machines. It was also the default home for services not yet onboarded to HA. Flexential ran its generators alongside the remaining feed and did not tell Cloudflare. Cloudflare's monitoring could not see the power source.
- About 11:40: a ground fault on a 12,470 V transformer tripped protection that also shut down all ten generators. The UPS batteries, rated for about 10 minutes, began failing after about 4 minutes.
- 11:44: Cloudflare's routers there went dark. Generator restart was slowed for three reasons: the generators needed manual restarts, the access-control system was not on battery backup, and the overnight staff were security plus a technician only a week into the job.
- 12:28: Flexential sent its first notice to Cloudflare.
- 12:48: generators restarted, but Cloudflare's circuit breakers were faulty and replacements had to be sourced.
- 13:40: Cloudflare decided to fail over to its European disaster recovery sites, and the first services came up at 13:43. A thundering herd of retried API calls then overwhelmed them, so rate limits were added (see cache failure modes for the same herd pattern).
- 17:57: the services that had moved were stable.
- 22:48: clean power was confirmed. The CEO sent the team to rest before failing back, delaying recovery to reduce the risk of tired mistakes.
- Nov 3: a full bootstrap of the facility. Power had been cycled several times, so server state could not be trusted. Rebuilding the configuration-management servers took 3 hours. Each server then took 10 minutes to 2 hours, with dependency ordering between services.
- 04:25 UTC, Nov 4: fully restored. Traffic through the network was never affected. Logpush logs from the event were lost, and datasets not replicated to the EU have gaps.
What failed in the design.
- A subset of services that were "on HA" depended on Kafka and ClickHouse, which existed only in PDX-04.
- Some newer products were never onboarded to HA, because GA (general availability) did not require it. Examples are Stream uploads and some APIs, and some needed manual DR setup, such as Magic WAN.
- The tests had removed each of the other two facilities, and the HA portion of PDX-04, but never the whole of PDX-04.
Remediation, called "Code Orange" (after Google's Code Yellow/Red, where most engineering moves to one crisis):
- Move control-plane configuration onto the distributed network, so it works with all core facilities offline.
- Every GA product must use the HA cluster, with no facility-specific dependencies, and a tested DR plan.
- Blast-radius tests and chaos tests that remove each whole core facility.
- Re-audits of facilities.
- A logging DR plan with zero dropped logs even if every core site fails.
Overlooked constraints.
- Redundancy you have not tested is a hypothesis. The one test that would have shown the hidden dependencies, losing all of PDX-04, was never run.
- Dependencies decide whether a service is HA, not where it runs. An HA service calling a single-site Kafka is single-site.
- Vendor signals matter. A generator failover with no notice removed a window for proactive draining. Monitor power source and UPS state if you can.
- Recovery is slower than failure. Power fails in seconds. Restoring a site means bootstrapping configuration management and then thousands of servers in dependency order, which took over a day.
- DR sites face a herd on arrival. Plan admission control for failover.
What Cloudflare sacrificed. Product velocity: GA now requires HA and tested DR, and Code Orange diverted most engineering for months. Running everything multi-site costs more hardware.
Deep Dive: finding hidden single-site dependencies before the data center doesShow
Three practical techniques, all implied by the remediation list:
- Dependency graph from traffic. Record every service-to-service call (service-mesh or eBPF connection logs), label each endpoint by facility, and compute, for each HA service, whether some path reaches a node that lives in only one facility. That is a reachability query on a graph with perhaps 2,000 services, which runs in seconds.
- Whole-site game days. Black-hole a facility at the network edge (not by shutting it down) for 30 minutes, with a quick undo. This finds dependencies that only appear on real traffic.
- Failure-mode budgets for GA. Require each product to state its behaviour when each core site and then all core sites are gone: degrade, queue or fail. Test that statement automatically.
On the numbers: the HA cluster survives losing one of three sites if each site carries at most half the load, since 2 × 50% = 100%. PDX-04 carried "more than a third", so the remaining two needed headroom of at least 50% over normal use. They had it. The failure was not capacity but the dependencies.
Lesson 42: The October 30, 2023 Workers KV outage, a deploy tool returning the wrong environment#
Assumptions. Workers KV, Cloudflare's globally distributed key-value store (Lesson 12), had become, in the post's own words, "organically" the base for many first-party products. It stores configuration, routing lookups, static asset bundles and auth state for Pages, Access, WARP/Zero Trust, Images, single-file purge, AI Gateway, Waiting Room, Turnstile and the dashboard's feature flags. KV releases used a progressive deployment tool that moves production to a new version in percentage steps.
What happened (UTC).
- 18:58: a progressive rollout of a new KV build started.
- 19:29: the tool's "list production builds" call also returned staging builds, a latent multi-tenancy bug. Production was pointed at a script that existed only in the staging account.
- 19:40: the rollout continued. Some traffic went to the wrong destination, alerts fired, and the team decided to roll back.
- 19:54: the rollback through the same tool made traffic fail at scale. KV answered every get, put, delete and list with HTTP 401 Unauthorized, because the target version was not authorised for production. It did this even for keys cached locally.
- 20:15: engineers used break-glass access to edit the deployment routes by hand back to the last known good build. 20:31: recovered, after 37 minutes of impact.
Why the rollback took 21 minutes. Access validates user JWTs using KV. With KV down, the dashboard and the CI system's authentication were down too. Automatic rollback through CI had been tested, but it could not get the secrets it needed.
Each product failed differently, by its own design:
| Product | Behaviour |
|---|---|
| Pages | HTTP 500 for all hosted sites |
| Access | New logins failed, so did the certs endpoint and posture checks |
| Waiting Room | Failed open (users let through), then queued on recovery |
| Turnstile and Challenge Pages | Failed closed: widget could not load, challenged users blocked |
| Single-file purge | Partially down; sites with locally cached config were fine |
| Deployed Workers not using KV | Unaffected |
Fixes.
- Move KV onto the standard Workers deployment model with automated impact detection and recovery.
- The rollback must hold a known good deployment ID and must work with Access down.
- Pre-checks on version and environment parameters, so a staging build cannot reach production.
- Make the progressive deployment tool multi-tenant safe.
Overlooked constraints.
- Internal platforms become critical dependencies without anyone deciding it. Every team that chose KV for good reasons added to one shared blast radius.
- The rollback path must not share dependencies with what it rolls back. This repeats the 2019 lesson (Access down during the WAF outage, Lesson 37) with a different component.
- Fail-open versus fail-closed is a per-product decision and should be deliberate. Waiting Room opened its gates, while Turnstile locked users out. Neither was planned for a KV outage.
- Deploy tooling is production code. A list API that leaked across environments was the root cause.
What Cloudflare sacrificed. Speed of ad-hoc internal deploys (more pre-checks, standard pipelines) and the convenience of building every product on KV without isolating critical paths. See resilience patterns for fail-open and fail-closed choices and serverless for the Workers model.
Deep Dive: a dependency budget for platform servicesShow
When a platform such as KV underpins N products, the expected outage cost of the platform grows with N. Suppose KV is available 99.99% of the time, which allows about 52 minutes of downtime per year. Each product that hard-depends on KV inherits that 52 minutes on top of its own budget. Ten products in a chain where each step needs KV multiply the exposure, because availabilities multiply: 0.9999 raised to the 10th is about 99.9%, roughly 8.7 hours a year. Mitigations:
- Serve last-known-good. Use a local copy if the platform returns errors. KV's 401s were returned even for locally cached keys, which removed this cushion.
- Classify dependencies as hard or soft, and give soft ones timeouts and defaults.
- Keep the control path (auth, CI, rollback) off the platform entirely, with a static or out-of-band credential path.
Serving cached values when the origin fails is what cache failure modes calls "stale-if-error".
Lesson 43: The June 27, 2024 1.1.1.1 incident, a hijack and a leak at the same time#
Assumptions. 1.1.1.1 is announced by Cloudflare (AS13335) as 1.1.1.0/24 via anycast. Its ROA (Lesson 36) authorises origin AS13335 with a max length of /24. By convention the default-free zone (DFZ) accepts nothing more specific than /24 for IPv4. Because 1.1.1.1 was long used as a lab or test address, it attracts stray configurations more than most addresses.
Two background mechanisms.
- Hijack via longest-prefix match. If any network announces 1.1.1.1/32, routers that accept it prefer it over the /24, because the most specific route wins. Traffic then ends at whatever device that network bound 1.1.1.1 to.
- Route leak (RFC 7908 "type 1"). A customer re-advertises a route from one provider or peer to another provider. BGP is a business-policy engine: transits give customer routes higher local preference than peer routes, and often prefer private interconnects (PNIs) over IX routes. So a leaked path through a paying customer can beat Cloudflare's direct route, even though Cloudflare peers with more than 13,000 networks.
What happened (UTC).
- 18:51: AS267613 (Eletronet) began originating 1.1.1.1/32.
- 18:52: AS262504 (Nova) leaked 1.1.1.0/24 upstream to AS1031 (Peer-1 Global Internet Exchange), which spread it to IX peers and route servers. At the same time, a Tier 1 provider accepted the /32 as an RTBH (remote-triggered blackhole) route, dropping all its customers' traffic to 1.1.1.1.
- 20:03: Cloudflare raised the incident. 1.1.1.1 was unreachable from more than 300 networks in 70 countries, though only a small share of users (under 1% in the UK and Germany).
- 20:08 and 21:56: Cloudflare disabled peering with AS267613 at two locations.
- 20:10 and 22:16: Nova leaked again via new paths. Some traffic reached Cloudflare in São Paulo with high latency. By then the /32 blackholing had stopped.
- 02:28 Jun 28: the leak was fully fixed.
Users in the US and Germany were seen hitting Brazilian data centers. The gaps between traffic spikes were blackholed periods, and the spikes were route flaps that briefly let traffic through.
How Cloudflare diagnosed it. It used public route collectors (RouteViews, RIPE RIS) and the monocle tool to search BGP updates by time window, prefix and AS-path regex. It also used BMP (BGP Monitoring Protocol) pre-policy data, which showed its own peers offering it 1.1.1.1/32. Cloudflare rejects that route on import, as both RPKI Invalid (wrong origin, too long) and DFZ Invalid (longer than /24).
Hijack: 1.1.1.1/32 path 398465 267613 origin 267613 -> RPKI INVALID (ROA: AS13335, maxLen /24)
Leak: 1.1.1.0/24 path 199524 1031 262504 267613 13335 origin 13335 -> RPKI VALID, path invalid
267613 is Cloudflare's peer: may give the route only to its customers (its "AS cone")
262504 (customer of 267613) re-announced to its upstream 1031 <- the leak
1031 accepted from a customer without prefix filtering, redistributed globally <- the amplifierRemedies discussed.
- ROV everywhere (ROA signing had passed 50% of prefixes).
- Reject IPv4 longer than /24 in the DFZ, per MANRS best practice.
- Authorise RTBH properly. Today it is filtered loosely via IRR AS-SETs. One proposal is a Discard Origin Authorization (DOA) RPKI object, from the expired IETF draft draft-spaghetti-sidrops-rpki-doa. Signing /32 ROAs for every address is not workable: it would take thousands of ROAs, and a /32 ROA would invite exact-match forgeries.
- ASPA (Autonomous System Provider Authorization). An AS signs the list of providers allowed to propagate its routes, so a path that goes "up" after going "down" is detectable.
- RFC 9234 BGP roles and the Only-To-Customer (OTC) attribute, which mark a route so it cannot go back upstream.
- More real-time route-leak detection. The public test site is isbgpsafeyet.com.
Overlooked constraints.
- Origin validation does not validate the path. The leak was RPKI-valid. You need ASPA or BGP roles to catch path problems.
- DDoS tools can themselves be attack surfaces. RTBH, meant to let a victim drop attack traffic, let a third party drop Cloudflare's traffic.
- Your reachability depends on strangers' filters. Cloudflare's only direct lever was depeering, a blunt tool that also removes good paths.
- Fame has costs. A memorable IP attracts misuse.
What Cloudflare sacrificed. Nothing new by design. Its posture already rejected invalid routes and kept anycast with a single well-known /24. The trade-off is that a single /24 has no more-specific backup announcements, because announcing /25s would break the DFZ convention.
Deep Dive: how ASPA catches the 2024 leak, step by stepShow
ASPA lets each AS publish its providers. Validation checks that an AS path is "valley-free": it may climb from customer to provider, cross at most one peer link at the top, then descend from provider to customer. Take the leaked path 199524, 1031, 262504, 267613, 13335, read from the origin outward:
- 13335 to 267613 is a peer link, the top of the valley.
- 267613 to 262504 descends to a customer. That is allowed.
- 262504 to 1031 climbs to a provider after a descent.
If 262504 has signed ASPA saying its providers are 267613 and 53072, then a receiver of the route from 1031 can check: is 1031 entitled to have this route from 262504? A climb after a descent is invalid, so 1031's peers reject the route. For this to work, ASPA needs records from the leaking network's neighbours, and validation by the networks receiving the route, so like ROV it only helps once deployed. The numbers matter: ROV reached half of prefixes about six years after Cloudflare's 2018 push (Lesson 36), so ASPA protection will likely arrive gradually too.
Lesson 44: The November 14, 2024 lost-logs incident, a fail-open safeguard and an unbuckled seatbelt#
Assumptions. Cloudflare processes over 50 trillion customer event logs a day and delivers about 4.5 trillion of them to customers. Most customers use Logpush (batched files) rather than per-server Edge Log Delivery. The post's analogy for why: the postman rings once per packet of letters, not once per letter. The pipeline:
- Logfwdr (Go): on every server, decides from config which events to forward, and where.
- Logreceiver (Go): demultiplexes into per-customer batches, about 45 PB per day uncompressed.
- Buftee (Go): a distributed buffer with a separate named buffer per Logpush job, normally over 1 million buffers. This prevents head-of-line blocking between customers and allows per-customer encryption and deletion. It is a "tee" because several consumers can read at different speeds.
- Logpush (Go): pushes over 600 million batches a day to destinations such as R2.
What happened.
- A change adding a new dataset made the config generator, which runs every few minutes, produce a blank Logfwdr config: "no customer has Logpush". It was reverted in under 5 minutes.
- The blank config triggered a latent fail-open failsafe in Logfwdr. When config is missing, forward events for all customers, so that no logs are lost. That design dated from much lower traffic.
- Buftee began creating a buffer for every customer whose logs arrived. It reached about 40 million buffers, roughly 40× its provisioned load.
- Buftee did have protections against buffer explosions, but they were not configured. It became so overloaded that operators could not interact with it, and a full reset and restart was needed.
- About 3.5 hours of impact, with about 55% of logs not delivered and lost.
Fixes. Alerts that make these misconfigurations impossible to miss, fixes to the config bug and its tests, and regular "overload tests" alongside existing "cut tests" (data center and network loss).
Overlooked constraints.
- Fail-open must be sized for today's population. A safe choice at 1,000 customers is a flood at a million. Re-check fallbacks as you grow.
- A five-minute cause can produce a multi-hour effect. Overloaded systems often cannot recover on their own (metastable failure), so the revert did not end the incident.
- A protection you have not configured is not a protection. Regularly check that limits are set and test them.
- Per-tenant buffers multiply cost by tenant count. Isolation is good, but each buffer needs memory and bookkeeping, so the count needs a hard cap.
What Cloudflare sacrificed. The fail-open choice originally traded extra volume for no lost logs. The fix accepts that some situations must shed load (drop or reject) rather than amplify. The cost of overload tests is engineering time. See delivery semantics and data pipelines.
Deep Dive: sizing fail-open fallbacks and buffer admissionShow
Model the fallback amplification as A = (all tenants) ÷ (configured tenants). Here A was about 40 (40M ÷ 1M buffers). A safe fallback either bounds A, or applies admission control at the next hop. For Buftee, admission could be a rule like: create a new buffer only if active buffers stay under 1.5× the trailing 24-hour peak, otherwise refuse with back-pressure, so Logfwdr keeps events locally and retries. In numbers: with 1M buffers at, say, 64 KB of in-memory state each (handbook's illustration), the cluster holds about 64 GB. At 40M buffers that is 2.5 TB, far beyond any provisioned RAM, so the process thrashes and stops answering even admin commands. A cap at 1.5M would have rejected the excess within seconds. The logs for unconfigured customers were not wanted anyway, so rejecting them would have cost nothing. This is the general rule: fail open on data that is known to be wanted, and fail closed (reject) on volume that is only possibly wanted.
Lesson 45: The February 6, 2025 R2 outage, an abuse action that disabled the front door#
Assumptions. R2 (S3-compatible object storage) has four layers:
- a Gateway service that authenticates and serves the S3 and REST APIs and coordinates every operation;
- a metadata layer on Durable Objects;
- intermediate caches;
- a distributed storage subsystem.
A write goes to a new immutable key, then the metadata is updated to point to it. So any request that already returned 200 is durable, whatever happens to the Gateway afterwards. Trust and Safety staff handle abuse reports, for example phishing hosted on R2, and can disable products for an offending account.
What happened (UTC).
- 08:12: while handling a phishing report, an operator disabled the production R2 Gateway service in place of the specific bucket. R2's production account was in an internal organisation, but the abuse system did not recognise internal accounts and allowed the action.
- 08:14: 100% of R2 operations failed. Dependents failed too:
- Stream and Images uploads: 100%. Image Delivery stayed at 97% because it reads from customer backends.
- Vectorize: 75% of queries failed (the rest served from cache), and 100% of writes.
- Cache Reserve fell back to origins, under 0.049% of cacheable requests.
- Log Delivery lost up to 4.5% (non-R2 jobs) and 13.6% (R2-destination jobs). R2 jobs saturated shared resources until a kill switch stopped them.
- Cache Purge: 1.8% 5xx and 10× p90 latency.
- Key Transparency Auditor: 100%.
- Workers and Pages: 0.002% of deploys.
- 08:42: root cause found from the deployment and config history.
- 08:46: the admin tool to re-enable the Gateway did not work, because it depends on R2. The incident was escalated to an operations team with lower-level access.
- 09:09: forced redeploy of the Gateway, to rebuild its routing across the edge. 09:13: recovered, after 59 minutes.
- 09:13 to 09:36: a reconnecting horde pushed Durable Objects errors in North America up by 0.09%.
- No data was lost or corrupted. Only the front door went down.
Fixes.
- Admin API guardrails that block product disablement on internal accounts.
- Disablement removed from the abuse UI until safer.
- Internal accounts provisioned into the right organisation by construction, with no standalone accounts.
- Fewer people allowed to take ad-hoc disablement actions, and two-party approval for them.
- Extend the internal-hostname protection to all products of internal accounts.
- The stated principle: rely on system guardrails, not training or process.
Overlooked constraints.
- Your own production runs in a customer account. Abuse tooling built for customers will one day point at you. Internal accounts need a hard, machine-checked identity.
- Human actions need blast-radius limits too. A scoped action ("disable this bucket") and a broad one ("disable this product") should not be one dropdown apart.
- Admin tooling must not depend on the service it administers. This repeats Lessons 37 and 42.
- Layering contains damage. Keeping the gateway, metadata and storage separate meant no data loss and a fast recovery once the gateway returned.
- Shared resources need per-destination isolation. Log jobs bound for R2 starved jobs bound for other destinations.
What Cloudflare sacrificed. Speed of abuse response (two-party approval, fewer people with access) and some operator autonomy. See security fundamentals for least privilege and handling large blobs for object-store front-door design.
Deep Dive: why write-new-key-then-swap-pointer makes a gateway crash safeShow
R2's write path is the standard crash-safe "copy on write" design:
- Write bytes to an immutable key K2. If the gateway dies here, K2 is garbage, collected later, and the object still points to K1.
- Atomically update metadata from K1 to K2 in a Durable Object. Durable Objects are single-writer, so the update is serialised.
- Return 200.
A crash before step 2 leaves the old version visible. A crash after step 2 leaves the new version visible. No state shows a 200 without a persisted pointer. That is why turning off the gateway abruptly, killing in-flight requests, could not corrupt anything: in-flight requests got errors and retried later. The same idea is used in log-structured storage engines (see storage engines) and in Git's object store. The cost is two round trips per write and garbage collection of orphaned keys. At, say, 0.1% of writes interrupted (handbook's illustration), a sweep that deletes unreferenced keys older than 24 hours keeps the leak negligible.
Lesson 46: The March 21, 2025 R2 incident, a credential rotation deployed to the wrong environment#
Assumptions. R2 has three parts:
- the gateway Worker (S3, REST and Workers APIs);
- a metadata service;
- storage infrastructure holding encrypted object data.
The gateway authenticates to storage with an ID and key pair, rotated regularly as a security practice. The rotation steps:
- Create new credentials while keeping the old ones.
- Put the new secret on the production gateway Worker (
wrangler secret put). - Deploy the Worker with the new credential ID (
wrangler deploy). - Delete the old credentials.
- Monitor.
Production and development are separate Workers environments, each with its own secrets. Both wrangler commands target the default environment when --env is omitted.
What happened (UTC).
- 19:49: rotation began.
- 20:19: both commands ran without
--env production, so the new credentials went to the default (non-production) Worker. - 20:37: the old credentials were deleted.
- 21:38: impact began, about an hour later, because the deletion propagated slowly through storage. The decline was gradual, which made it hard to spot.
- 21:45: alerts at a 2% error-budget burn rate. 21:50: incident declared.
- 22:15: another new key pair was created to "force re-propagation". 22:30: the new credentials were redeployed, still without
--env. - 22:36: the root cause was found by reading the production Worker's release history. 22:45: the correct deploy restored service, after 67 minutes.
Impact.
- 100% of writes failed and about 35% of reads. Head and list (metadata only) were unaffected.
- Cached public objects on custom domains still served, because the intermediate cache absorbed many reads.
- Images delivery fell to about 25%, and Stream segment delivery to 94% (stalls about every minute). Stream Live was down.
- Vectorize writes failed 100%. Invoices could not be downloaded.
- Log delivery was delayed up to 70 minutes but nothing was lost, unlike Lesson 44.
- No data was lost or corrupted.
Fixes.
- Log tags with the credential ID suffix the gateway is using.
- A rule: confirm the new token suffix in storage logs before deleting the old one.
- Rotation only through hotfix release tooling that enforces the environment.
- An explicit two-person rule.
- Closed-loop health checks that test new keys and confirm global propagation.
- Dashboards of upstream success rates that bypass caching, so the cache cannot hide failures.
Overlooked constraints.
- Dangerous defaults. A CLI whose default target is "not production" seems safe, but makes production changes silently go somewhere else. Use an explicit target with no default for privileged operations.
- Check the effect, not the action. "I ran deploy" is not "production uses key X". Verify through a signal from the consumer, the storage logs.
- Delayed propagation hides cause and effect. An hour between deleting the key and the impact made the link non-obvious. Keep both keys valid longer, or verify before deleting.
- Caches mask outages in metrics. Upstream success rates must be visible on their own.
- Repeating a failed fix with the same tool repeats the error.
What Cloudflare sacrificed. Speed and flexibility of hand-run CLI operations, now replaced by enforced tooling with two-person checks.
Deep Dive: a safe two-key rotation protocolShow
A rotation is a small distributed protocol with three parties: issuer (storage), holder (gateway) and verifier (logs). A safe order:
- Issue K_new. Both K_old and K_new are valid.
- Deploy K_new to the holder, with an explicit target environment.
- Observe that the issuer sees requests signed with K_new from the production holder's identity, ideally 100% of them for N minutes. In the R2 fix, this is the "suffix in storage logs" check.
- Only then revoke K_old.
- Alert if any request still arrives with K_old after revocation.
If step 3 is automated as a precondition for step 4, the March incident cannot happen: the check would have shown 0% K_new traffic from production and refused to revoke. Overlap windows are cheap. Keeping K_old alive for 24 extra hours costs almost no security, compared with the risk of revoking a key that is still in use. The same pattern applies to TLS certificate rotation and to the signing keys in token systems (see security fundamentals).
Lesson 47: The June 12, 2025 outage, Workers KV's third-party storage and a dependency tree#
Assumptions. Workers KV is a "coreless" service that runs in every location, but it relied on a central data store as the source of truth for cold reads and writes. Part of that store was backed by a third-party cloud provider. KV was being re-architected onto Cloudflare's own R2. One storage provider had already been removed, which left a gap in redundancy. Cloudflare's principle is to build on its own platform, so many first-party products depend on KV for configuration, identity and assets.
What happened (UTC). The third-party provider had an outage. For 2 hours 28 minutes (17:52 to 20:28), about 90.22% of KV requests failed: everything not already in KV's cache. The dependency tree spread it widely:
| Service | Impact and why |
|---|---|
| Access | 100% of identity logins failed. Fails closed by design without policy or identity |
| Gateway | Most DNS fine; identity-based DoH rules, proxy, egress and TLS decryption failed closed |
| WARP | No new registrations; emergency disconnect override unavailable because it also used KV |
| Dashboard | Password login failed (Turnstile), Google OIDC failed (KV), SSO failed (Access). v4 API fine |
| Turnstile and Challenges | Kill switches let users through, but tokens could then be redeemed more than once |
| Workers AI, AutoRAG, Zaraz, Queues | 100% failed (config and routing in KV) |
| Durable Objects (SQLite-backed), D1 | Peak 22% errors: same storage underneath as KV |
| Stream | Over 90% errors, Live 100% |
| Realtime TURN | Near 100% errors; SFU dropped to 20% of traffic |
| CDN | A surge of Zero Trust client re-registrations triggered traffic management in a few cities |
Not affected: DNS, cache, proxy, WAF, Magic Transit and Magic WAN.
Timeline.
- 17:52: WARP saw registrations failing. 18:06: the separate incidents were merged into one once KV was found to be the shared cause, and raised to P0 at 18:21.
- From 18:43: teams began work to move Access off KV. Gateway began gracefully degrading identity and posture rules. 19:32: Access and Device Posture force-dropped requests to shed load on KV. In parallel, a KV release against an alternative datastore was prepared.
- 20:23: the provider recovered. Caches refilled under rate limits.
Fixes.
- KV storage redundancy with no single provider; critical namespaces backfilled to Cloudflare's own infrastructure.
- Per-product blast-radius fixes.
- Progressive re-enabling of namespaces after an outage, so refilling caches cannot overload Cloudflare's own infrastructure.
Overlooked constraints.
- "Coreless" can still have a core. A service distributed at the edge with one central source of truth inherits that source's availability for every miss.
- Migrations open redundancy gaps. Removing one provider before the new backend was ready left a single point of failure. This mirrors Lesson 40's lesson that migrations change the environment.
- Dogfooding concentrates risk. Building on your own platform improves the product but creates a deep dependency tree. Ten or more products depended on KV directly or through Access.
- Emergency overrides must not share the dependency. WARP's emergency disconnect needed KV.
- Fail-closed versus fail-open is a security decision. Access and Gateway correctly failed closed (no bypass of customer policy). Turnstile's kill switch failed open with a known replay risk. Both were deliberate, and the post says so.
- Recovery needs pacing. Cold caches refilling all at once can overload the backend just as it returns.
What Cloudflare sacrificed. By choosing a third-party store, it gained time to market and lost control. The fix costs capacity: running its own redundant stores. Failing closed in Access trades availability for security, which is right for a zero-trust product.
Deep Dive: computing the blast radius of a shared platformShow
Treat services as a directed graph where an edge A to B means A needs B. The blast radius of B is the set of services that can reach B. Here B was KV's central store. Direct dependents included Access, Turnstile, Workers AI, Pages assets, Zaraz and Queues, and, through the shared storage, Durable Objects and D1. Second-order dependents included Gateway, WARP, the dashboard and Browser Isolation (via Access), Browser Rendering (via Isolation) and AutoRAG (via Workers AI). That is around 20 products for one storage failure. Two quantities guide fixes:
- Fan-in of B: the size of the reachable set. Cut it by giving critical products a different store or a local last-known-good copy.
- Cache-miss dependence: KV served 9.78% of requests from cache. Raising cache hit rates and TTLs for configuration and identity data, where staleness is acceptable for minutes, directly lowers the failure rate. With a 99% hit rate, the same outage would fail about 1% of reads.
This is the KV version of cache failure modes: a cache that can serve stale data on error is a resilience feature, not just a speed-up.
Lesson 48: The July 14, 2025 1.1.1.1 outage, a dormant topology error and a non-staged legacy system#
Assumptions. Almost all Cloudflare services are reached by anycast: the same prefixes are announced from every location (Lesson 1). The Data Localization Suite (DLS) has services whose IPs must be reachable only in certain regions, so each service has a service topology, the set of locations that announce its prefixes. Topologies are managed in a legacy system that hard-codes lists of locations per prefix, with no progressive deployment. A newer system describes topologies without hard-coded IPs and supports staged, health-mediated rollout. The two are kept in sync during the migration.
What happened.
- June 6, 17:38 UTC: a change prepared a topology for a future DLS service and accidentally included the 1.1.1.1 Resolver's prefixes. Nothing in production changed, so no alert fired. The error lay dormant for 38 days.
- July 14, 21:48: a second change attached an offline test location to that non-production service. This triggered a global refresh of network configuration. The Resolver's topology was reduced from all locations to one offline location, and every 1.1.1.1 prefix was withdrawn worldwide at once:
- 1.1.1.0/24 and 1.0.0.0/24;
- 2606:4700:4700::/48;
- several 162.159.x.0/24 and 172.64.x.0/24 prefixes.
- 21:52: traffic dropped globally over UDP, TCP and DoT. DoH stayed mostly up, because most DoH users reach cloudflare-dns.com, which uses different IPs.
- 21:54: with Cloudflare's route gone, Tata Communications India (AS4755) was seen announcing 1.1.1.0/24, a hijack that had been hidden while Cloudflare's announcement was present. It was not the cause.
- 22:01: alerts fired and the incident was declared.
- 22:20: revert. Prefixes were re-announced instantly, bringing traffic back to about 77%, with a spike from client retries.
- Why not 100%: about 23% of edge servers had automatically removed their IP bindings for the Resolver. Restoring them went through change management, which is deliberately progressive over hours. It was accelerated after validation in test locations.
- 22:54: fully restored, after 62 minutes.
Fixes. Deprecate the legacy addressing system and move all addressing to staged, health-mediated deployment with automatic rollback.
Overlooked constraints.
- Latent config errors need a semantic diff at review time, not at activation time. The June change looked harmless because it changed nothing yet. A check like "which production prefixes does this topology now reference?" would have flagged it.
- Two systems in sync double the ways to fail. During a migration, the legacy path is often the unstaged one.
- Anycast's strength is its weakness. One logical announcement serves everywhere, so one logical withdrawal removes it everywhere.
- Recovery has a hidden second step. Routes came back instantly, but server-side state (IP bindings) moved through a deliberately slow, safe pipeline. Safety mechanisms slow recovery as well as failure.
- Clients by hostname survived. DoH via a name with its own IPs was a separate failure domain.
What Cloudflare sacrificed. Speed of addressing changes, which now go through stages, and migration effort to retire the legacy system early. The DLS feature itself, regional reachability, is what required per-service topologies in the first place. Compliance features add configuration surface.
Deep Dive: why hidden hijacks surface when you withdrawShow
When a legitimate origin announces 1.1.1.0/24 and a rogue network also announces 1.1.1.0/24 (same length), each router picks between them by local preference, AS-path length and so on. Most of the Internet prefers Cloudflare's path, because it is directly connected or shorter and RPKI-valid where ROV is enforced. The rogue route survives only inside networks that do not validate and prefer it locally, so it is mostly invisible to collectors. Withdraw the legitimate route and the rogue route is the only candidate everywhere that lacks ROV, so it suddenly spreads and becomes visible. Two lessons follow. First, monitoring should alert on any unexpected origin for your prefixes even when your route is winning (Lesson 43's BMP and monocle tooling). Second, ROV enforcement is what keeps such routes out during your own outages: with about half of the Internet enforcing ROV by 2024 (Lesson 43), the Tata route was invalid, but it still reached networks that did not validate.
Lesson 49: The September 12, 2025 dashboard and API outage, a React hook that became a load generator#
Assumptions. The Tenant Service (a Go process on Kubernetes in a subset of data centers) is part of API request authorization: without it, authorization cannot be evaluated, so API requests return 5xx. The control plane is strictly separated from the data plane, so customer traffic does not depend on it.
What happened (UTC).
- 16:32: a new dashboard release had a bug. A
useEffecthook calling the organizations endpoint had, in its dependency array, an object recreated on every render. React compares dependencies by reference, so the effect re-ran on every state or prop change. One page view made many calls, retries included. - 17:50: a new Tenant Service version was deployed. 17:57: the Tenant Service was overwhelmed during the deploy, and the dashboard and API fell.
- 18:17: more pods were added and the API recovered to 98%, but the dashboard did not.
- 18:58: a patch removing some error paths made things worse: the API went down a second time. It was not on Argo Rollouts, which watches deployments and rolls back automatically on errors, so the bad patch was not rolled back.
- 19:01: a temporary global rate limit. 19:12: the patch was reverted and the dashboard came back to 100%.
On every restart, every open dashboard re-authenticated at once, a thundering herd made worse by the loop bug.
// Bug pattern (illustrative): a new object each render keeps re-running the effect
const filters = { accountId, includeMembers: true }; // new reference every render
useEffect(() => {
fetchOrganizations(filters); // runs on every render, retries on failure
}, [filters]);
// Fix: depend on stable primitive values, or memoize the object
useEffect(() => {
fetchOrganizations({ accountId, includeMembers: true });
}, [accountId]);Fixes.
- A hotfix for the loop.
- Random delays (jitter) on dashboard retries.
- Migrate the Tenant Service to Argo Rollouts.
- Much more capacity, with alerts before limits are hit.
- Dashboard requests marked as retry or new, because during the incident the team could not tell a rising rate of new requests (a loop) from retries.
Overlooked constraints.
- Your clients are part of your load model. A frontend bug can multiply load by the number of open tabs. Treat the dashboard as a potential DDoS source and rate-limit per session.
- An authorization dependency must have capacity headroom. Every API call needs it, so its overload means total API failure.
- Retries need jitter and identification. Without a retry marker you cannot tell an amplification loop from organic growth.
- Deploying during overload adds risk. Two changes (dashboard, tenant service) close together made the root cause ambiguous.
- Separating the control plane from the data plane works. Traffic was unaffected.
What Cloudflare sacrificed. More idle capacity for the Tenant Service, plus the work of migrating all services to automated rollouts. See rate limiting and resilience patterns for jittered backoff.
Deep Dive: how a render loop and synchronized retries multiply loadShow
Say 20,000 dashboards are open (handbook's illustration). Normally each makes 1 organizations call per page load, about 1 every 30 s, which is roughly 670 requests per second. With the hook bug, each state change triggers another call. A busy page with 10 state changes per load gives 10× the traffic, about 6,700 per second. Add retries on failure, say 3 immediate retries, and the failing service sees up to 4× that, about 27,000 per second, which is 40× normal. On restart, all 20,000 clients re-authenticate in the same second.
Exponential backoff with full jitter (each retry waits a random time between 0 and base × 2^attempt) spreads the reconnect over the backoff window. With a 30 s window, the peak becomes about 670 per second instead of 20,000 in one second. This is why "add jitter" is in almost every postmortem with a herd: synchronized clients are as dangerous as an attack. The Rapid Reset (Lesson 30) and lost-logs (Lesson 44) incidents show the same amplification arithmetic.
Lesson 50: The November 18, 2025 outage, a doubled feature file and an unwrap#
Assumptions. A request passes through TLS/HTTP termination, then the core proxy FL ("Frontline"), then Pingora for cache and origin fetch. Inside FL, modules apply each customer's configuration (WAF, DDoS, Workers routing). The Bot Management module runs an ML model that scores every request. The model reads a feature file (the list of features it uses), regenerated every 5 minutes from a ClickHouse query and pushed to the whole network quickly, because bot tactics change fast. Customer traffic was migrating from FL to FL2, written in Rust (Lesson 6).
What happened.
- 11:05: a ClickHouse permissions change, rolled out gradually across the cluster. Distributed queries were moving from a shared system account to each initial user's own account, for finer-grained limits. Users could now see the metadata of the underlying r0 tables, not only the
defaultdatabase's Distributed tables. - The feature generator used a metadata query that did not filter by database. On updated nodes it returned every column twice, once for default and once for r0, so the file more than doubled.
- FL2's Bot Management preallocates memory for a maximum of 200 features, against about 60 in use. The oversized file exceeded the limit, and the code called
unwrap()on the error, so the worker thread panicked and returned 5xx. - On old FL there was no crash, but bot scores were all zero, so customers with block-bot rules saw false positives.
- The symptom pulsed. Each 5-minute run produced a good or bad file depending on which nodes the query hit, so the network failed, recovered and failed again. That pattern, plus a coincidental outage of the status page (hosted entirely off Cloudflare), made the team suspect a hyper-scale Aisuru DDoS at first.
- Latency also rose, because debugging and observability systems used heavy CPU enriching uncaught errors.
- Dependents: Workers KV's front-end gateway runs through the proxy, so KV, Access and dashboard logins (Turnstile) failed too. 13:05: KV and Access were moved to the older proxy, which reduced impact.
Timeline. First customer errors at 11:28. An automated test detected the issue at 11:31, and the incident call started at 11:35. At 14:24 new file generation was stopped and an old file tested. At 14:30 a known-good file was inserted into the distribution queue and the core proxy restarted: main impact resolved. A second dashboard dip came from a backlog of logins plus retries, fixed by scaling control-plane concurrency at about 15:30. Everything was normal by 17:06. The post calls it the worst outage since 2019, the first in more than 6 years where most core traffic stopped.
-- Metadata query used to build the feature list (simplified from the post)
SELECT name, type
FROM system.columns
WHERE table = 'http_requests_features'
ORDER BY name;
-- No "AND database = 'default'": after explicit r0 grants, each column appears twice.Feature limit check in the proxy (handbook's illustration of the pattern):
features = parse(file) -> Err(TooManyFeatures) when count > 200
features.unwrap() -> panic in fl2_worker_thread -> HTTP 5xx
Safer pattern: on Err, log, alert, keep the previous good feature set, continue serving.Fixes.
- Treat Cloudflare-generated config files like user input, with validation on ingest.
- More global kill switches for features.
- Stop core dumps and error reports from exhausting resources.
- Review the error-handling failure modes of every core proxy module.
Overlooked constraints.
- Internal config is untrusted input. The proxy validated customer input carefully, but trusted a file Cloudflare generated itself. Generated data inherits every bug of its generator.
- A safe limit plus a crash on breach is not safe. The 200-feature cap was a good guardrail, but the reaction to hitting it should have been to reject the file and keep the old one.
- Schema assumptions hide in queries. "system.columns returns one database" was an unwritten assumption that a permissions change broke. Queries over metadata should state every filter explicitly.
- Gradual rollout of a dependency creates confusing pulsing. Partially rolled-out database grants produced alternating good and bad outputs.
- Error handling can cost more than the error. Debug enrichment of panics consumed CPU, adding latency to working requests.
- Coincidences mislead. The status page outage pushed the diagnosis toward "attack".
What Cloudflare sacrificed. The speed of the bot feature pipeline: validation and staged rollout of generated files add latency to threat response. The fixes also add code paths, and kill switches must be maintained.
Deep Dive: validate, stage and fall back for machine-generated configShow
A robust consumer of a frequently refreshed config file follows a four-step contract:
- Validate structure and bounds: count ≤ limit, no duplicate names, schema version known. Reject on failure.
- Keep last-known-good. Never replace a working config with one that fails validation. Keep serving the old one and alert.
- Stage. Even a 5-minute cycle can canary. Push to 1% of machines, check error rates for 60 s, then the rest. That adds about 1 minute of propagation delay, which costs almost nothing against bot tactics that change over hours.
- Fail per request, not per process. If a module cannot run, skip it for that request and mark the result as degraded (for example, no bot score). Do not crash the worker.
With this contract, the November 18 file would have been rejected on every machine at step 1, with old features kept and no customer impact. Two cheap invariants on the producer side, the row count and duplicate names, would also have caught it: the file went from about 60 to over 120 rows in one cycle, a 2× jump, and a rule like "alert and hold if the count changes by more than 20%" stops it at the source. Compare Lesson 37: in both 2019 and 2025, fast global config distribution made one bad artefact reach everywhere in seconds.
Lesson 51: The December 5, 2025 outage, a kill switch never used on an "execute" rule#
Assumptions. The WAF buffers the HTTP request body in memory to inspect it, previously up to 128 KB. A critical React Server Components vulnerability (CVE-2025-55182) was disclosed that week. To protect as many customers as possible, the body buffer was being raised to 1 MB, the Next.js default limit, via the gradual deployment system. The rulesets engine evaluates rules, each a filter plus an action: block, log, skip, or execute, which evaluates another ruleset. An internal testing tool uses execute to try new rules before release. A killswitch subsystem, fed by the global configuration system (which propagates in seconds with no gradual rollout), can disable a misbehaving rule. There is a well-practised SOP for it.
What happened (UTC).
- During the buffer rollout, engineers noticed that the internal WAF test tool did not support the larger buffer. Since the tool served no customer traffic, they turned it off with the global config system.
- 08:47: the change was out; it fully propagated by 08:48. On the older FL1 proxy, the killswitch was applied to an execute rule for the first time ever. Evaluation correctly skipped the sub-ruleset, but result processing then tried to read a field of the skipped rule's execute result, which was nil.
- The Lua exception ("attempt to index field 'execute' (a nil value)") made every request return 500 for customers who were both on FL1 and using the Cloudflare Managed Ruleset. That was about 28% of HTTP traffic. The China network and FL2 (Rust) were not affected: the Rust type system makes this error impossible to write.
- 08:50: automated alerts. 09:11: revert. 09:12: resolved, after about 25 minutes.
-- Result processing in FL1 rules module (from the post)
if rule_result.action == "execute" then
rule_result.execute.results = ruleset_results[tonumber(rule_result.execute.results_index)]
end
-- When the killswitch skipped the rule, rule_result.execute was nil -> runtime error -> HTTP 500Context and response. This came 17 days after November 18 (Lesson 50), with the same shape: a change made to protect customers from a security issue reached the whole network in seconds. The planned fixes, not yet deployed, were:
- Enhanced rollouts and versioning for config and threat-response data, matching software releases: health validation and fast rollback.
- Streamlined break-glass for internal services and all control-plane interfaces.
- "Fail-open" error handling. Replace the hard-fail logic applied in the wrong places across the data plane. A corrupt or out-of-range config (for example, one exceeding feature caps) should log the error and use the known-good state, or pass traffic without scoring, not drop requests. Customers may get a fail-open or fail-closed choice, with drift prevention to keep the setting enforced.
Cloudflare also froze all network changes until the better mitigation and rollback systems were in place.
Overlooked constraints.
- An untried path through a trusted tool is untested code. The killswitch was well practised, but never on this action type. List the combinations of (tool × action) and test each one.
- A "harmless" second change can bypass the safe pipeline. The risky change (buffer size) went gradually. The "safe" change (turning off a test tool) went instantly, and that is the one that broke production.
- Dynamic typing hides nil paths for years. The same logic in Rust's FL2 did not fail. The language migration (Lesson 6) is a reliability project, not just a performance one.
- Incidents close together erode trust faster than one large incident. Freezing changes buys time, but costs feature velocity.
What Cloudflare sacrificed. A network-wide change freeze (velocity), slower config propagation once it is versioned and staged (threat-response speed), and, in fail-open mode, possible unscored or uninspected traffic during config faults, which is a security cost made explicit per customer.
Deep Dive: deciding fail-open versus fail-closed per componentShow
Each data-plane component has a fault behaviour, and the right choice depends on what an unfiltered request costs compared with a dropped one:
| Component | Fail-open cost | Fail-closed cost | Typical choice |
|---|---|---|---|
| Bot scoring | Some bots pass unscored | All traffic blocked or 5xx | Open (skip score) |
| WAF managed rules | Attack payload might pass for minutes | Site fully down | Open with alert, customer-selectable |
| Zero-trust Access | Unauthorised access to a private app | Users cannot log in | Closed |
| Gateway policy | Policy bypass for an enterprise | Users lose Internet | Closed by default |
The November and December outages both fell in the first two rows, where failing closed (crash or 500) was the wrong choice. Lesson 47's Access behaviour was the right fail-closed choice in the third row. A quantitative test: if the component fails for 30 minutes, which costs more in expected harm, 30 minutes with a small probability of a successful attack on a fraction of customers, or 30 minutes of total outage for all of them? For bot scoring the answer is clear. For zero-trust access it is the reverse.
Lesson 52: The February 20, 2026 BYOIP outage, an empty query parameter that meant "everything"#
Assumptions. BYOIP (Bring Your Own IP) lets customers announce their own prefixes through Cloudflare for the CDN, Spectrum, Magic Transit and Dedicated Egress. The Addressing API is the authoritative dataset of addresses on the network. Changes made through it trigger workflows that propagate immediately to the edge:
- The customer signals advertise or withdraw, via the API or BGP Control.
- The API instructs machines.
- Routers update BGP once enough machines have the change.
- Service bindings attach products to ranges.
Under Code Orange: Fail Small (the plan after Lessons 50 and 51), risky manual steps were being replaced with automated, health-mediated workflows. One was removing BYOIP prefixes for customers, which had been done by hand.
What happened (UTC).
- Feb 5: code merged for a recurring clean-up sub-task that lists prefixes pending deletion and removes them. Its query passed the flag with no value. The server checks whether the flag's value is non-empty, so it skipped the pending-only branch and returned all prefixes, and the task treated them all as queued for deletion.
- Feb 20, 17:46: deployed. 17:56: the task began deleting BYOIP prefixes and their dependent objects, including service bindings, step by step across customers.
- 18:13: failures noticed on the one.one.one.one website (403 "Edge IP Restricted"). DNS over 1.1.1.1 itself, including DoH, was fine.
- 18:46: an engineer found and killed the sub-task. About 1,100 of 4,306 BYOIP prefixes (25%) had been withdrawn, out of 6,500 prefixes advertised to a sample peer.
- 19:19: customers were told they could re-advertise from the dashboard. 20:20: about 800 prefixes were restored.
- About 300 prefixes had lost their service bindings and could not be toggled. They needed a global machine configuration rollout, done by 23:03. Total time was 6 hours 7 minutes.
User experience. With a prefix withdrawn, clients go through BGP path hunting: packets wander while routers look for a route, until the connection times out. That is slow failure, not a fast refusal.
// Client (clean-up sub-task): flag sent with no value
resp, err := d.doRequest(ctx, http.MethodGet, "/v1/prefixes?pending_delete", nil)
// Server: an empty value fails the check, so it falls through to "list all prefixes"
if v := req.URL.Query().Get("pending_delete"); v != "" {
prefixes, err := c.RO().IPPrefixes().FetchPrefixesPendingDeletion(ctx)
// ... render only pending prefixes
return
}
// ... default path: return every BYOIP prefix -> client deletes them allWhy tests missed it. Staging data and mocks were not close enough to production. Tests covered the customer self-service journey, but not the task runner changing user data on its own, with no explicit input.
Why recovery was slow. Prefixes ended up in three different states:
- withdrawn only, fixable with a dashboard toggle;
- withdrawn with some bindings removed, partly fixable;
- withdrawn with all bindings removed, needing a global config push.
The planned system for snapshotting operational state and rolling it out under health checks was not yet in production.
Fixes.
- API schema standardisation, so flags are typed booleans and malformed calls are rejected.
- Separate configured state from operational state. Snapshot what is read from the database and apply snapshots through health-mediated deploys, so a bad database state is never live and can be reverted per customer almost instantly. The cost: during an outage, customers may be temporarily unable to change their config via the API.
- Circuit breakers on large or fast withdrawals and deletions. Stop snapshot deployment when changes are too broad or too fast, including when signals from customer services degrade.
Overlooked constraints.
- "Absent" versus "empty" versus "true" must be unambiguous. Stringly typed flags turn a missing value into the widest possible query. A destructive action should require a positive, typed selector, never the default branch.
- Automation removes a human sanity check. A person deleting one customer's prefix would never delete 1,100. Automation needs its own sanity limits, such as "no more than N deletions per hour".
- The authoritative database was also the live config. Every write was production. Separating desired state from deployed state is the main architectural fix.
- Safety projects carry risk too. The change was itself part of a reliability programme. New automation needs the same staged rollout it is meant to enforce.
- Partial deletions create many recovery states. Destructive multi-object operations should be transactional, or recorded as tombstones (soft deletes) that can be restored.
What Cloudflare sacrificed. Immediate propagation of customer addressing changes (snapshots plus health-mediated rollout add delay) and API writability during incidents. In return, it gains fast per-customer rollback. See idempotency for safe API semantics and distributed transactions for multi-object atomicity.
Deep Dive: a circuit breaker for destructive control-plane changesShow
A rate-and-breadth breaker on a desired-state pipeline:
- Track D(t), the number of prefixes withdrawn in the last 5 minutes, and C(t), the number of distinct customers affected.
- Baselines: normal churn is perhaps 0 to 5 withdrawals per 5 minutes from 1 to 3 customers (handbook's illustration).
- Trip if D exceeds 20, or C exceeds 5, in any window. Then halt all snapshot deployments, page the owning team and require two-person approval to resume.
In February the task deleted about 1,100 prefixes in 50 minutes, about 110 per 5 minutes. The breaker would have tripped after the first 20, a blast radius of under 2% of the actual one. Add soft deletes: mark a prefix "pending removal" for 24 hours before purging bindings. Then even a tripped breaker leaves every object restorable with one state flip, not a global config rebuild. The general lesson matches Lesson 38's BGP max-prefix limit: wherever a single process can change many objects, put a cap on how many it can change per unit of time.
Lesson 53: How Verizon and a BGP optimizer knocked large parts of the Internet offline (June 24, 2019)#
Assumptions. BGP depends on transit providers filtering what their customers announce. Each customer should be allowed to announce only its own prefixes and those of its own customers, as listed in IRR objects such as as-sets. BGP route optimizers, used by some enterprises, create more-specific routes (for example, splitting a /20 into /21s) so they can steer traffic inside their own network. These synthetic routes should never leave that network, and the NO_EXPORT community (RFC 1997) exists to mark exactly that.
What happened. From 10:34:25 to 12:38:54 UTC, just over two hours, AS396531 (Allegheny Technologies) leaked routes it had learned from AS33154 (DQE Communications) to its transit provider AS701 (Verizon). DQE ran a BGP optimizer, and the routes included synthetic /21s inside Cloudflare's /20s. Verizon passed them on to its peers. Because they were more specific, they beat Cloudflare's real announcements wherever they were accepted. About 2,400 networks were affected, and Cloudflare was hit hardest.
How Cloudflare investigated, using only public data.
- It took 24 hours of RIPEstat BGP updates for AS13335: 340 MB of JSON, 691,318 routing events.
- It filtered to paths containing "701,396531": 204,568 events, 101 unique prefixes. The post notes that a sort typo had first shown only 20.
- Each leaked /21 sat inside a Cloudflare /20 with an IRR object and an RPKI ROA with max length /20. Any /21 was therefore RPKI-invalid.
- The paths read, from the origin outward: 13335, then 3356 (Level3) or 174 (Cogent), then 33154, then 396531, then 701, then Verizon's peers, including other Tier 1s: Cogent, Sprint, Vodafone, DTAG, PCCW, Zayo and Telecom Italia.
- The as-set AS-DQECUST did not list Cloudflare, proving that Verizon applied no customer filtering.
- Telia (1299), NTT (2914) and AT&T (7018) were not affected. They reject routes from a Tier 1 peer whose path contains another Tier 1, since Tier 1s are fully meshed, so such a path is always a leak. AT&T also dropped RPKI invalids, so its traffic graph was flat that day.
- IPv6 was unaffected, because AS396531 had no IPv6. Mobile clients using Happy Eyeballs (RFC 8305), which tries IPv6 and IPv4 in parallel, partly survived over IPv6.
Leaked path (read right to left from origin):
6762 701 396531 33154 3356 13335
13335 Cloudflare -> 3356 its transit -> 33154 DQE (runs optimizer, makes /21s)
-> 396531 Allegheny (customer of both) -> 701 Verizon (no customer filter) -> Tier 1 peers
ROA: 104.26.0.0/20 maxLength /20 origin AS13335
Leak: 104.26.0.0/21 -> more specific than allowed -> RPKI INVALIDRemedies named. RPKI ROV now (an ROV-enforcing network was protected), NO_EXPORT on optimizer routes, customer filtering from IRR as-sets, the Tier 1-in-path filter, and the IETF ASPA draft by Alexander Azimov and colleagues (Lesson 43).
Overlooked constraints.
- More-specific routes are the most dangerous leak. They win by longest-prefix match whatever their preference or path length. An ROA with a tight max length is the defence.
- Tools that create routes must label them. An optimizer's routes are internal by definition, so default them to NO_EXPORT.
- Two failures in a row. The leak needed both a misbehaving customer and an unfiltering transit. Each network's filters protect everyone else.
- Public data makes BGP auditable. Anyone can reconstruct an incident from collectors, as this post shows with shell commands.
What Cloudflare sacrificed. Nothing at the time, but the incident explains its later RPKI campaign (Lesson 36): signing ROAs with exact max lengths gives up the flexibility to announce more-specific routes later without first updating the ROA.
Deep Dive: why a /21 beats a /20 everywhere, and how ROA max length stops itShow
A router holding both 104.26.0.0/20 (via Cloudflare) and 104.26.0.0/21 (via Verizon) forwards a packet for 104.26.3.7 using the longest match, the /21. BGP attributes are compared only between routes for the same prefix, so the /21 wins on every router that accepted it, whatever the local preference or path length. Leaked more-specifics are therefore far worse than leaked equal-length routes, which compete on path length and often lose. Over the two hours, the leak covered half of each affected /20: 2,048 of 4,096 addresses, for 101 prefixes. ROV turns the problem into a lookup: for a received route (P, len, origin), find ROAs covering P. If one exists with the same origin and maxLength ≥ len, the route is valid. If covering ROAs exist but none match, it is invalid. With maxLength /20, every /21 is invalid regardless of origin, so even a forged origin of AS13335 would have been rejected. That is why exact max length is recommended practice.
Lesson 54: Understanding how Facebook disappeared from the Internet (October 4, 2021), an outside view#
Assumptions. Facebook (AS32934) runs its own authoritative DNS servers on prefixes it announces itself, and it moves few routes in normal operation. Recursive resolvers, Cloudflare's 1.1.1.1 among them, rely on reaching those servers on every cache miss.
What Cloudflare saw.
- About 15:40 UTC: a spike of BGP UPDATEs from Facebook, mostly withdrawals. 15:51: Cloudflare opened an internal incident, "Facebook DNS lookup returning SERVFAIL", at first worried it was a 1.1.1.1 fault. 15:58: confirmed that Facebook had stopped announcing the prefixes holding its DNS servers, for example 185.89.218.0/23 and 129.134.30.0/23, which were absent from RouteViews.
- Other Facebook prefixes stayed routed, but were useless without DNS. Resolvers everywhere, 1.1.1.1 and 8.8.8.8 alike, returned and cached SERVFAIL.
- A retry tsunami. Apps retried aggressively and users reloaded and relaunched apps, so resolvers saw about 30× normal query volume. 1.1.1.1 kept most answers under 10 ms, with higher p95 and p99 where expired TTLs forced timeouts against Facebook's nameservers (the familiar 10 s DNS timeout).
- Spillover: more DNS queries to Twitter, Signal and other platforms. WARP traffic to and from AS32934 disappeared in every country.
- About 21:00: BGP activity resumed, peaking at 21:17. facebook.com resolved again on 1.1.1.1 from about 21:20, and by 21:28 Facebook appeared reconnected.
Facebook's own write-up, as summarised in the post, says a configuration change hit the entire internal backbone, which cascaded into the withdrawals and made recovery hard for internal staff.
Overlooked constraints.
- DNS is a routing dependency. Withdrawing the prefixes of your authoritative servers removes your name from the Internet, even if your other prefixes are fine. Put authoritative DNS on independent networks or use a secondary provider.
- Failure creates load elsewhere. Retries from billions of clients hit third-party resolvers at 30×. Your outage is someone else's capacity event.
- Negative caching cushions the herd. Resolvers caching SERVFAIL briefly cut repeat queries. Clients should use exponential backoff on DNS failure.
- Self-healing tooling must not depend on the network it heals. That is the inside view of the same incident, and the theme of Lessons 37, 42 and 45.
What Facebook's design sacrificed (as observed from outside). Running DNS and the backbone under one control made operations simpler, but coupled them. The edge DNS servers withdrew their own routes when they could not reach the backbone. That is sensible for a single broken site, and catastrophic when every site does it at once.
Deep Dive: why resolver load jumps 30× when a big name failsShow
A popular name like facebook.com is normally answered from resolver cache at a hit rate near 100%, with TTLs of minutes, so the authoritative servers see almost nothing per resolver. When the name fails, three multipliers stack:
- Cache hits turn into misses as TTLs expire, so every query goes upstream and waits for a timeout.
- Clients retry: a mobile app might retry 3 to 5 times with short backoff.
- Users relaunch the app, which triggers new lookups for several hostnames (API, CDN and chat endpoints), each repeated.
With 3 names × 4 retries × 2.5 relaunches, a single user's lookups become about 30 queries where one cached answer used to do. That matches the observed 30×. Two resolver-side defences:
- Negative caching of SERVFAIL for a short time (RFC 2308 covers negative caching in general), so most repeats are answered locally.
- Serving stale answers (RFC 8767) when the authority is unreachable. In this case it would not have helped, because Facebook's address answers depended on routes that were also gone for the DNS servers, and there were no usable stale answers for the withdrawn services.
On the client side, exponential backoff with jitter (Lesson 49) is the cheapest fix: with 2^n backoff starting at 1 s, the 4 retries spread over 15 s instead of 1 s.
Lesson 55: Recurring patterns across eighteen outage reports#
Lessons 37 to 54 cover eighteen incidents across seven years, plus two outside analyses. Put side by side, they repeat a small number of patterns. This is the most transferable lesson on the page, because every large system runs into the same ones.
| Pattern | Incidents | Lesson for any system |
|---|---|---|
| Instant global config path | WAF regex 2019 (37), bot feature file 2025 (50), killswitch Dec 2025 (51), 1.1.1.1 topology 2025 (48) | Config and data that change behaviour are code. Stage them like binaries, with health gates and automatic rollback |
| Recovery tools depend on the broken system | Access during WAF 2019 (37), KV and CI 2023 (42), R2 admin 2025 (45), WARP override 2025 (47) | Keep break-glass paths off the platform, and practise them |
| Order or scope mistakes in network policy | Atlanta 2020 (38), MCP spines 2022 (39), BYOIP 2026 (52) | Use semantic diffs, max-prefix limits, commit-confirm and circuit breakers on mass withdrawals |
| Latent bug woken by a change elsewhere | Cloudbleed 2017 (40), killswitch on "execute" 2025 (51), topology dormant 38 days (48) | Old code inherits new environments. Fuzz, type-check and test untried combinations |
| Hidden dependencies and concentrated platforms | PDX 2023 (41), KV 2023 (42), KV 2025 (47), Tenant Service 2025 (49) | Map dependency graphs, test losing whole sites, cap fan-in on shared services |
| Fail-open or fail-closed chosen by accident | Logfwdr 2024 (44), FL2 panic 2025 (50), Turnstile vs Waiting Room 2023 (42) | Decide per component and test the choice under load |
| Amplification and herds | Logfwdr 40× buffers (44), dashboard loop (49), DR failover herd (41), R2 reconnects (45), Facebook 30× DNS (54) | Admission control, jittered backoff, and progressive re-enabling |
| Human action at too wide a scope | R2 abuse disablement (45), credential rotation default env (46) | Typed, scoped actions, two-person rules, verify the effect not the command |
| Routing trust on the open Internet | Verizon 2019 (53), 1.1.1.1 hijack and leak 2024 (43), Tata hijack seen 2025 (48) | RPKI ROV with exact max length, customer filters, ASPA and BGP roles |
Patterns in the fixes.
- Code Orange. Engineering redirected after 2023 (Lesson 41) and again as "Fail Small" after late 2025 (Lessons 51 and 52). It has three buckets: controlled rollout for every config change, break-glass with no circular dependencies, and well-defined failure modes.
- Rust and types. The FL2 proxy survived the Lua nil error (Lesson 51), and memory safety would have prevented Cloudbleed (Lesson 40). But FL2 panicked on an unwrap (Lesson 50), so types do not replace error-handling design.
- Separate desired state from deployed state. BYOIP snapshots (Lesson 52), Quicksilver versioning (Lessons 9 to 11), and last-known-good files (Lesson 50).
- Detection in the data plane, not only in metrics. Automatic tests found the 2025 failure in 3 minutes (Lesson 50). Missing upstream-success views slowed the R2 diagnosis (Lesson 46).
Deep Dive: the arithmetic of staged rollout for configurationShow
Suppose a bad change would break 100% of the traffic it reaches, and is detected T_d = 2 minutes after reaching any traffic. That is realistic: automatic tests found the November 2025 failure in about 3 minutes.
- Global push. Propagation is seconds (Quicksilver p99 about 2.3 s, Lesson 37). Impact is 100% of traffic × (detection plus rollback) = 100% × (2 + R) minutes, where R is rollback time. In the 2019 WAF case R was about 7 minutes, giving about 9 minutes at 100% (excluding diagnosis time). The full 27 minutes came from diagnosis and access problems.
- Staged push. Stages of 0.1% (employees, DOG), 1% (PIG), 10% (canary) and 100%, with a 5-minute bake each. A bad change is caught in the first stage, affecting 0.1% of traffic for 2 minutes. That is about 1,000× less impact, for a cost of about 15 minutes of extra propagation delay for good changes.
The trade-off is the one Cloudflare keeps facing: threat-response data (WAF rules, bot features) wants to be global in seconds, and safety wants it staged. The resolution in the 2025–2026 reports is to stage everything with short bake times (minutes, not hours) and keep an explicitly separate, rarely used emergency path that skips stages, guarded by two-person approval. If 1% of config changes are bad and there are 400 a month (handbook's illustration, close to the 2019 WAF rate of 476 in 60 days), that is 4 bad changes a month. Global push gives 4 incidents at 100% blast radius. Staged push gives 4 near-misses at 0.1%. Few reliability investments have a payoff that clear.
Cross-cutting: queue the burst or shed it#
Every system that meets a traffic spike has two basic moves. It can queue: accept the work now and do it later, at a rate the back end can sustain. Or it can shed: refuse some work immediately, preferably the least valuable, so the rest succeeds. Queuing keeps every request but adds latency and needs bounded storage. Shedding keeps latency low but loses some requests. Cloudflare's posts show both moves, and show what goes wrong when the choice is left to chance.
| Mechanism | Move | What is protected | Lesson |
|---|---|---|---|
| Waiting Room | Queue people, not requests: time buckets, admission by free slots | The customer's origin and its checkout flow | 18 |
| Cloudflare Queues | Queue messages in Durable Object shards, consumers pull at their own rate | Downstream services that cannot absorb peaks | 14 |
| Kafka between services | Queue with replay, consumers catch up after an outage | Producers, which never block on slow consumers | 25 |
| Traffic Manager | Shed from a site by moving the lowest-priority plans first (Free, then Pro) | Paying customers' latency at an overloaded site | 8 |
| l4drop and the autonomous edge | Shed attack packets at the driver before any work is done | CPU for legitimate traffic | 28 and 29 |
| Rate limiting counters | Shed a client's excess requests with a 429 | The origin and fairness between clients | 23 |
| Logfwdr and Buftee after 2024 | Shed (drop or reject) instead of amplifying when buffers fill | The logging pipeline itself | 44 |
A queue is only a burst absorber if its drain rate is above the average arrival rate. Otherwise it is a slow-motion outage. Kafka's catch-up arithmetic in Lesson 25 and Waiting Room's estimated wait in Lesson 18 are the same formula: backlog ÷ (drain rate − arrival rate). Three practical rules follow from the incidents:
- Bound every queue and decide in advance what happens at the bound. The 2024 lost-logs incident (Lesson 44) began when a fail-open path, meant to protect against losing logs, created 40 times more buffers than the system was sized for.
- Shed by value, not at random. Traffic Manager moves free-plan traffic first, Waiting Room admits the oldest arrivals first, and DDoS rules drop only fingerprints that match an attack. Random shedding punishes the users you most want to keep.
- Shed as early and as cheaply as possible. A packet dropped in XDP costs nanoseconds. The same packet rejected after TLS and HTTP parsing has already cost most of the work it was meant to save.
For the general pattern with database-side numbers, see scaling writes and rate limiting.
When to Use It#
Cloudflare's posts are most useful when your system has one of these properties:
- Many sites serving the same addresses or the same software. Anycast and the uniform server (Lessons 1 and 2), Unimog and Maglev for layer 4 balancing (Lessons 3 and 5), Traffic Manager for cross-site steering (Lesson 8).
- A proxy that terminates huge numbers of connections. Pingora's shared connection pool and multithreading (Lessons 6 and 7), Keyless SSL to keep keys away from the edge (Lesson 32), HTTP/3 and QUIC trade-offs (Lessons 33 and 34).
- Configuration that must reach every machine fast. Quicksilver's versions, replicas and consistent reads (Lessons 9 to 11), plus every outage lesson about staging that speed (Lessons 37, 50 and 51).
- Globally distributed state with coordination needs. Workers KV for read-heavy data (Lessons 12 and 13), Durable Objects for one owner per piece of state (Lessons 15 to 17), Queues and Waiting Room built on top (Lessons 14 and 18).
- Caching at the edge with fast purge. Tiered Cache (Lesson 19), coreless and instant purge (Lessons 20 and 21), a transient cache for unpopular assets (Lesson 22).
- Counting and analytics at very high event rates. Sliding-window rate limits (Lesson 23), memory-aware probabilistic structures (Lesson 24), Kafka as a paved road (Lesson 25), ClickHouse for analytics and logs (Lessons 26 and 27).
- DDoS and protocol attacks. XDP dropping (Lesson 28), autonomous per-server detection (Lesson 29), Rapid Reset (Lesson 30), SYN queues and cookies (Lesson 31).
- Routing and DNS you do not fully control. The 1.1.1.1 resolver (Lesson 35), RPKI (Lesson 36), and the routing incidents (Lessons 43, 48, 53 and 54).
- Writing or reading postmortems. Lessons 37 to 55 are a library of blameless reports with timelines, contributing causes and fixes.
When NOT to Use It#
- Building your own anycast network, XDP load balancer or proxy at small scale. Cloudflare does this for hundreds of cities and tens of millions of requests per second. A managed CDN and load balancer are the right answer for nearly everyone else.
- A Quicksilver-style global config system for one region. A config service with versioned files and a staged rollout tool is enough.
- Durable Objects-style single-owner actors when a database row lock works. One owner per key is powerful but adds routing and placement complexity.
- Copying fail-open everywhere. Lessons 44 and 50 to 51 show that the right fault behaviour depends on the component. Security gates such as Access correctly fail closed.
- Running both a legacy and a new control system for years. Lesson 48 shows the risk of the sync period. Plan the migration to be short.
- Trusting internal data more than user input. Lesson 50 shows a self-generated file taking down the network.
How to Implement It#
A practical order for applying these lessons to any multi-site service:
- Make every site identical and announce the same addresses, so any site can serve any user (Lessons 1 and 2). Start with one CDN or anycast provider rather than your own ASN.
- Balance at layer 4 with consistent hashing that survives server changes without breaking connections (Lessons 3 and 5).
- Ship config through a versioned, replicated store, and make every consumer keep a last-known-good copy (Lessons 9 to 11 and 50).
- Stage every change, code or config, through employee-only, low-value and canary tiers with health gates and automatic rollback (Lessons 37 and 55).
- Validate machine-generated config like user input. Use bounds, schema, duplicate checks and size deltas, and reject without crashing (Lessons 50 and 51).
- Decide fail-open or fail-closed per component, write it down, and test it under overload (Lessons 44, 47 and 51).
- Keep break-glass access off your own platform and rehearse it every quarter (Lessons 37, 42 and 45).
- Put circuit breakers on mass changes: max-prefix limits in BGP, rate and breadth caps on deletions, buffer-count caps (Lessons 38, 44 and 52).
- Sign ROAs with exact max lengths, enforce ROV, and monitor your prefixes' origins from public collectors (Lessons 36, 43 and 53).
- Map service dependencies by facility and run whole-site loss tests, plus overload tests (Lessons 41 and 44).
The snippet shows steps 3 and 5 together: a config consumer that validates each new file and keeps serving the last good version instead of crashing.
type FeatureFile = { version: number; features: { name: string; type: string }[] };
const MAX_FEATURES = 200;
let active: FeatureFile | null = null; // last known good, used by every request
function validate(next: FeatureFile, prev: FeatureFile | null): string | null {
if (next.features.length > MAX_FEATURES) return "too many features";
const names = new Set(next.features.map((f) => f.name));
if (names.size !== next.features.length) return "duplicate feature names";
if (prev && next.features.length > prev.features.length * 1.2) return "size jump over 20%";
if (prev && next.version <= prev.version) return "stale version";
return null;
}
export function onNewFile(next: FeatureFile, alert: (msg: string) => void): void {
const problem = validate(next, active);
if (problem) {
alert(`rejected feature file v${next.version}: ${problem}`); // keep serving old file
return;
}
active = next; // atomic swap
}
export function scoreRequest(req: Request, model: (f: FeatureFile, r: Request) => number): number | null {
if (!active) return null; // no score: fail open for this module only
try { return model(active, req); }
catch { return null; } // never crash the worker for one module
}| Technology | Fits when |
|---|---|
| Anycast via a CDN or your own ASN | Users worldwide should reach the nearest healthy site on one IP (Lesson 1) |
| XDP and eBPF | Packet filtering or layer 4 balancing at line rate in the kernel (Lessons 2, 3 and 28) |
| Maglev-style consistent hashing | Connection-stable balancing across a changing set of servers (Lesson 5) |
| Pingora or Envoy | A programmable proxy with shared connection pools (Lessons 6 and 7) |
| A replicated KV store for config (Quicksilver-like, etcd, Consul) | Fast, versioned config at every node (Lessons 9 to 11) |
| Workers KV, DynamoDB global tables | Read-heavy global data with eventual consistency (Lessons 12 and 13) |
| Durable Objects or actors (Orleans, Akka) | One owner per key for coordination and counters (Lessons 15 to 18) |
| Kafka | High-volume internal messaging with replay (Lesson 25) |
| ClickHouse | Analytics and logs at millions of rows per second (Lessons 26 and 27) |
| RPKI with ROV and an RTR validator | Protecting your prefixes from origin hijacks (Lessons 36 and 43) |
| RE2 or the Rust regex crate | User- or operator-written patterns that must run in linear time (Lesson 37) |
| Argo Rollouts, Spinnaker | Staged deployments with automatic rollback (Lesson 49) |
| Commit-confirm on routers | Network changes that undo themselves if access is lost (Lesson 39) |
Trade-offs#
| Lesson | Gain | Cost |
|---|---|---|
| Anycast plus uniform servers | Any site serves anyone, attacks spread across all sites | Withdrawals and bad routes are global too |
| Unimog and Maglev | Connection-stable balancing with no dedicated hardware | Kernel-level code and careful hashing to maintain |
| Pingora (Rust) | 70% less CPU and fewer connections to origins | A proxy to own instead of NGINX |
| Quicksilver | Config everywhere in seconds | The same speed carries bad config everywhere |
| Workers KV | Very fast reads near users | Central store dependency on misses |
| Durable Objects | Simple correctness per key | Placement latency and a single owner per key |
| Coreless and instant purge | Purges in milliseconds worldwide | Per-machine indexes and fan-out messaging |
| Autonomous DDoS edge | Detection in seconds on every server | Per-server false-positive risk, tuning |
| Keyless SSL | Customers keep private keys | Extra round trip to the key server on handshakes |
| QUIC and HTTP/3 | Faster handshakes and no head-of-line blocking | Kernel bypass, UDP middleboxes, more CPU |
| RPKI signing | Hijacks of signed prefixes rejected by validators | ROA maintenance and exact max lengths limit flexibility |
| Staged config rollout (after outages) | 1,000× smaller blast radius for bad changes | Minutes of delay for urgent threat data |
| Fail-open data plane | Traffic keeps flowing during config faults | Unscored or uninspected traffic for a while |
Common Pitfalls#
- Treating config as data, not code. WAF rules, feature files and topologies all changed behaviour globally. Give them versioning, staging and rollback.
- Hard-failing on bad internal input. A cap is good, but a panic when it is exceeded is not. Reject the input, keep the old version and alert.
- Recovery tools behind the broken service. Login, CI and admin panels must work when your platform does not.
- Untested fallbacks. Fail-open paths sized years ago, limits never configured, and DR plans never tested with a whole site removed.
- Order-sensitive policies reviewed as text diffs. Use semantic checks on what a policy will actually advertise.
- Defaults that target the wrong environment. Make the target explicit and mandatory for privileged commands.
- Synchronized retries. Add jitter and mark retries, so you can tell a loop from growth.
- Announcing a /24 with a loose ROA. Use exact max lengths, and monitor your prefixes from outside.
- Assuming a "coreless" design has no core. Find the single source of truth every miss depends on.
Real-World Examples#
All from the fetched Cloudflare posts:
- The edge: every server in every data center runs every service, and Unimog balances layer 4 traffic in each data center using XDP (Lessons 2 and 3).
- Pingora replaced NGINX for upstream traffic, using about 70% less CPU and 67% less memory, and cutting new connections to origins by reusing them across threads (Lesson 6).
- Quicksilver replicates configuration to every server, with a p99 of 2.29 s to reach the whole fleet at about 350 changes per second (Lesson 37).
- HTTP analytics ingests about 6 million requests per second into ClickHouse (Lesson 26).
- The July 2, 2019 outage dropped 80% of traffic for 27 minutes because of one backtracking regex (Lesson 37).
- Cloudbleed leaked memory in about 1 in 3.3 million requests at peak, fixed globally in under 7 hours, with 770 cached URIs purged from search engines (Lesson 40).
- The November 2023 PDX outage kept the edge fully up while the control plane failed over to Europe, then needed a full facility bootstrap (Lesson 41).
- The November 18, 2025 outage was the worst since 2019: a doubled bot feature file exceeded a 200-feature limit and panicked the FL2 proxy (Lesson 50).
- The February 20, 2026 BYOIP incident withdrew about 1,100 of 4,306 BYOIP prefixes because an empty query flag meant "all" (Lesson 52).
- Telia, NTT and AT&T were not affected by the 2019 Verizon leak, thanks to Tier 1-in-path filters and RPKI ROV (Lesson 53).
In the Interview#
Deep Dive: designing a small global edge with Cloudflare's lessons, with numbersShow
Take a hypothetical edge service: 20 sites, 40 servers each, 2 million requests per second at peak, a WAF and a bot score per request, and 300 config changes a month.
Capacity per site. 2M requests per second ÷ 20 sites = 100,000 per site on average. Anycast is uneven, so plan for 2× at the busiest sites: 200,000 per site, 5,000 per server. A Pingora-like proxy at about 20,000 requests per second per server (handbook's illustration) leaves 4× headroom for attacks and site failures.
Losing a site. If the busiest site (10% of traffic) withdraws, its 200,000 requests per second spread to its 3 nearest neighbours: about 67,000 extra each, a 33% to 67% rise depending on their base load. The 4× headroom absorbs it. Test it monthly with a real withdrawal (Lesson 41).
Config staging. Stages of 1 site (employees), 2 sites (free tier), 4 sites (canary), then all, with 3-minute bakes. Each change takes about 10 minutes to reach everywhere. With 300 changes a month and a 1% bad rate, that is 3 bad changes, each caught at the first stage, with at most 5% of traffic affected for a few minutes (Lesson 55).
WAF cost. 100 rules at up to 0.05 ms each in a linear-time engine is at most 5 ms of CPU per request, so budget for the worst case. A backtracking engine can take seconds on a bad input, so it would not fit any budget (Lesson 37).
Feature file. About 60 features with a cap of 200. Validation rejects any file with duplicates or a size jump over 20%, and the consumer keeps the last good file (Lesson 50).
Routing safety. One /22 split into four announced /24s, with ROAs at maxLength /24 and origin your ASN only. Max-prefix on each transit session is 10 (Lesson 38). Monitor RIPE RIS and RouteViews for any other origin (Lessons 43 and 53).
Break-glass. An out-of-band SSH path through a separate provider, credentials kept in a hardware-backed vault outside the platform, and a quarterly drill that times "open the console during a simulated outage" (Lessons 37, 42 and 45).
None of these numbers are Cloudflare's; they show how to derive your own from the same rules.
Key Takeaways#
- Making every site identical and announcing the same anycast addresses gives huge leverage and spreads attacks, but means mistakes can also be global.
- Layer 4 balancing with consistent hashing in the kernel (XDP) keeps connections stable as servers come and go, without dedicated hardware.
- A memory-safe, multithreaded proxy with shared connection pools can cut CPU, memory and origin connections at once, as Pingora did.
- Fast global config distribution is a strength only if every change is staged with health gates, versioned and instantly reversible. Seven of the eighteen outages were config or data pushed everywhere at once.
- Treat internally generated files and data as untrusted input: validate them, cap their size, keep the last good version, and never crash on a breach.
- Choose fail-open or fail-closed per component, deliberately. Bot scoring and WAF should keep traffic flowing; zero-trust access should stay closed.
- Recovery tools, logins and CI must not depend on the platform they repair. This single theme appears in at least five Cloudflare outages.
- Hidden dependencies make "highly available" services single-site. Map them and test losing whole facilities, not just pieces.
- Mass changes need circuit breakers: BGP max-prefix limits, deletion rate caps, buffer-count caps and commit-confirm.
- The Internet's routing depends on other networks' filters. Sign ROAs with exact max lengths, enforce ROV, and watch your prefixes from outside.
- Linear-time regex engines, typed languages and per-pointer bounds checks prevent whole classes of outages, but error handling still has to be designed.
- Retries and recoveries create herds. Add jitter, mark retries, re-enable gradually and put admission control in front of shared buffers.