System Design

Core Concepts

CDNs and Edge Compute

The edge is close to your users and far from your data. Every win comes from exploiting the first half, and every failure comes from forgetting the second, which is why a CDN speeds up content it never caches and edge compute can be slower than no edge at all.

Why you are doing this at all

A content delivery network (CDN) is a set of servers that a vendor runs in a few hundred locations near users. Most people think of it as a cache. But a CDN makes your site faster even for content it never caches, and often about three times faster.

The reason has nothing to do with caching. A user in Mumbai is about 200 milliseconds from a server in Virginia, measured as a round trip time (RTT): there and back. Before the browser can send its request, it needs one round trip to open a TCP connection and another for the TLS handshake that sets up encryption. Then the request goes out and the response comes back, which is a third round trip. Three round trips at 200 milliseconds each is 600 milliseconds before the first byte arrives. None of that time is spent in your server or your database.

Now put a CDN server in Mumbai, 5 milliseconds from the user. Each of these locations is a point of presence (PoP). The user's two handshakes now happen with the PoP, at 5 milliseconds each. The PoP already holds an open connection to your own server, which the CDN calls the origin. So the request crosses the ocean once, with no handshake on the way. The origin is the same, the query is the same and nothing comes from the cache. But the time to first byte, how long the user waits for the first byte of the response, falls to about 210 milliseconds.

The same request, with and without a PoP
Time runs down the page. On the left, the browser in Mumbai opens TCP (1), runs the TLS handshake (2) and sends the request (3), each a 200 ms round trip to Virginia, so the first byte arrives at 600 ms. On the right, both handshakes end at the PoP in Mumbai, 5 ms away. The PoP sends the request over a connection that is already open (3), so the first byte arrives at about 210 ms.Time runs down the page. On the left, the browser in Mumbai opens TCP (1), runs the TLS handshake (2) and sends the request (3), each a 200 ms round trip to Virginia, so the first byte arrives at 600 ms. On the right, both handshakes end at the PoP in Mumbai, 5 ms away. The PoP sends the request over a connection that is already open (3), so the first byte arrives at about 210 ms.
Nothing is cached, and the first byte still arrives three times sooner. Time runs down the page. On the left, the browser in Mumbai opens TCP (1), runs the TLS handshake (2) and sends the request (3), each a 200 ms round trip to Virginia, so the first byte arrives at 600 ms. On the right, both handshakes end at the PoP in Mumbai, 5 ms away. The PoP sends the request over a connection that is already open (3), so the first byte arrives at about 210 ms.

All of the PoPs together are called the edge. Here is the useful way to think about the whole topic:

The edge is close to your users and far from your data. Every win comes from exploiting the first half. Every failure comes from forgetting the second.

Caching works because you moved the data to the edge. Ending the handshakes at the PoP, called terminating them, works because it needs no data at all. Edge compute means running your own code at the PoPs. It works for checking a signature, because the key is tiny and can be copied everywhere. But edge compute that queries a database in one region is slower than not using the edge at all. It shortens the first hop, and then every query pays a long trip.

Five things a CDN does, and only one is caching

Designs that treat a CDN as a cache for static files, such as images and CSS, leave most of it unused. A CDN does five things.

Terminating TCP and TLS near the user. The handshake round trips shrink from the distance to your origin to the distance to the nearest PoP. This is automatic, costs nothing extra, and applies to every request, including requests that can't be cached.

Reusing connections to your origin. Each PoP keeps a pool of open connections to your origin, so the trip from the PoP to the origin skips the handshakes. These connections are often tuned as well. TCP starts every connection by sending only a little data and then speeds up. The CDN sets a larger starting amount, called the initial window, so a response needs fewer round trips.

Splitting one long, lossy path into two. The user's connection ends at the PoP, and the PoP has its own connection to the origin. So one long path becomes two short ones. TCP throughput falls as the round trip time grows, and it also falls with the square root of packet loss. So a 200 millisecond path that loses a few packets is much slower than its length suggests. Splitting it can raise the throughput on the lossy part about tenfold.

Absorbing traffic you do not want. Bot filtering, rate limiting and absorbing distributed denial of service (DDoS) attacks happen at hundreds of PoPs rather than at your origin. A DDoS attack is a flood of traffic meant to knock you offline. Capacity at your origin is small and expensive.

Caching. The caching article covers caching in general, so this article covers only what is different about caching at the edge.

When you do not need one

If all your users and your origin are in one region, the distance is small, and a CDN mostly buys you DDoS protection. If every response is different for every user and none of it can be cached, you still get the handshake win. The question is whether that win is worth adding a vendor. And if your server takes 800 milliseconds to render a page, no CDN will fix it. The problem is slow compute, not distance.

The toolkit

The handshake win, counted

Here is the opening claim as a worksheet. It's the number that justifies putting a CDN in front of an application that caches nothing. That application's hit rate, the share of requests answered from the cache, is zero.

Back of envelopeTime to first byte, on content with a 0 percent hit rate
User in Mumbai. Origin in Virginia, 200 ms round trip.
Nearest edge 5 ms away. TLS 1.3, so one round trip.

Straight to the origin
  TCP handshake                    1 RTT       200 ms
  TLS handshake                    1 RTT       200 ms
  request out, response back       1 RTT       200 ms
  ──────────────────────────────────────────────────
  time to first byte                          ~600 ms

Through the edge, cache disabled
  TCP handshake to the edge        1 RTT         5 ms
  TLS handshake to the edge        1 RTT         5 ms
  edge to origin, connection already open,
    so no handshake                1 RTT       200 ms
  ──────────────────────────────────────────────────
  time to first byte                          ~210 ms

  2.9x faster, on a cache hit rate of zero.

A second request on the same connection costs about
200 ms either way, because both paths have already paid
for their handshakes. The win comes on every new
connection, and browsers and apps open new ones often.

And note where the saving is: not in your code, not in your
database, and not in the cache. It is in the two round trips
you stopped making across an ocean.

Why splitting the path helps so much

It seems that splitting a 200 millisecond path into 5 plus 195 should gain nothing. It gains a lot, because of how TCP behaves.

The Mathis equation, published by Matthew Mathis and colleagues in 1997, gives an upper limit on the throughput of one TCP connection:

throughput is roughly the segment size divided by the round trip time, divided by the square root of the packet loss rate.

