How CDNs Work: Cache Keys, TTLs, and Origin Shield
A CDN is the only component in a typical architecture that makes a system faster by doing nothing clever. It does not shard better, index better, or batch better. It just moves a copy of the bytes closer to the person asking for them, and distance turns out to be the single largest term in most page-load budgets. That is also why CDN questions separate candidates quickly: everyone knows to draw the box, and almost nobody can say what the cache key is, why their hit ratio is 60% instead of 98%, or what happens to the origin the moment someone clicks "purge everything".
This post works through the arithmetic that justifies the edge, how a request actually finds a nearby point of presence, the cache key and TTL mechanics that decide whether any of it works, why tiered caching matters more as you add locations, and the failure modes — including one that is a data leak rather than a slowdown.
The arithmetic that justifies the edge
Light in fiber travels at roughly two-thirds of its vacuum speed: about 200 km per millisecond. London to Ashburn, Virginia is about 5,900 km great-circle, so the theoretical one-way time is 29.5 ms and the theoretical round trip is 59 ms. Real paths are not great circles, so measured RTT on that route sits around 75 ms.
The reason that number hurts more than it looks is that a cold HTTPS request costs multiple round trips before a single byte of content moves:
TCP handshake (SYN, SYN-ACK) 1 RTT
TLS 1.3 handshake 1 RTT
HTTP request → first byte 1 RTT
-------
3 RTTs × 75 ms = 225 ms
Add origin processing and you are at roughly a quarter of a second before the browser can start parsing. Nothing in your code caused it. You cannot optimise a query to recover it.
Now put a point of presence in London, 5 ms from the user. The same three round trips cost 15 ms, and on a reused connection — which is the common case, because the edge keeps connections alive — a cache hit is a single round trip at 5 ms.
The hit ratio then decides your average. Call an edge hit 5 ms and a miss 105 ms (5 ms to the edge, 80 ms RTT to origin, 20 ms of origin work):
| Hit ratio | Effective latency |
|---|---|
| 50% | 0.5 × 5 + 0.5 × 105 = 55 ms |
| 80% | 0.8 × 5 + 0.2 × 105 = 25 ms |
| 95% | 0.95 × 5 + 0.05 × 105 = 10 ms |
| 99% | 0.99 × 5 + 0.01 × 105 = 6 ms |
Going from 80% to 95% is a 2.5× improvement in average latency without moving a single server. Everything in the rest of this post is in service of that one number, which is why "what's your cache hit ratio and what's fragmenting it" is the question a good interviewer asks next.
How a request finds a nearby edge
There are two mechanisms in production use, and knowing which one a provider uses tells you how it fails.
BGP anycast. The same IP address is advertised from every PoP. Internet routing delivers your packet to whichever PoP is topologically nearest, and the client never knows there were others. Cloudflare and Fastly work this way. Failover is implicit: withdraw the route at a sick PoP and traffic reroutes in seconds, with no DNS TTL to wait out. The weakness is control — BGP optimises for AS-path length, not latency, so "nearest" is occasionally wrong, and you cannot easily steer a specific slice of traffic away from an overloaded PoP.
DNS-based mapping. The hostname is a CNAME into the provider's zone, and their authoritative nameserver returns different A records depending on where the query came from. Akamai and CloudFront work this way. It gives much finer control: you can weight PoPs by real-time load and use measured latency rather than topology.
Its historical weakness is that the provider sees the resolver's location, not the client's. A user in Lagos on 8.8.8.8 could be mapped from a Google resolver node far away. EDNS Client Subnet (RFC 7871) fixed most of this by letting resolvers forward a truncated client subnet, but privacy-focused resolvers deliberately omit it, so a slice of your traffic is still mapped blind. The other weakness is that failover is bounded below by DNS TTL plus however long clients and middleboxes ignore it — which, in practice, is longer than the TTL you set.
If I were choosing, I would take anycast for anything where availability dominates, because "withdraw a route" is a far more reliable lever under stress than "hope caches respect a 20-second TTL". For workloads where a specific PoP needs to absorb a known traffic shape — large-object video, regional egress pricing — DNS steering earns its complexity. In an interview, naming both and saying which failure mode you care about is the whole answer; the layer-4 and layer-7 distinctions in load balancing algorithms apply inside each PoP once the packet arrives.
The cache key is the whole game
A CDN entry is keyed, by default, on roughly the request method, host, path, and full query string. Two requests that differ in any of those are two objects, even when the origin would return identical bytes.
This is where hit ratios die, and almost always for the same reason: analytics parameters.
Run the second case for an object that gets three requests per TTL at a given PoP, which is what most of a large catalogue looks like. With one key you get one miss and two hits. With 40 variants, all three requests land on different keys and all three miss. Fragmentation does not reduce the hit ratio proportionally; it annihilates it in the tail.
The fix is cache key normalisation at the edge: strip or allow-list query parameters before the lookup.
# Fastly VCL — normalise before the cache lookup happens.
sub vcl_recv {
# Keep only parameters that change the response; drop the rest.
set req.url = querystring.filter_except(req.url,
"page" + querystring.filter_sep() + "sort");
# Stable parameter order, so ?a=1&b=2 and ?b=2&a=1 are one object.
set req.url = querystring.sort(req.url);
}
The same idea on CloudFront is a cache policy that lists exactly which query strings, headers and cookies participate in the key; on Cloudflare it is a Cache Key template. The mechanism differs, the discipline does not: a parameter belongs in the cache key only if it changes the bytes.
Vary is the same trap wearing a different hat. The response header Vary: Accept-Encoding is correct and cheap, because CDNs normalise it to two or three buckets. Vary: User-Agent is a catastrophe: there are thousands of distinct UA strings in real traffic, so you have just multiplied your object count by thousands. If you need device-class variation, vary on a header you control and that has three possible values, not on the raw UA.
TTLs, revalidation, and the two headers that matter most
The origin controls caching through Cache-Control, and the field candidates most often miss is that browsers and CDNs can be told different things:
Cache-Control: public, max-age=60, s-maxage=86400, stale-while-revalidate=600, stale-if-error=86400
Surrogate-Key: article-8821 author-42 homepage
ETag: "8f3c1b-9a2"
max-age=60— the browser may reuse this for 60 seconds.s-maxage=86400— shared caches, meaning the CDN, may reuse it for a day. This split is the useful one: you want a long edge TTL, because you can purge the edge, and a short browser TTL, because you cannot.stale-while-revalidate=600— for 10 minutes after the edge TTL expires, serve the stale copy immediately and refresh in the background.stale-if-error=86400— if the origin returns 5xx or times out, keep serving the stale copy for a day rather than passing the error through.ETag— on revalidation, the edge sendsIf-None-Matchand the origin can answer304 Not Modified, saving the body bytes but not the round trip.
stale-while-revalidate is the highest-value header on this list. Without it, the unlucky request that arrives one millisecond after expiry pays the full origin round trip — so your p99 contains a cliff that your average hides. With it, no user ever waits for a refresh.If you add one header to a design, add that one. It converts cache expiry from a user-visible event into a background job.
Why more PoPs can mean a worse hit ratio
Here is the counterintuitive part, and a strong thing to volunteer unprompted.
Each PoP has its own cache. Adding PoPs divides your traffic among more independent caches, so each object is requested less often per PoP. Hit ratio depends on request rate per object per PoP, not on total traffic. Scaling out locations improves latency on a hit and makes hits rarer.
The origin feels this directly. Take 1,000,000 distinct objects, 100 PoPs, and a one-hour TTL. In the worst case each PoP fetches each object once per TTL:
1,000,000 objects × 100 PoPs × 24 hours = 2.4 billion origin requests/day
≈ 27,800 req/s sustained
Your origin is now serving 27,800 requests per second for content that changes once a day. That is the CDN generating load, not absorbing it.
The fix is tiered caching, sold as origin shield. Edges miss to a small number of regional parent caches; only the parents talk to the origin.
With 5 shields instead of 100 edges talking to the origin, the same workload drops to 1M × 5 × 24 = 120 million origin requests per day, about 1,390 req/s. The reduction is exactly the fan-in ratio.
On top of that, every serious CDN does request collapsing: if 10,000 clients hit a PoP simultaneously for an object that is not cached, one request goes upstream and the other 9,999 wait on it. That is the same thundering-herd defence described in caching strategies, implemented for you. It is worth knowing it exists, because the obvious interview follow-up — "what happens when a popular object expires everywhere at once?" — is answered by collapsing plus stale-while-revalidate, not by hope.
Purging is the hard part
Caches are easy to fill and awkward to empty. There are three approaches, in increasing order of how much I like them.
Purge by URL. Works, needs you to know every URL affected by a change. Fastly advertises global purge in the low hundreds of milliseconds; most providers land somewhere in seconds. Fine for "I republished one article".
Purge by tag. The origin labels each response with Surrogate-Key (Fastly) or Cache-Tag (Cloudflare Enterprise), and you purge a tag. An article page tagged article-8821 author-42 homepage can be invalidated along with every listing page that embeds it, in one call, without you tracking the URL graph. This is the right tool for content-managed sites and it is underused.
Don't purge — version the URL. Build assets to a content hash and serve them immutable:
GET /static/app.3f9a1c7e.js
Cache-Control: public, max-age=31536000, immutable
A changed file is a different URL, so there is nothing to invalidate and nothing can be stale. The old object ages out on its own. This is what I would do for every asset a build step touches, and it is strictly better than any purge strategy, because the correctness no longer depends on an API call succeeding.
That leaves a clean split worth stating as a position: immutable, year-long TTLs for fingerprinted assets; short s-maxage plus stale-while-revalidate plus tag-based purge for HTML and API responses. The one thing to never do is purge everything on a busy site — you have just set the hit ratio to zero globally and pointed full traffic at an origin sized for 5% of it.
The edge still helps when nothing is cacheable
A POST /checkout cannot be cached. It can still be meaningfully faster through a CDN, and this is the point candidates most often miss.
The edge terminates TLS 5 ms from the user, so the handshake round trips are local. It then reuses a long-lived, already-warm connection to your origin — frequently over an optimised backbone path rather than the public internet. On a 100% uncacheable request you still save two of the three round trips: 225 ms becomes roughly 5 ms of local handshake plus one 80 ms origin round trip, around 90 ms.
Beyond that, edge compute (Cloudflare Workers, Lambda@Edge, Fastly Compute) lets you do the cheap parts of a request near the user: auth token validation, A/B bucket assignment, redirects, geo-routing, serving a cached shell and personalising it client-side. Keep it small. Logic at the edge runs in hundreds of locations you cannot easily debug, and it is the wrong place for anything that needs your database.
What a CDN does not solve
Write latency. Caching is a read-path optimisation. A user in Sydney writing to an origin in Virginia still waits for Virginia, minus the handshake savings. Fixing that is a data problem — multi-region placement and the failover consequences in database replication — not an edge problem.
Per-user content. A personalised feed has a hit ratio near zero by construction, because the cache key necessarily includes the user. The usable pattern is splitting the response: cache the shell and the shared fragments aggressively, fetch the personalised slice separately. Pretending a logged-in homepage is cacheable is how you get the next failure.
Cold and long-tail content. PoP storage is finite and evicts by LRU. An object requested once an hour at a PoP under memory pressure may be evicted before its second request, so it never hits no matter what TTL you set. Tiered caching is the mitigation; for a genuinely enormous catalogue with flat demand, the honest answer is that most requests will miss and your origin must be sized for it.
Origin capacity. Every number above assumed the origin can serve the misses. A purge-all, a TTL expiring across all PoPs simultaneously, or a cache-key change shipped behind a flag flip all produce the same event: full traffic at a cold cache. Design the origin for the miss storm, not the steady state.
Correctness, and this one is a security bug. If the origin returns a response containing Set-Cookie or user-specific data without Cache-Control: private or no-store, a shared cache will store it and serve one user's page — session cookie included — to the next. This is a recurring class of real-world incident, not a hypothetical. The rule: anything user-specific is marked private at the origin, and the CDN is configured to bypass the cache when an auth cookie is present. Verify it with a test, because the default on both sides is to trust the other.
The alternatives worth naming
Multi-region active-active origins. If writes are the problem, or if the dynamic share of your traffic is large enough that cache hit ratio barely moves the average, the answer is moving the application closer, not the bytes. More expensive and much harder to keep correct, but it is the only thing that fixes write latency.
Object storage as the origin. S3 or GCS behind CloudFront or Cloudflare R2 with zero egress fees. For static sites and media this removes the origin tier entirely, and your "miss storm" problem becomes someone else's capacity planning.
Multi-CDN with RUM-based steering. NS1, Cedexis and similar services measure real user latency per provider per region and steer DNS accordingly. The reason to do it is not performance, it is that a single CDN having a bad day is a correlated global failure — several of the most visible internet outages of the last decade were exactly that. The cost is that cache hit ratio splits across providers, so you pay in origin load for the independence.
Running your own edge. Varnish or nginx in a handful of colocation sites. Worth it when egress volume makes commercial CDN pricing the dominant line item, or when you need control a provider will not give you. Netflix Open Connect is the extreme version — purpose-built appliances inside ISP networks — and it exists because at their volume no general-purpose CDN economics work.
Answering it in an interview
CDN questions rarely arrive labelled. "How do users in Europe get this quickly?" is one. "What's in front of your API?" is one. "Why is your p99 so much worse than your median?" is often one. The order that lands:
- Justify it with distance, not vibes. "The London–Virginia round trip is about 75 ms, and a cold HTTPS request is three of them, so 225 ms before the first byte is pure geography."
- Say what you are caching and what the key is. Not "I'll put a CDN in front" — "static assets with content-hashed URLs and a one-year immutable TTL, article HTML with
s-maxageof a day keyed on path only, with UTM parameters stripped." - Volunteer the fragmentation risk. Query parameters and over-broad
Varyare the usual reasons a real hit ratio is 60%, and naming them shows you have operated one of these. - Name
stale-while-revalidateand say what it fixes. It removes the latency cliff at expiry. That is a p99 answer, and p99 is what the interviewer is usually probing. - Bring up tiered caching before being asked. One hundred independent caches multiply origin load by one hundred; shields divide it by the fan-in ratio.
- Give the purge strategy, then say what it costs. Versioned URLs where you can, tag purge where you cannot, and never purge-all under load.
- Close the loop on the things it does not fix — writes, personalised responses, and the
privateheader that stops you serving one user's session to another.
Point 7 is the one that changes how an interviewer reads the rest of your answer. A candidate who draws a CDN box has recognised a pattern; a candidate who says "and here is the request that must not be cached, and how I would prove it isn't" has run one in production, or at least thought like someone who has.
If you want to hear how this holds up when someone interrupts to ask what your origin does the second after a purge-all, you can practise it out loud in a voice system design mock on Whitepad.
Practice this out loud
Reading is the easy part. Sit across from a senior AI interviewer that talks, watches your whiteboard, and scores you like the real thing — your first mock is free.
Start a free mock →