Course contents

14. Cloud and Infrastructure Lesson 6 of 8

Content Delivery Networks

See an edge cache cut latency for distant users, how hit ratio sets origin load, what TTLs and purges do, and why many PoPs need an origin shield.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A CDN answers requests from caches in PoPs near users; only misses travel to the origin.
  • Origin load = traffic × miss ratio; misses also set the latency tail.
  • Cache-Control (max-age, s-maxage, no-store, private, stale-*) tells the CDN what it may cache and for how long.
  • A full purge briefly turns the CDN off; prefer versioned asset names and targeted purges.
  • Every PoP caches separately; an origin shield collapses their misses into one tier in front of the origin.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A content delivery network is a large, shared fleet of caching reverse proxies placed in many points of presence (PoPs) around the world. Your domain points at the CDN; users are routed to a nearby PoP (by DNS answers or by anycast routing), and the PoP answers from its cache when it can. When it cannot, it fetches the object from your origin (an application, a load balancer or an object storage bucket), returns it and keeps a copy for later requests.

Why it exists

Distance costs time. A user 80 ms away from your origin waits at least 160 ms per round trip, and a page load involves many round trips: DNS, TCP and TLS handshakes, then dozens of requests. Moving copies of content near users removes most of that distance. It also removes load: requests answered at the edge never reach the origin, so the same origin can serve far more users, and traffic spikes and many kinds of attack are absorbed by the CDN's capacity instead of yours.

How it works

Hits and misses. On a hit the PoP returns the cached object. On a miss it fetches from the origin (or from a parent tier), stores the result if it is cacheable and returns it. Origin load is roughly traffic × miss ratio: going from a 90% to a 96% hit ratio cuts origin traffic by more than half. Because misses take the long path, the latency tail (P95, P99) is set by misses even when the median looks excellent.

Cache-Control. The origin controls caching through response headers. max-age sets how long any cache may reuse a response; s-maxage overrides it for shared caches such as CDNs. no-store forbids storing it, private allows only the user's browser to store it. stale-while-revalidate lets a cache serve a slightly stale copy while it fetches a fresh one in the background; stale-if-error lets it serve a stale copy when the origin fails. Validators (ETag, Last-Modified) let an expired copy be revalidated cheaply with a conditional request.

Cache keys. By default an object is identified by host and path, often plus the query string. Anything else that changes the response (a header via Vary, a cookie, a device class) has to be part of the key, and everything in the key fragments the cache. Normalise and drop parameters that do not change the response.

Changing content. Two ways: versioned URLs (put a content hash in the file name, cache for a year, reference the new name on deploy) and purges (tell the CDN to drop objects by URL, tag or prefix, or everything). Purges typically reach all PoPs within seconds to minutes, depending on the provider, but every purged object then has to be fetched again.

Tiered caching and origin shield. Each PoP has its own cache, so a file popular everywhere is fetched once per PoP per expiry. An origin shield (or tiered cache) adds a shared parent cache, usually close to the origin: PoPs fetch from the shield, and only the shield goes to the origin. Expect a modest hit ratio at the shield itself: it only sees what the edges missed, the long tail. It pays off anyway, because each of its hits saves an origin fetch that every PoP would otherwise make on its own.

When to use it

  • Static assets (scripts, styles, fonts, images), media and video segments, software downloads.
  • Public, shared API responses where a few seconds of staleness are fine (product listings, scores, feeds that are the same for everyone).
  • Any public website, for TLS termination near users, DDoS absorption and HTTP/2 and HTTP/3 support, even when the cache hit ratio is modest.

When not to

  • Highly personalised or private responses, unless you design keys and controls very deliberately; a mistake serves one user's data to another.
  • Content that must never be stale and changes on every request.
  • Internal traffic between services in one region: the round trip to a PoP adds latency instead of removing it.

Trade-offs

Choice You gain You pay
Longer TTL Higher hit ratio, lower origin load Staler content, more reliance on purges
Versioned asset names Cache forever and deploy instantly Build tooling to fingerprint and rewrite references
Origin shield Far fewer origin requests across many PoPs An extra hop on shield misses, one more tier to purge
Wider cache key (more headers, cookies, params) Correct variants per user group Fragmented cache, lower hit ratio
stale-while-revalidate / stale-if-error Smooth refreshes, resilience to origin failures Users may briefly see outdated content

Alternatives

  • Serve from the origin with a regional cache or reverse proxy: enough when users are close to the origin.
  • Multi-region origins: full application stacks near users, needed for dynamic, personalised responses that cannot be cached.
  • Edge compute: run small functions at PoPs (redirects, header logic, A/B assignment, authentication checks) without a round trip to the origin.

Failure modes

  • Purge storms: purging everything sends a burst of misses from every PoP to the origin.
  • Cache-key leaks: caching a response that depends on a cookie or authorization header without keying on it serves private data to other users.
  • Low hit ratio from fragmentation: tracking parameters, random query strings or Vary: User-Agent create millions of distinct entries.
  • Origin outage: without stale-if-error, cached objects stop being served as soon as they expire.
  • CDN outage or misconfiguration: the CDN itself is a dependency; a bad configuration push can take down every site behind it. Some teams keep a second CDN or a direct-to-origin fallback for critical paths.