Two things follow from it. First, throughput is inversely proportional to the round trip time, so halving the RTT doubles the throughput. Second, throughput is inversely proportional to the square root of the loss rate, so a path with 1 percent loss carries about a third of what it would at 0.1 percent. The two multiply, so a long path that also loses packets pays for both at once.

Back of envelopeWhat one long path costs, versus two short ones
Mathis bound: throughput = MSS / (RTT x sqrt(loss))
MSS 1,460 bytes. Valid for small loss rates.

One long path, Mumbai to Virginia
  RTT 200 ms, loss 0.1%
  1,460 / (0.2 x 0.0316)             = 231 KB/s = 1.85 Mbps
  a 2 MB page                        = 8.7 seconds

Split at a nearby edge
  client leg   RTT 20 ms, loss 0.1%  (mobile last mile)
  1,460 / (0.02 x 0.0316)            = 2.31 MB/s = 18.5 Mbps
  a 2 MB page over this leg          = 0.87 seconds

  origin leg runs over the CDN's backbone: low loss, tuned
  congestion control, and a connection that is already open,
  so it is nowhere near the bottleneck

  ────────────────────────────────────────────────────────
  10x the throughput on the leg that has the loss, from
  dividing the round trip time by ten.

The loss did not change. The RTT it multiplies against did,
and because loss and RTT multiply, shortening the lossy leg
is worth much more than the arithmetic of "5 + 195" suggests.
TCP throughput against round trip time
Each line is the Mathis upper limit for one packet loss rate. On the 0.1 percent line, a 20 ms leg carries 18.5 Mbps and a 200 ms path carries 1.85 Mbps, ten times less. The 1 percent line sits about three times lower at every RTT. This is why splitting the path helps a large download that is never cached.Each line is the Mathis upper limit for one packet loss rate. On the 0.1 percent line, a 20 ms leg carries 18.5 Mbps and a 200 ms path carries 1.85 Mbps, ten times less. The 1 percent line sits about three times lower at every RTT. This is why splitting the path helps a large download that is never cached.
Throughput falls with distance, and loss pushes the whole curve down. Each line is the Mathis upper limit for one packet loss rate. On the 0.1 percent line, a 20 ms leg carries 18.5 Mbps and a 200 ms path carries 1.85 Mbps, ten times less. The 1 percent line sits about three times lower at every RTT. This is why splitting the path helps a large download that is never cached.

How a request finds the nearest edge

There are two ways to send a user to a PoP, and each one can send some users to the wrong place.

Anycast. Every PoP announces the same IP address, and internet routing delivers each packet to whichever PoP is nearest by BGP path. BGP, the Border Gateway Protocol, is how networks tell each other which addresses they can reach. Anycast is simple, and it fails over quickly: if a PoP goes down, routing sends its users to another one. The catch is how BGP measures "nearest". It counts hops between networks, called autonomous systems, and follows each network's own routing policy. It doesn't measure latency. So a user can be sent to a PoP that is more milliseconds away than another PoP that routing never picked, and you can't see or control that from your side.

DNS-based steering. The CDN's DNS server, which turns its hostname into an IP address, gives a different answer depending on where the lookup came from. The catch is that the lookup comes from the user's resolver, the DNS server that looks up names on the user's behalf, not from the user. So someone in Jakarta whose resolver is in Singapore gets the answer meant for Singapore. The partial fix is EDNS Client Subnet: the resolver passes along the first part of the user's IP address, which is enough to place them roughly. Not every resolver sends it.

Two ways a user reaches the wrong PoP
With anycast, BGP prefers the route through fewer networks, so this user reaches PoP B, 40 ms away, and never tries PoP A, 10 ms away. With DNS steering, the user's lookup goes to a resolver in Singapore (1), which asks the CDN's DNS (2). The CDN answers for Singapore, so the user in Jakarta connects to the Singapore PoP (3), and the Jakarta PoP sits unused.With anycast, BGP prefers the route through fewer networks, so this user reaches PoP B, 40 ms away, and never tries PoP A, 10 ms away. With DNS steering, the user's lookup goes to a resolver in Singapore (1), which asks the CDN's DNS (2). The CDN answers for Singapore, so the user in Jakarta connects to the Singapore PoP (3), and the Jakarta PoP sits unused.
Routing picks by network path or by resolver, not by distance. With anycast, BGP prefers the route through fewer networks, so this user reaches PoP B, 40 ms away, and never tries PoP A, 10 ms away. With DNS steering, the user's lookup goes to a resolver in Singapore (1), which asks the CDN's DNS (2). The CDN answers for Singapore, so the user in Jakarta connects to the Singapore PoP (3), and the Jakarta PoP sits unused.

You can't fix either of these yourself. But when one group of users has bad latency and nothing in your system explains it, check this first. The usual answer is that they are being sent to a PoP far from them.

Cache keys at the edge, and how cardinality kills you

The cache key is the set of inputs that decides which cached copy a request gets, and it should hold every input the response depends on. At the edge, that's the URL plus whatever you tell the CDN to vary on: headers, cookies, query parameters and device class. To vary on a header means to keep a separate copy for each value of it.

Each input is a dimension of the key, and every dimension you add multiplies the number of distinct objects. That number is the key's cardinality. A PoP can only hold a limited working set, the objects it keeps because they are being read. Past that size the objects stop fitting, and the hit rate falls toward zero. This is the most common way a CDN that looks correctly configured ends up doing nothing.

One URL, 180 cached copies
One page, /pricing, is cached separately for each of 3 encodings, then for each of 3 device classes, then for each of 20 locales. Only one branch is drawn open at each level. The result is 180 copies of one URL, and a per-user cookie, in red, would multiply that by every user.One page, /pricing, is cached separately for each of 3 encodings, then for each of 3 device classes, then for each of 20 locales. Only one branch is drawn open at each level. The result is 180 copies of one URL, and a per-user cookie, in red, would multiply that by every user.
Each dimension multiplies the copies of every URL. One page, /pricing, is cached separately for each of 3 encodings, then for each of 3 device classes, then for each of 20 locales. Only one branch is drawn open at each level. The result is 180 copies of one URL, and a per-user cookie, in red, would multiply that by every user.
Back of envelopeHow a cache key becomes a cache miss
10,000 distinct URLs. Each PoP can hold 100,000 objects
of this size in its working set.

  key dimensions added              distinct objects   fits?
  ──────────────────────────────────────────────────────────
  URL only                                    10,000   yes
  + Accept-Encoding (gzip, br, none)          30,000   yes
  + device class (mobile, tablet, desktop)    90,000   just
  + language (20 locales)                  1,800,000   no, 18x over
  + a per-user cookie (1M users)       1.8 x 10^12     hit rate ~0

