System Design · Concept Library · Free article
CDN & Edge Caching — serving the world from next door
How to make a far-away user fast when you can’t move your servers: keep copies of the answer in hundreds of locations worldwide, so the request is answered a few kilometres away instead of across an ocean. From what a CDN is up through pull-vs-push, TTL and freshness, invalidation, the offload math, and edge compute — for interns through principal engineers.
A CDN (content delivery network) is a global fleet of caching servers that keep copies of your content close to users. Geo-latency is mostly distance, and you can’t move your origin — so instead you scatter copies of the answer across hundreds of points of presence (POPs) worldwide, and the network routes each user to the nearest one. A redirect that took ~150 ms across the Pacific now takes ~15 ms from a POP down the street, and — the second prize — the origin only sees the small fraction of traffic that misses the edge (a 95% hit ratio means your servers handle 5% of the load). The craft is in the details: pull vs push (fill lazily on first request vs upload ahead), TTL / Cache-Control (how long a copy stays fresh), stale-while-revalidate (serve the old copy instantly while refreshing), and invalidation (versioned URLs beat purging). It’s caching (the in-memory idea) pushed out to the edge of the planet.
The answer is across an ocean — so move a copy next door
We left Zoe in Sydney waiting ~600 ms for a redirect a New Yorker gets in 50. The speed-of-light page showed why: her request crosses the Pacific several times, and no faster server changes that — distance is a fixed tax. So stop trying to make the trip faster. Make the trip shorter.
Here’s the move: instead of one origin near Seattle answering the whole planet, keep copies of the hot answers in hundreds of locations worldwide — one a few kilometres from Zoe, one near every other cluster of users. Now her tap is answered by a machine down the street in ~15 ms, and the packet never touches the ocean. That global fleet of copy-holding servers is a CDN — a content delivery network — and this page is about how it works and how to run it well.
A copy of your content in every city
A CDN is a network of edge servers grouped into POPs in cities all over the world. Each POP holds cached copies of your content and answers nearby users directly. The magic that makes it seamless is the routing: you publish one address, and the network automatically sends each user to the nearest POP — usually via anycast, where the same IP address is announced from every location and the internet’s own routing delivers the user to the closest one. No smart client, no per-region URLs; the user just gets the copy nearest them.
Toggle the CDN on below and watch what changes for users around the world — the request stops crossing oceans and gets answered locally:
The interactive version of this example is available when JavaScript loads.
How a POP decides what to serve
When a request reaches a POP, the edge server checks whether it already holds a fresh copy for that cache key (usually the URL, sometimes plus a few headers). If it does — a hit — it answers immediately from local storage, no origin involved. If it doesn’t — a miss — it fetches from your origin once, hands that back to the user, and keeps a copy so the next person nearby gets a hit. That last step is the whole trick: the edge fills itself from real traffic. Step through it:
The interactive version of this example is available when JavaScript loads.
Pull (lazy) vs push (eager)
There are two ways content gets into the edge. A pull CDN is lazy: you just point it at your origin, and each POP fills itself on the first miss (exactly the flow above). It’s the default for websites and apps — huge variety of content, most of it fetched on demand, no upload step to manage; the only cost is that first-miss penalty. A push CDN is eager: you upload content to the CDN ahead of any request, so it’s already in place before the first user arrives. That’s worth the effort for a small set of big, rarely-changing files — software installers, game assets, video libraries — where you never want a user to pay a cold miss on a multi-gigabyte object.
| Pull CDN (lazy) | Push CDN (eager) | |
|---|---|---|
| How it fills | On the first miss, from your origin | You upload it ahead of time |
| Best for | Websites/apps: lots of varied, changing content | A few big, static files (installers, media) |
| First request | Pays the origin round trip (cold miss) | Already warm — no cold miss |
| Effort | Point-and-go; origin is the source of truth | You manage uploads + when to expire |
Freshness: TTL and Cache-Control
A cached copy can’t be trusted forever — the underlying thing might change. So every copy has a time-to-live (TTL): how long the edge may serve it before it must check with the origin again. You set it from the origin with the Cache-Control header: max-age=3600 means "good for an hour"; s-maxage sets a different lifetime for shared caches like the CDN (vs the browser); no-store means "never cache this"; private means "browser only, not the CDN" (for per-user data). The TTL is a dial with a real trade-off — drag it:
The interactive version of this example is available when JavaScript loads.
Serving stale to stay fast (stale-while-revalidate)
When a copy’s TTL expires, the naive move is to block the next user while the edge re-fetches from the origin — so that unlucky person eats the full round trip. Stale-while-revalidate avoids it: the edge serves the slightly stale copy instantly and refreshes it in the background, so nobody waits. Think of three states for a cached object: fresh (within TTL — serve it), stale (just past TTL but within the revalidate window — serve it now, refresh behind the scenes), and rotten (too old even for that — must re-fetch before serving). A sibling directive, stale-if-error, says "if the origin is down, keep serving the old copy rather than showing an error" — turning the CDN into a resilience layer, not just a speed one.
Getting a new version out: purge vs versioned URLs
What happens when content changes before its TTL expires — you shipped a fix and don’t want the edge serving the old copy for an hour? Two approaches, and the difference is a classic senior tell. Purge (invalidate): tell the CDN to drop the cached copy for a URL, forcing the next request to re-fetch. It works, but it’s the slow, error-prone path — purges take time to propagate to every POP, and a mass purge triggers a stampede of misses back to the origin. Versioned URLs: put a content hash in the filename — app.a1b2c3.js — so new content gets a new URL. The old copy stays cached (harmlessly) and every fresh page load references the new URL, which misses once and fills. No purge, no propagation delay, no stampede — the swap is effectively instant.
The interactive version of this example is available when JavaScript loads.
Hit ratio, the offload math, and the stampede
The single metric that decides whether a CDN is earning its keep is the cache hit ratio — the fraction of requests answered at the edge without touching your origin. The leverage is enormous: at 10 million requests a day, a 95% hit ratio means the origin sees 500,000, not 10 million — a 20× reduction. Push it to 99% and the origin sees 100,000. The last few percent aren’t vanity; they’re the difference between an origin that’s bored and one that’s on fire. Drag the hit ratio and watch the origin load — then flush the cache and watch what happens:
The interactive version of this example is available when JavaScript loads.
Static vs dynamic content — and edge compute
CDNs shine on static content — the same bytes for everyone (images, JS/CSS, videos, and yes, a redirect rule). Dynamic, personalised content — your logged-in dashboard, a per-user feed — can’t just be cached and handed to the next person, or Zoe would see Liam’s account. But the edge still helps: it can terminate the connection nearby (do the TLS handshake at the POP, saving those round trips) and keep a warm connection to the origin, so even an uncacheable request skips the slow cold-connection setup. And edge compute — small functions that run at the POP (Cloudflare Workers, Lambda@Edge) — lets you do real work near the user: auth checks, A/B routing, request rewriting, assembling a page from cached fragments. The frontier is moving from "cache static files at the edge" to "run part of the app at the edge."
Security and resilience come along for the ride
- DDoS absorption. Because anycast spreads your address across every POP, a flood of attack traffic is soaked up across the whole global network instead of drowning one origin IP. The CDN is a shield, not just a cache.
- A WAF at the edge. Web application firewalls run at the POP, blocking malicious requests before they ever reach (or cost you) origin capacity.
- TLS termination + newer protocols. The POP does the encryption handshake nearby and often speaks HTTP/3 to the user even if your origin doesn’t — fewer round trips for everyone (see geo-latency).
- Origin hiding. With all traffic flowing through the CDN, your origin’s real address can stay private — a smaller attack surface.
Cost, and when a CDN won’t help
A CDN isn’t free — you pay for the bandwidth it serves (though edge egress is usually cheaper than origin egress, and offloading the origin saves there too), plus request fees and any edge-compute time. Usually it pays for itself many times over on a global, read-heavy site. But it’s not a magic "make it fast" button:
Signs a CDN isn’t the fix
- The content is per-user and uncacheable. If every response is unique to the logged-in user, there’s nothing to share — the edge can only help with connection termination, not caching. (This is where regional read replicas come in — the next step.)
- Write-heavy or real-time. Caching helps reads; it does nothing for writes or data that must be to-the-millisecond fresh.
- A tiny, single-region audience. If everyone’s already near your origin, distance is small and a CDN adds cost for little latency win.
- Cache-busting yourself. Very short TTLs or aggressive purging drop the hit ratio toward zero — you’re paying for a cache you keep emptying.
The providers and how they differ
You rarely build a CDN; you rent one. The big four differ in emphasis rather than fundamentals. Cloudflare runs the full cache + security stack at every edge with anycast single-hop routing, and has the largest edge-compute ecosystem (Workers). Fastly is prized for a tight operator loop — sub-second config propagation and instant purge — popular where teams tune caching aggressively. Akamai has the deepest, most distributed footprint and tiered caching that handles huge long-tail media libraries. AWS CloudFront integrates tightly with the AWS stack (S3, Lambda@Edge, origin shield). The interview point isn’t brand trivia — it’s recognising the shape: POPs + anycast + a cache honouring Cache-Control + purge/versioning + optional edge compute. Every provider is a variation on that.
The headers that drive all of this
A CDN mostly does what your Cache-Control headers tell it. The behaviour above — long-lived immutable assets, short-lived HTML with background refresh, per-user data that never caches — is almost entirely a matter of the right header on the right response:
The interactive version of this example is available when JavaScript loads.
Pitfalls
- Caching per-user data publicly. A missing
private/no-storeon a personalised response lets the CDN serve one user’s data to the next. The classic, dangerous CDN bug. - TTLs so short the hit ratio collapses. A cache you constantly re-check or purge is a cache you’re paying for and not using. Match TTL to how fast the truth changes; version instead of purging.
- Blocking users on revalidation. Without stale-while-revalidate, every expiry makes some user eat the origin round trip. Serve stale, refresh behind them.
- Purge stampedes. A mass purge (or a synchronized expiry) sends every POP to the origin at once. Use versioned URLs and an origin shield to keep the origin calm.
- Forgetting the cache key. If the key ignores a header that changes the response (language, device), users get the wrong cached variant; if it includes too much (a random query param), the hit ratio craters. Tune what’s in the key.
- Assuming the CDN fixes dynamic pages. It caches shared content. Per-user reads still need the data closer (read replicas), not just an edge cache.
Best practices
- Version immutable assets; cache them forever —
max-age=31536000, immutable+ a content hash in the URL gives instant, purge-free updates. - Match TTL to change rate — a year for a logo, minutes for a report,
no-storefor a stock price. - Always add stale-while-revalidate (and stale-if-error) — never block a user on a refresh; survive origin blips on the old copy.
- Mark per-user responses
private/no-store— never let shared caches hold personalised data. - Turn on an origin shield — collapse edge-to-origin fan-out so an expiry or flush can’t stampede the origin.
- Watch the hit ratio by content type — it’s the health metric; a falling ratio means a mis-tuned key, TTL, or purge habit.
Rapid-fire cheat-sheet (intern → principal)
- "What is a CDN and why use one?"
- A global fleet of caching servers (POPs) that keep copies of your content near users, so a request is answered a few km away (~15 ms) instead of across an ocean (~150 ms). Two wins: lower latency and origin offload (a 95% hit ratio means your servers see 5% of traffic).
- "Pull vs push CDN?"
- Pull = lazy: point it at your origin, each POP fills on the first miss. Default for websites/apps. Push = eager: upload content ahead of time. Worth it for a few big, rarely-changing files (installers, media) where a cold miss is unacceptable.
- "How does a CDN know how long to cache?"
- The
Cache-Controlheader from the origin:max-age(lifetime),s-maxage(lifetime for shared caches like the CDN),no-store(never cache),private(browser only). Short TTL = fresher but more origin load; long TTL = faster but staler. - "How do you push out a change without serving stale content?"
- Prefer versioned URLs — a content hash in the filename so new content = new URL, cached forever, instant swap, no purge. Use purge only for URLs you can’t version, and expect it to be slower and to risk a stampede.
- "A cache flush knocked over the origin. Why, and how do you prevent it?"
- A stampede: every POP missed at once and rushed the origin. Fix with an origin shield (one POP fetches and fans out to the rest) plus stale-while-revalidate (serve the old copy while refreshing), so an expiry or flush barely touches the origin.
- "Can a CDN speed up a logged-in, personalised page?" (the deeper one)
- Not by caching — the content is per-user, so mark it
private/no-store. But the edge still helps by terminating TLS nearby and keeping a warm origin connection, and edge compute can do auth/routing at the POP. For the per-user data, though, you need it closer — regional read replicas, not an edge cache.
The takeaway
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.