In production

Measure hit ratio (by requests and by bytes), origin request rate, and errors and latency per PoP. Set explicit Cache-Control headers on every response instead of relying on defaults. Fingerprint static assets. Use targeted purges by URL or tag. Enable an origin shield in front of small or expensive origins. Restrict the origin to accept traffic only from the CDN (signed headers, private buckets with origin access controls) so attackers cannot bypass it.

Common misconceptions

  • "A CDN is only for static files." Short-TTL caching of shared dynamic responses and edge TLS termination help dynamic sites too.
  • "A 90% hit ratio means the origin is almost idle." It still sees 10% of all traffic, and that share jumps when the ratio drops.
  • "Purging is free." Every purged object must be refetched by every PoP that needs it.
  • "TTL guarantees freshness." It is an upper bound on reuse, not a promise of fresh content; clients and intermediate caches may hold copies too.

Interview angle

Put a CDN in front of static content and media by default and say what it buys: latency, origin offload, DDoS absorption. Then show depth: hit ratio and origin load arithmetic, Cache-Control choices, versioned assets instead of purges, cache keys for semi-personalised content, origin shield for many PoPs, and how the origin is protected and sized for a cold cache. For video or large downloads, mention that bytes served from the edge dominate the cost.

Model assumptions

The simulation is a simplified model, not a benchmark. Users request 2,000 cacheable files with Zipf(1) popularity at random (Poisson) times. The origin is modelled as a store with 10 concurrent requests and a 40 ms mean response time (about 250 requests per second); waiting more than 300 ms for a slot fails the request. Each PoP is a fast proxy (1 ms) with an LRU cache of 300 files that stores a copy after every origin fetch. TTLs are compressed: 3 simulated seconds stand in for minutes. A purge is modelled as the edge cache restarting empty. stale-if-error and stale-while-revalidate are described, not simulated. The origin shield is a proxy with its own 1,000-file LRU cache. Every cache stores whatever its next hop answers, so an edge cache also keeps copies the shield served, and the shield sees only the PoPs' real misses (its hit ratio, about a third, is the honest result of that). One-way latencies are fixed: users to a nearby PoP 8 ms, Europe to the origin 75–80 ms, North America 20 ms, Asia 90 ms. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every request crosses an ocean

    Users in Europe load images, scripts and videos from an origin server in North America, about 80 ms away in each direction. At 150 requests per second the origin is comfortable, but every request pays the full trip: a median of about 200 ms before the first byte, most of it distance.

    No amount of origin tuning removes that. Light in fibre needs time, and a real page needs dozens of these requests, plus TCP and TLS handshakes that cost round trips of their own.

    Scene: Users in Europe send 150 requests per second straight to an origin in North America. Every request succeeds with a median latency of about 200 ms, mostly network distance.

    Key idea: For far-away users, latency is dominated by distance to the server, not by how fast the server is.

  2. 2. An edge cache near the users

    A CDN runs points of presence (PoPs) in many cities. Users now reach a PoP in Europe, 8 ms away (DNS or anycast routes them to a nearby one). The PoP keeps a cache of recently requested files.

    A hit is answered right there in about 20 ms. A miss goes on to the origin, comes back, and the PoP keeps a copy for the next user. The cache only holds 300 of the 2,000 files, yet about two thirds of requests hit: a few popular files get most of the traffic. Median latency falls about tenfold; P95 still shows the trip to the origin, because misses pay it in full.

    Scene: Users now reach an edge PoP in Europe. About two thirds of requests hit its cache and return in about 20 ms; misses are fetched from the origin and stored. Median latency drops to roughly 20 ms while P95 still reflects origin fetches.

    Key idea: A CDN moves copies of content close to users. Hits cost the short trip to the PoP; misses still cost the long trip to the origin.

  3. 3. Four times the traffic, same origin

    Traffic quadruples to 600 requests per second. The origin can serve about 250 per second: on its own it would be overwhelmed.

    With the PoP in front it only sees the misses, about a third of the traffic, roughly 200 requests per second. The CDN is now part of the capacity plan. That is a gift (cheap scale for static content) and a risk: anything that suddenly lowers the hit ratio sends the difference straight to the origin.

    Scene: At 600 requests per second the PoP answers about two thirds from cache. The origin receives only the misses, roughly 200 requests per second, and handles them without errors.

    Key idea: Origin load = traffic × miss ratio. A CDN with a high hit ratio is the cheapest capacity there is, as long as the hit ratio holds.

  4. 4. Cache-Control decides how long a copy lives

    The origin tells caches what they may do with each response through the Cache-Control header. max-age (or s-maxage for shared caches like a CDN) sets the TTL: how long a copy may be served without asking the origin again. no-store forbids caching; private allows only the browser to cache it.

    Our files now get a short TTL (3 s here, standing in for a few minutes). Every popular file expires and has to be fetched again, so the hit ratio drops and origin traffic rises, close to the origin’s limit: P95 climbs as misses queue there. Short TTLs mean fresher content and more origin load. Versioned file names (app.3f9a1c.js) avoid the dilemma for static assets: cache them for a year, change the name when the content changes.

    Scene: Cached files now expire after a short TTL. The hit ratio falls and noticeably more requests reach the origin, which gets close to its limit; P95 rises but nothing fails yet.

    Key idea: TTL trades freshness against hit ratio. Fingerprinted asset names let you cache forever and still deploy instantly.

  5. 5. Purge everything

    A deploy went out with a broken stylesheet, so someone clicks purge all. One second in, the edge cache is emptied.

    For a moment every request is a miss. 600 requests per second hit an origin built for about 250: requests queue for its connections, some wait longer than 300 ms and fail. Then the popular files are cached again and the hit ratio recovers. A large CDN has hundreds of PoPs, and each one refills from the origin. Prefer purging specific URLs or tags, and versioned names that never need purging.

    Scene: One second in, the edge cache is purged. For a short time every request misses and goes to the origin, which saturates; some requests fail with timeouts until the cache refills and the hit ratio recovers.

    Key idea: A full purge turns the CDN off for a moment. The origin must survive the refill, or you purge narrowly.

  6. 6. The origin fails

    One second in, the origin goes down. The PoP keeps answering every request it has in cache. Only misses fail, so users see a partly working site instead of a dead one.

    As TTLs run out, more files count as expired and those requests fail too; one TTL later (3 s here) nothing is left that may be served and every request fails. CDNs can do better than this model: with stale-if-error the origin allows serving an expired copy while it is unreachable, and stale-while-revalidate lets the PoP serve a slightly old copy while it refreshes in the background.

    Scene: The origin fails one second in. Cache hits keep succeeding and only misses fail, so at first the error rate roughly matches the miss ratio; as cached files expire it climbs until every request fails.

    Key idea: Cached content keeps being served during an origin outage; stale-if-error extends that past the TTL.

  7. 7. Three continents, three caches

    The origin is back, and traffic now comes from three places: 200 requests per second each from Europe, North America and Asia, each served by its own PoP and cache.

    Total traffic is the same 600 per second, but every PoP has to fetch each popular file separately, and each PoP sees only a third of the traffic, so its copies expire before they are reused as often. Each PoP now hits only about half the time, and the origin receives the misses of all three: more than it can serve, so some requests time out. Real CDNs have hundreds of PoPs; without help, the origin would see every one of them miss.

    Scene: Three groups of users, in Europe, North America and Asia, each send 200 requests per second to their own PoP. Each PoP caches separately and hits only about half the time, so the origin receives the misses of all three, more than with one PoP serving the same total; it overloads and some requests time out.

    Key idea: Every PoP has its own cache. More PoPs mean lower latency for users, but more separate misses at the origin.

  8. 8. An origin shield: one more cache tier

    We add an origin shield: a shared cache tier in the origin’s region with room for 1,000 files. PoPs no longer go to the origin on a miss; they ask the shield. The first PoP to miss a file makes the shield fetch and keep it; the other PoPs then find it at the shield instead of reaching the origin, and keep their own copy of what the shield sends back.

    The shield only ever sees what the PoPs missed: the long tail of less popular files, many of which only one PoP asks for before its copy expires. So it hits only about a third of the time, far less than an edge cache. That is still enough: origin traffic drops by about 40%, the timeouts stop, and the origin is comfortable again. The price is an extra hop for anything the shield does not have, and one more cache to purge.

    Scene: An origin shield with its own cache sits in the origin region. Every PoP sends its misses to the shield and stores what it sends back; the shield hits about a third of the time, and only its misses reach the origin, which now receives about 40% fewer requests and no longer times out.

    Key idea: An origin shield collapses misses from many PoPs into one, so the origin sees roughly one fetch per file per TTL instead of one per PoP. Its own hit ratio is modest: it only sees the edge’s misses.

  9. 9. What to put on a CDN, and what to watch

    Three PoPs and a shield serve 600 requests per second; the origin sees a fraction of it.

    Good candidates: static assets with fingerprinted names, images, video segments, downloads, and public API responses that many users share for a few seconds. Bad candidates: personalised or authenticated responses, unless you design the cache key carefully. A cache key that includes every query parameter, cookie or header fragments the cache into millions of one-off entries.

    CDNs also terminate TLS close to users (saving handshake round trips), absorb DDoS traffic and can run small edge functions. Watch hit ratio, origin request rate and the 4xx/5xx rate per PoP.

    Scene: Users on three continents are served by their nearby PoPs, which share an origin shield in front of the origin. Most requests are answered at the edge and nothing fails.

    Key idea: Cache what many users share, key it narrowly, version it, and keep the origin able to survive a cold cache.