At the fourth row, 1 object in 18 is resident. If requests
spread evenly across them, most requests miss and the CDN
is a proxy with extra steps.
At the fifth, every request is unique and the cache is
pure overhead.

The fix is not a bigger cache. It is normalising the key:
  strip query parameters you do not use
  bucket 20 locales into the 3 you actually serve
  bucket device classes into the 2 layouts you have
  never vary on a cookie that identifies a person

  10,000 x 3 encodings x 2 devices x 3 languages
                                   = 180,000 objects
  18x over  →  1.8x over: much closer, still not inside

Tiered caching, and why more locations makes your origin worse

Each PoP has its own cache. So when Mumbai misses, it doesn't help that Frankfurt has the same object cached.

Every PoP misses on its own, so your origin sees roughly one fill request per PoP, per object, per TTL. A fill is the request a PoP sends to the origin for an object it doesn't have. The TTL, or time to live, is how long a cached copy is kept before it expires. If you add more PoPs, latency improves, and the fill traffic at your origin grows in proportion to the number of PoPs.

The fix is a shield tier: an extra layer of cache that the PoPs fill from, so that only the shield fills from your origin.

Back of envelopeWhat 200 locations do to your origin
10,000 popular objects, 60 second TTL, 200 PoPs,
each location serving enough traffic to want every object.

Flat CDN: every PoP fills from origin independently
  fills per TTL   10,000 x 200            = 2,000,000
  origin load     2,000,000 / 60          ≈ 33,000 req/s
  → for cache fills alone, before any real traffic

With a shield tier: PoPs fill from the shield, shield fills
from origin
  fills per TTL at origin                 = 10,000
  origin load     10,000 / 60             ≈ 167 req/s

  ────────────────────────────────────────────────────────
  33,000 → 167, a 200x reduction, and 200 is exactly the
  number of PoPs. The shield collapses N fills into 1.

Doubling your PoP count improves your latency and
doubles your origin fill load. Only tiering breaks that link.
Fills with and without a shield
On the left, each PoP that misses on object A fills it from the origin itself, so the origin answers once per PoP. On the right, the PoPs fill from the shield, and only the shield goes to the origin, once. Six PoPs are drawn, and the worksheet uses 200.On the left, each PoP that misses on object A fills it from the origin itself, so the origin answers once per PoP. On the right, the PoPs fill from the shield, and only the shield goes to the origin, once. Six PoPs are drawn, and the worksheet uses 200.
The shield turns one fill per PoP into one fill in total. On the left, each PoP that misses on object A fills it from the origin itself, so the origin answers once per PoP. On the right, the PoPs fill from the shield, and only the shield goes to the origin, once. Six PoPs are drawn, and the worksheet uses 200.

Every major CDN offers this, under different names. Cloudflare calls it Tiered Cache, which started as part of its Argo product. A PoP that misses asks its nearest upper-tier data centre before going to the origin, and Cloudflare reports about 60 percent fewer cache misses. AWS calls it CloudFront Origin Shield. It combines requests from different regions so that as few as one request per object reaches your origin, and customers report up to 57 percent less origin load. Fastly calls it shielding, and you choose one PoP to act as the shield. These measured cuts are smaller than the worksheet's 200 times, because the worksheet assumes every PoP wants every object, and real traffic is less even than that.

Cloudflare's documentation points out a second benefit. Links between PoPs are shorter and have more capacity than links from a PoP to your origin. So a miss that only travels as far as the upper tier is usually faster than one that reaches your origin.

Origin fill load against the number of PoPs
The red line is a flat CDN, where every PoP fills on its own: 33,000 requests a second at 200 PoPs and 83,000 at 500. The green line is the same CDN with a shield, flat at 167 requests a second however many PoPs there are. The axis is linear, so the green line sits almost on the floor.The red line is a flat CDN, where every PoP fills on its own: 33,000 requests a second at 200 PoPs and 83,000 at 500. The green line is the same CDN with a shield, flat at 167 requests a second however many PoPs there are. The axis is linear, so the green line sits almost on the floor.
Without a shield, every new PoP adds load to your origin. The red line is a flat CDN, where every PoP fills on its own: 33,000 requests a second at 200 PoPs and 83,000 at 500. The green line is the same CDN with a shield, flat at 167 requests a second however many PoPs there are. The axis is linear, so the green line sits almost on the floor.

What the edge absorbs, and why only the edge can

One thing a CDN does can't be done any other way. It follows from the same geography as everything else: the attack traffic you can absorb is the sum of what all your PoPs can carry.

A volumetric denial of service attack sends more traffic than your network link can carry, so it's a bandwidth problem first. Your origin connects to the internet through an uplink, and you can't make that uplink bigger quickly. It might be 10 gigabits per second, or 100 if somebody planned for this. A large attack is measured in terabits per second. Two terabits a second against a 10 gigabit uplink is 200 times its capacity. Nothing you run behind that uplink can help, because the link is full before your software sees any of it.

If the same attack is spread across 300 PoPs, each one sees about 7 gigabits a second. That's ordinary traffic for a location built to serve a whole region. Nothing clever has stopped the attack. Geography has split it into 300 pieces, and your origin, in one place, can't split anything.

A 2 Tbps attack, at the origin and at the edge
The red bar is a 2 Tbps attack, 200 times what your origin's 10 Gbps uplink carries. Split across 300 PoPs, each PoP's share is about 7 Gbps, less than your whole uplink. The axis is linear, so the two small bars are drawn to scale beside the attack.The red bar is a 2 Tbps attack, 200 times what your origin's 10 Gbps uplink carries. Split across 300 PoPs, each PoP's share is about 7 Gbps, less than your whole uplink. The axis is linear, so the two small bars are drawn to scale beside the attack.
Spread over 300 PoPs, the attack is ordinary traffic. The red bar is a 2 Tbps attack, 200 times what your origin's 10 Gbps uplink carries. Split across 300 PoPs, each PoP's share is about 7 Gbps, less than your whole uplink. The axis is linear, so the two small bars are drawn to scale beside the attack.

The same applies to any request you don't want to serve. A web application firewall rule, a bot signature, a block by country and a rate limit all reject a request at the PoP nearest the sender. So the request never uses origin capacity, origin bandwidth or origin egress. Egress is the data you pay to send out of your cloud. Rejecting a request at the edge costs almost nothing. Rejecting it at the origin costs the whole trip there.

This is also the answer to "we cache nothing, so why would we pay for a CDN?" Absorbing attacks is often reason enough. You hope never to need it, and you can't build it yourself.

What it costs, and the case where a CDN costs you more

Latency is the usual reason for a CDN, and it's often not the biggest one. Sending a gigabyte out of a cloud region costs more than sending it from a CDN, often several times more. At any real volume, a CDN cuts the bill as well as the latency.

But there's a trap in the arithmetic, and it comes from cache key cardinality. With a CDN from a different provider than your origin, you pay CDN egress on every byte, and origin egress on every miss as well. So every miss is paid for twice, and a low hit rate means most bytes cost double.

Back of envelopeWhen a CDN is a saving, and when it is a surcharge
100 TB of egress a month, through a third-party CDN.
Origin egress $0.08/GB, close to list price. CDN egress
$0.02/GB, a negotiated high-volume rate; list prices at
this volume are nearer $0.07. Check your own.

No CDN
  100,000 GB x $0.08                        = $8,000

CDN at a 95% hit rate
  CDN egress   100,000 x $0.02              = $2,000
  origin egress  5,000 x $0.08              =   $400
  ──────────────────────────────────────────────────
  total                                     = $2,400
  → 3.3x cheaper, and faster

CDN at a 20% hit rate, after somebody added a locale
dimension to the cache key
  CDN egress   100,000 x $0.02              = $2,000
  origin egress 80,000 x $0.08              = $6,400
  ──────────────────────────────────────────────────
  total                                     = $8,400

  → MORE expensive than having no CDN at all, while also
    adding a hop and a vendor

The break-even hit rate here is where CDN egress equals the
origin egress you avoided: at these rates, about 25%. Below
it, the CDN is a surcharge.

At list CDN prices the break-even climbs towards 90 percent. And if the CDN belongs to the same cloud as the origin, the origin fetch is often free (CloudFront pulling from S3 or EC2 is), so a miss is paid once and the trap disappears. Cost as a design constraint prices both cases. Calculate that break-even once, at your own rates. It turns the hit rate from a performance number into a line on the bill. People pay attention to a bill in a way they don't to a percentage.

Monthly bill against hit rate
The grey line is the $8,000 bill with no CDN. The purple line is the bill with a CDN: $2,000 of CDN egress plus origin egress on every miss. The lines cross at a 25 percent hit rate. At 20 percent the CDN bill is $8,400, and at 95 percent it is $2,400.The grey line is the $8,000 bill with no CDN. The purple line is the bill with a CDN: $2,000 of CDN egress plus origin egress on every miss. The lines cross at a 25 percent hit rate. At 20 percent the CDN bill is $8,400, and at 95 percent it is $2,400.
Below a 25 percent hit rate, the CDN costs more than no CDN. The grey line is the $8,000 bill with no CDN. The purple line is the bill with a CDN: $2,000 of CDN egress plus origin egress on every miss. The lines cross at a 25 percent hit rate. At 20 percent the CDN bill is $8,400, and at 95 percent it is $2,400.

Edge compute: what it actually is

Edge compute means running your own code at the CDN's PoPs instead of in a cloud region. The platforms differ in one decision that explains most of how they behave: do they give you a container, or a sandbox inside a shared runtime?

A container platform starts an operating system process with your language runtime and your dependencies. You can run almost anything you could run on a server. The cost is the cold start, the delay before a new instance can handle its first request, and it's hundreds of milliseconds to seconds.

An isolate platform, such as Cloudflare Workers, runs your code as a V8 isolate. V8 is the JavaScript engine from Chrome. An isolate is a sandbox inside a process that is already running, and it shares that process's engine. There's no operating system process to create, no runtime to start and no dependencies to load. Cold starts are reported at around 5 milliseconds, against hundreds of milliseconds to seconds for containers.

That gap comes from the design, not from tuning, and so do the costs. An isolate has no filesystem, can't run arbitrary native programs and has tight limits on CPU time. It also moves the wall between customers from the operating system kernel into the JavaScript runtime, and that wall is weaker than the one between two processes. So isolates are very good at changing requests and responses, and a poor fit for anything that needs to be a normal server.

What a cold start has to start
On the left, a container cold start creates a process, starts the language runtime and loads your dependencies before your code runs, which takes hundreds of milliseconds to seconds. On the right, the process and the V8 engine are already running, and a cold start only adds one more isolate beside the others, in about 5 ms.On the left, a container cold start creates a process, starts the language runtime and loads your dependencies before your code runs, which takes hundreds of milliseconds to seconds. On the right, the process and the V8 engine are already running, and a cold start only adds one more isolate beside the others, in about 5 ms.
An isolate skips everything a container has to boot. On the left, a container cold start creates a process, starts the language runtime and loads your dependencies before your code runs, which takes hundreds of milliseconds to seconds. On the right, the process and the V8 engine are already running, and a cold start only adds one more isolate beside the others, in about 5 ms.

That makes edge compute good at authentication and signature checks, routing, and assigning users to A/B test groups. It's also good at rewriting requests and responses, redirects, adjusting cached content for the user's location, bot filtering, and building a page from cached fragments. All of these need very little data. They are data-light.

Edge data, which is the actual problem

This is the half people skip. Your code runs in 300 places, and your database runs in one.

Back of envelopeEdge compute without edge data is slower than no edge
User 200 ms from origin, 5 ms from the nearest edge.
Database sits next to the origin, 1 ms away from it.

Handler runs at ORIGIN, makes 3 sequential queries
  client to origin and back                  200 ms
  3 queries at 1 ms each                       3 ms
  total                                     ~203 ms

Handler runs at the EDGE, same 3 sequential queries
  client to edge and back                      5 ms
  query 1: edge to database and back         200 ms
  query 2                                    200 ms
  query 3                                    200 ms
  total                                     ~605 ms

  ────────────────────────────────────────────────────────
  3x SLOWER than not using the edge at all, and it gets
  worse with every query you add, because each sequential
  data access costs a full long-haul round trip.

The rule: at the edge, N sequential data accesses cost
N x RTT. At the origin they cost N x 1 ms. Moving compute
away from data converts cheap calls into expensive ones.
Three queries, from the origin and from the edge
Time runs down the page. On the left, the request crosses to Virginia once, and the three queries (1, 2, 3) take 1 ms each beside the database, so the response is back at about 203 ms. On the right, the request reaches the PoP in 5 ms, but each query is a 200 ms round trip to Virginia, so the response is back at about 605 ms.Time runs down the page. On the left, the request crosses to Virginia once, and the three queries (1, 2, 3) take 1 ms each beside the database, so the response is back at about 203 ms. On the right, the request reaches the PoP in 5 ms, but each query is a 200 ms round trip to Virginia, so the response is back at about 605 ms.
At the edge, every query crosses the ocean. Time runs down the page. On the left, the request crosses to Virginia once, and the three queries (1, 2, 3) take 1 ms each beside the database, so the response is back at about 203 ms. On the right, the request reaches the PoP in 5 ms, but each query is a 200 ms round trip to Virginia, so the response is back at about 605 ms.

So edge compute only wins when the data it needs is tiny and rarely changes, or has itself been moved to the edge. Moving data to the edge raises the consistency question: after a write in one place, how soon do the other PoPs see it? The platforms state their answers plainly.

Eventually consistent edge key-value stores. Eventually consistent means every copy catches up with a write, but not straight away. Cloudflare's Workers KV is the standard example. Reads are fast because they are local. A write takes up to 60 seconds or more to become visible everywhere, and longer in locations that recently read the older value. That's a good deal for data that can be a minute old, and a bad one for data that can't.

Strongly consistent single-instance objects. Cloudflare's Durable Objects give each object exactly one running instance, in one location. The instance handles requests one at a time, so two writes can't interleave, and its storage is strongly consistent: every read sees the latest write. Geographically, that means you get correct answers and you're back to one round trip, because there is exactly one place to talk to. The gain over a regional database is that you choose the location for each object. A document's coordinator, the single instance that orders every edit to it, can live near the people editing it.

Where edge code can keep its data
Each dot is a place to keep data that edge code reads, placed by how long a read takes from the PoP and how stale it can be. Bundled data and an edge key-value store read locally but lag behind writes. A single-coordinator object and a regional database are always current but cost a round trip, and only the coordinator's trip is short, because you place it near its users. The empty corner, fast and current, is the one nothing reaches.Each dot is a place to keep data that edge code reads, placed by how long a read takes from the PoP and how stale it can be. Bundled data and an edge key-value store read locally but lag behind writes. A single-coordinator object and a regional database are always current but cost a round trip, and only the coordinator's trip is short, because you place it near its users. The empty corner, fast and current, is the one nothing reaches.
Nothing is both current and local, so each option picks one. Each dot is a place to keep data that edge code reads, placed by how long a read takes from the PoP and how stale it can be. Bundled data and an edge key-value store read locally but lag behind writes. A single-coordinator object and a regional database are always current but cost a round trip, and only the coordinator's trip is short, because you place it near its users. The empty corner, fast and current, is the one nothing reaches.

The method

1. Split the work into what needs data and what does not. Handshakes, TLS, compression, bot filtering, redirects and header rewriting need no data. They move to the edge at no cost, and you can stop thinking about them.

2. Write the cache key down, explicitly, and count it. Every dimension multiplies the count, so multiply them out and compare the total with what one PoP holds. If you skip this step, a working CDN can turn into an expensive proxy.

3. Ask for the shortest tolerable freshness, not for cacheability. "Uncacheable" is usually false for anything many users share. A one second TTL is invisible to users and removes most of the origin load for that content.

4. Add a shield tier. Without one, origin fill traffic grows with the number of PoPs, and the vendor decides that number, not you.

5. For each edge handler, name the data it reads and where that data is. If the answer is a regional database, the handler belongs in the region.

6. For each piece of edge data, choose the consistency and say the number. Bundled at deploy time, eventually consistent with a stated delay before every PoP sees a write, or one coordinator in a location you chose.

Worked examples, start to finish

There are four systems here, and the obvious approach fails in a different way in each. It skips a CDN that would have helped anyway, configures one so it can't help, adds PoPs that hurt the origin, and moves code away from its data.

An API that is genuinely uncacheable

A JSON API serves data to logged-in users, and each user gets their own data. Nothing can be cached, so the decision seems obvious: no CDN, and the clients talk straight to the origin.

That throws away the handshake win, and for distant users it's the largest single improvement available.

Naive

Skip the CDN, because nothing is cacheable

This follows from its premise, and the premise is wrong: it assumes caching is all a CDN does. Users in distant regions pay three round trips before the first byte. At 200 milliseconds each, that's 600 milliseconds of network time with no server work in it at all. You can spot this in the latency numbers. They track where users are almost perfectly, and not what your service is doing.

Senior

Proxy everything through the CDN, caching nothing

Send all traffic through the CDN with caching turned off. TLS and TCP terminate near the user, the PoP reuses its open connections to the origin, and time to first byte drops from about 600 milliseconds to about 210. You also get DDoS protection, bot filtering and a place to run per-request code later.

The cost is a vendor on the path of every request, and one more place where a configuration mistake can break everything. It's usually worth paying, but it should be a decision you make on purpose, not a side effect.

Staff

Stop believing the word uncacheable

Question the label. "Per-user and uncacheable" is usually two claims in one, and the second one rarely holds up when you look closely.

Split the response. Most endpoints have a large shared part and a small personal part. The product catalogue is shared, and the cart badge isn't. The article is shared, and the reader's position in it isn't. Cache the shared part for as long as you can, and add the personal part at the edge or in the browser.

Then take the parts that are shared but change often, such as prices, stock levels on a product page or a trending list. Ask how stale they can be, rather than whether they can be cached. A one second TTL is invisible to a person and removes almost all of the origin load. Say one shared response gets 10,000 requests a second. With a one second TTL, each PoP sends the origin at most one request a second for it. With a shield, the origin sees one a second in total. That's 10,000 times fewer requests, from a delay nobody can notice. If you add stale-while-revalidate, which lets the PoP serve the old copy while it fetches the new one in the background, no user waits for the refill either.

In numbers: 10,000 requests a second at the origin become about 1, and the cost to users is that the data can be up to one second old.

Origin requests for one shared response
Each dot is the origin requests a second for one response that users ask for 10,000 times a second. With no caching, every request reaches the origin. With a one second TTL, each of 200 PoPs fills once a second, which is 200. With a shield as well, only the shield fills, once a second. The scale is logarithmic, so each step along it is ten times the one before.Each dot is the origin requests a second for one response that users ask for 10,000 times a second. With no caching, every request reaches the origin. With a one second TTL, each of 200 PoPs fills once a second, which is 200. With a shield as well, only the shield fills, once a second. The scale is logarithmic, so each step along it is ten times the one before.
A one second TTL and a shield take 10,000 requests a second down to 1. Each dot is the origin requests a second for one response that users ask for 10,000 times a second. With no caching, every request reaches the origin. With a one second TTL, each of 200 PoPs fills once a second, which is 200. With a shield as well, only the shield fills, once a second. The scale is logarithmic, so each step along it is ten times the one before.

You give up correctness wherever one second matters. That covers real cases: a balance shown before a transaction, the stock count at checkout, and anything users have just changed themselves. Those endpoints stay uncached and get only the handshake win. The work is sorting endpoints into these groups and keeping the sorting up to date as the API changes. That's ongoing work, not a setting you turn on once.

A page that fragments itself out of the cache

A marketing site sits behind a CDN. One person adds localisation, another adds a separate layout for each device type, and a third adds an experiment cookie. Each change is small and correct. The hit rate falls from 96 percent to 20 percent, and nobody can say which change did it. No single change did. Their dimensions multiplied together.

The cardinality worksheet in the toolkit is the whole diagnosis. Three encodings times three device classes times twenty locales is 180 variants of every URL. Across 10,000 URLs that's 1.8 million objects, 18 times what a PoP holds, and adding the language dimension is what pushed it over.

There are four fixes, and the first one usually recovers the most.

Strip what you do not use. Query parameters from ad campaigns, analytics and social sites create a new URL for every click. If ?utm_source=x doesn't change the response, it must not be in the key. This change alone often recovers most of the lost hit rate.

Bucket instead of varying. Browsers send twenty locales, but you serve three languages. So rewrite the header to one of those three before it goes into the key. Do the same for devices: two classes, not the full user-agent string. This rewriting is called normalising the key.

Never vary on identity. A cookie that identifies a person makes every object unique.

Move personalisation out of the key. Cache one shell for everyone: the page with its personal parts left empty. Then fill in the personal parts at the edge or in the browser. This turns a cache key problem into an assembly problem, and assembly is cheap.

Naive

Vary on anything that might matter

This feels safe, and it's how every one of these configurations gets built. Somebody worries that a response might differ by language, so they add Vary: Accept-Language, which tells caches to keep a separate copy for each value of the language header. That's correct, and on the day it costs nothing anyone can see. Over two years, four people each make a call like that, and each call is reasonable. Multiplied together, their choices give a cache that holds one eighteenth of what it needs. Nobody made a mistake, and nobody multiplied.

Senior

Normalise the key down to what actually changes the bytes

Go through the key one dimension at a time and cut each one down to the number of values you serve. Use an allowlist of query parameters, not a blocklist, because new tracking parameters appear all the time and a blocklist is always behind. Collapse twenty locales into the three languages you have translations for. Collapse the full user-agent into two device classes. Leave out anything that identifies a person. On the worksheet's numbers, that takes 1.8 million objects down to 180,000. That's ten times better, and still almost twice what a PoP holds.

Normalising a request before the key
The raw request carries a tracking parameter, a long language header, a full user-agent string and a session cookie. The edge rule keeps only the parameters on its allowlist, maps the language header to one of 3 languages and the user-agent to one of 2 device classes, and drops the cookie. The key that is left has 3 x 2 values for each URL and encoding.The raw request carries a tracking parameter, a long language header, a full user-agent string and a session cookie. The edge rule keeps only the parameters on its allowlist, maps the language header to one of 3 languages and the user-agent to one of 2 device classes, and drops the cookie. The key that is left has 3 x 2 values for each URL and encoding.
Only the values that change the bytes reach the key. The raw request carries a tracking parameter, a long language header, a full user-agent string and a session cookie. The edge rule keeps only the parameters on its allowlist, maps the language header to one of 3 languages and the user-agent to one of 2 device classes, and drops the cookie. The key that is left has 3 x 2 values for each URL and encoding.

The cost: normalising is code on the path of every request, usually at the edge, and it has to stay in step with what the origin varies on. If you normalise to three languages while the origin serves five, users of two of those languages get the wrong content. That's worse than a low hit rate.

Staff

Stop serving one response per audience

Question the idea that a response must be either shared or personal. Almost none is purely one or the other. A typical page is 90 to 95 percent the same for everybody. A few small regions differ: a name, a cart count, a button that depends on permissions, a price in the local currency.

So separate them. Cache one shell for everyone, with a hit rate near 100 percent, and fill in the regions that vary afterwards. There are three ways to do it, and each needs more from you than the one before.

Client-side fill. The shell arrives straight away, and a small extra request fills in the personal parts. Edge assembly. Code at the PoP joins cached fragments into one page. It can be an edge worker or an Edge Side Includes (ESI) tag, a marker in the HTML that tells the CDN which fragment to insert there. Streaming. The origin sends the cached shell first and the personal part later, in the same response.

Here is the difference on the worksheet's numbers. Each URL's 180 variants become one shell per encoding, plus a handful of small fragments shared across pages. The object count falls from 1.8 million to about 30,000 shells plus the fragments, which fits in a PoP's 100,000 with room to spare. The costs reverse too, because origin egress falls with the miss rate.

One shell, filled at the edge
The shell is the same for every user, so the PoP caches one copy and almost every request hits it (1). The price for the user's language is a small cached fragment (2). The name and cart count are the only personal part, and they come from the origin (3). The PoP joins the three into the page the user sees.The shell is the same for every user, so the PoP caches one copy and almost every request hits it (1). The price for the user's language is a small cached fragment (2). The name and cart count are the only personal part, and they come from the origin (3). The PoP joins the three into the page the user sees.
The shared page is cached once, and only the small parts vary. The shell is the same for every user, so the PoP caches one copy and almost every request hits it (1). The price for the user's language is a small cached fragment (2). The name and cart count are the only personal part, and they come from the origin (3). The PoP joins the three into the page the user sees.

You give up three things. The page is now built from parts, which changes how the application renders. A new kind of bug appears, where a cached shell and a fresh fragment disagree. And it's the wrong answer when the personal part is most of the page, which is true of a dashboard and false of almost everything else. A good answer says which pages fit the shell model and which don't, instead of applying it everywhere.

The day you added more locations

Your CDN vendor opens new PoPs, or you move to a plan with more of them. Latency for users improves, and your origin starts seeing fill traffic it has never seen before, in proportion to the new number of PoPs.

This is the tiered caching worksheet in the toolkit: 200 PoPs filling on their own send 200 origin requests per object per TTL. Nobody deployed anything, and your traffic didn't change. Only the number of PoPs did.

The fix is a shield tier, and it costs little: on every major CDN it's a setting you switch on. The reported effects are large. Cloudflare reports about 60 percent fewer misses with Tiered Cache, and AWS customers report up to 57 percent less origin load with Origin Shield.

There are two more things to note while you're there. First, your TTLs and your PoP count now interact. A short TTL that is harmless with a shield gets multiplied by the number of PoPs without one. Second, the shield is a new place where all the misses meet, so it needs its own capacity planning. The "smart" versions of tiering handle that by choosing the upper tier automatically.

Auth at the edge, which works, and the feed that does not

A team wants to move request handling to the edge. There are two candidate pieces of logic, and they end in opposite results.

Validating a signed token, such as a JSON Web Token (JWT). The handler needs only a public key. The key is a few hundred bytes, changes only when you rotate it, and can be bundled with the code or read from an edge key-value store. So the check runs 5 milliseconds from the user, and every request with a bad token is rejected without crossing an ocean. This is close to an ideal edge workload, because rejected requests never use origin capacity at all.

Rendering a personalised feed. The handler needs the list of accounts the user follows, their recent items and the user's preferences. That's several reads, one after another, against a database in one region. The edge data worksheet in the toolkit shows this is three times slower than running the same code at the origin, and every extra query makes it worse.

Naive

Move the handler to the edge and call the existing database

This is the natural first step, and it makes things worse. The thinking is that the edge is nearer to users, so code there must be faster. That's true for the request's first hop and false for every data access after it. The result is a handler slower than the one it replaced. An architecture diagram doesn't show why, because the arrows to the database look the same length whether they start at the edge or at the origin.

Senior

Put the read-mostly data in an edge store, and leave the rest

Sort the reads by how often the data changes. Feature flags, routing rules, access control lists, redirect maps and configuration are read all the time and written rarely. They go into an edge key-value store such as Workers KV, where reads are local. Accept the store's stated delay before a write reaches every PoP, which for Workers KV is up to 60 seconds or more. Put in only data that can safely be a minute old.

Anything that needs current data stays at the origin, and the handler splits in two. The edge does the cheap checks that need little data, and forwards everything else to the origin.

The cost: logic now lives in two places, and everyone has to respect the delay before a write reaches every PoP. Sooner or later, somebody will put something in KV that can't be a minute old.

Staff

Decide per data item, and place the coordinator on purpose

Question the idea that "edge" and "region" are the only two choices. There's a third, and people often miss it.

Some state needs to be correct more than it needs to be fast to read from everywhere. For that state, use a single-coordinator object and choose where the coordinator lives. A shared document's coordinator sits near the people editing it. A rate limiter for one tenant, meaning one customer account, sits near that tenant. A game session sits near its players. You still pay one round trip, just as you would with a regional database. But you chose the location for each object, instead of one region for the whole company, so the trip is short for the people who use that object.

In numbers: a team in Sydney is editing a document. A round trip to a database in Virginia takes 200 milliseconds, and a round trip to a coordinator in Sydney takes about 10. The consistency is the same and the latency is twenty times lower. The gain comes from where you put the object, not from copying it.

A coordinator placed near its users
A team in Sydney edits one document. On the left, every edit goes to the company's database in Virginia, a 200 ms round trip. On the right, the document's single coordinator runs in Sydney, about 10 ms away, and still orders every edit in one place. A second document, edited from London, gets its own coordinator in London.A team in Sydney edits one document. On the left, every edit goes to the company's database in Virginia, a 200 ms round trip. On the right, the document's single coordinator runs in Sydney, about 10 ms away, and still orders every edit in one place. A second document, edited from London, gets its own coordinator in London.
Same consistency, one twentieth of the round trip. A team in Sydney edits one document. On the left, every edit goes to the company's database in Virginia, a 200 ms round trip. On the right, the document's single coordinator runs in Sydney, about 10 ms away, and still orders every edit in one place. A second document, edited from London, gets its own coordinator in London.

You give up a lot for this. You now own a placement decision for every object, and a wrong placement is worse than the regional default because it's harder to see. Objects whose users move around, or that are used from everywhere, have no good home. And this only works for state that splits cleanly by who uses it. A global leaderboard, or a stock count shared by all users, doesn't split that way and should stay in one region. A good answer says which of your state splits cleanly and which doesn't.

Where it goes wrong

These are ordered by how often they turn up.

1. Treating a CDN as a static asset cache

This is the biggest missed win. Handshake termination, connection reuse and path splitting apply to every request, including requests with a zero percent hit rate. For a dynamic application, they're usually worth more than the cache. If your CDN only sits in front of /static, you're using a small part of what it does.

2. Cache key cardinality

Dimensions multiply. The usual sources are query parameters you don't read, headers you vary on just in case, and above all cookies. On most CDN configurations, the change worth the most is removing unused query parameters from the key.

3. No shield tier

Origin fill load is proportional to the number of PoPs. Unusually, this gets worse when your vendor improves, so nothing in your own change log explains it.

4. Edge compute that reads a distant database

Each data access made one after another costs a full round trip to the distant region, so N queries cost N x RTT. The handler ends up slower than the origin version it replaced. Ask what data the code reads before deciding where the code runs.

5. Purge as an invalidation strategy

A purge tells every PoP to drop a cached object. It works, but it's a request to hundreds of PoPs. It usually takes seconds to reach all of them, sometimes minutes, and vendors limit how fast you can send purges. A design that purges on every write has tied its write path to a global fan-out, where one message is copied to every PoP. Short TTLs with stale-while-revalidate, or versioned URLs, are both better, and neither can fail halfway. The caching article makes the general case: the best invalidation is a key that changes.

6. Believing "nearest" means nearest

Anycast picks a PoP by BGP path, and DNS steering picks one by the resolver's location. Both are usually right, and now and then they send a group of users to a distant PoP. When one country's latency has no explanation, check this first, even though you can't control it.

7. Never testing the origin without the CDN

Once your CDN answers 95 percent of requests, your origin is sized for 5 percent of traffic. The CDN is then something your availability depends on, not an optimisation. The caching article has the arithmetic. At the edge, the version to watch for is a configuration mistake that turns off caching everywhere. That one change multiplies your origin traffic by twenty.

8. Personalisation that defeats caching when assembly would not

If a page is 95 percent shared and 5 percent personal, caching none of it is a choice. If you cache the shell and fill the personal part at the edge or in the browser, the shared 95 percent is cached for everyone. Teams often decide the opposite because the personal part is what they were looking at.

If you memorise nothing else

factwhy it matters
The edge is close to your users and far from your dataevery win and every failure comes from one half of that
A CDN speeds up content it never cachesthree round trips become one, at 0 percent hit rate
600 ms to first byte becomes about 210 msTCP and TLS handshakes move next to the user
TCP throughput falls with RTT and with the square root of lossso they multiply, and splitting the path beats the arithmetic
Cache key dimensions multiply, they do not addthree encodings times three devices times twenty locales is 180
Never vary the cache key on a cookie that identifies a personhit rate zero, unbounded objects, and a leak risk
Stripping unused query parameters is the cheapest big winad campaign parameters make every click a unique URL
Origin fill load is proportional to the number of PoPs200 locations means 200 fills per object per TTL
A shield tier collapses N fills into onereported at about 60 percent fewer misses and up to 57 percent less origin load
More PoPs improves latency and worsens origin loadand your vendor decides your PoP count, not you
"Uncacheable" usually means nobody considered a 1 second TTL10,000 req/s becomes about 1, invisibly
Isolate cold starts are around 5 ms, containers hundreds to thousandsarchitectural, and the costs are architectural too
At the edge, N sequential data reads cost N round tripswhich can be 3x slower than not using the edge
Eventually consistent edge KV: up to 60 seconds to propagatefine for config, wrong for anything a user just changed
A single-coordinator object lets you choose the locationsame consistency as a regional database, chosen per object

What is expected at each level

Mid-level

Know that a CDN caches content at locations near users, and that the cache key decides which requests count as the same response. Know that the TTL controls freshness. Be able to say why a user far from your origin is slow.

You are not expected to raise handshake termination, cardinality arithmetic or edge data consistency unprompted. You are expected to answer sensibly when asked. If you're asked whether a CDN is useless for per-user content, a good mid-level answer is "the caching part is, but it would still terminate TLS near the user, which saves round trips."

The mistake to avoid is describing a CDN as only for images and CSS. Say what happens to dynamic requests too.

Senior

You lead this part of the conversation, and three things should come up without prompting.

The cache key, written out. Not "we cache the page", but the actual list of dimensions and roughly how many values each has. Multiply them out during the conversation. That's the most useful thing you can do here, because it's where real configurations fail.

The handshake win for uncacheable content. If you say a CDN helps even at a zero percent hit rate, and why, you show you understand what you're buying.

A shield tier, with the reason. Origin fill grows with the number of PoPs. Senior candidates miss this more often than anything else here, because nothing in their own system changes when it starts to hurt.

Two things are disqualifying: proposing edge compute that reads a regional database without noticing it's slower, and varying a cache key on a session cookie.

Staff+

The question moves from how to configure a CDN to what the edge should be responsible for.

Sort the work by data dependency before deciding placement. Each piece of logic needs one of five kinds of data: none, bundled with the code, in an edge store with a stated delay, behind a single coordinator, or in a region. That list is the design. Once you know the kind, where the logic runs follows directly.

Challenge the word "uncacheable" every time you hear it. Ask how stale the content may be instead, and split shared content from personal content. This is usually the largest win available, and it's a conversation with the product team, not an infrastructure change.

Treat the cache key as a reviewed interface. Keep it in one place, documented, with the number of values for each dimension noted. Any team can damage it with a one-line change that nobody notices.

Say what staleness each piece of edge data may have, in seconds. A 60 second delay before every PoP sees a write is fine for feature flags and unacceptable for something a user just edited. The only way to keep that straight is to write the number down for each item.

And say what you would not build. Each of these can cost a team a whole quarter.

A globally replicated edge database for data that three endpoints read, when an eventually consistent key-value store with a stated 60 second delay would have done. A data-heavy handler moved to the edge, where it's measurably slower than in the region. A pipeline that purges hundreds of PoPs on every write, when a one second TTL with stale-while-revalidate needed no pipeline at all.

A second CDN vendor for redundancy, before anyone has tested whether the origin survives without the first one. Per-user page caching, which gives a cache with a hit rate of zero. And a custom edge routing layer, when the real problem was ad campaign query parameters in the cache key.

Sources

Every figure attributed to a vendor or paper below comes from that published source. The latency, throughput, cardinality and fan-out arithmetic is worked in the article with its inputs stated.

  • The Mathis bound on TCP throughput, from Matthew Mathis and colleagues, 1997. Throughput is bounded by the maximum segment size, divided by the round trip time, divided by the square root of the packet loss rate. The model holds for small loss rates. Summarised at NetCraftsmen and ThousandEyes.
  • Tiered Cache and Argo, Cloudflare. That a PoP which misses asks its nearest upper tier before going to origin. That PoP-to-PoP links are generally shorter and better provisioned than PoP-to-origin links. And the reported roughly 60 percent reduction in cache miss rate.
  • Announcing Amazon CloudFront Origin Shield, AWS. Collapsing requests across regions so that as few as one request per object reaches the origin, with customers reporting up to 57 percent less origin load.
  • Cloud Computing without Containers and Eliminating cold starts with Cloudflare Workers, Cloudflare. V8 isolates as sandboxes inside a shared runtime rather than operating system processes, and cold starts of around 5 milliseconds. Hence the constraints: no filesystem, no native binaries and tight CPU limits.
  • How KV works and Choosing a data or storage product, Cloudflare. That Workers KV is eventually consistent, with writes taking 60 seconds or more to become globally visible, and longer delays in locations that recently read an older value. And that Durable Objects give each instance one location, sequential request handling, and strongly consistent storage.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.