Content Delivery Network
Serve content from a server near the user so the network distance stops being the bottleneck.
CDN in 30 seconds
- What: a global network of edge servers that cache your content close to users, so network distance stops being the bottleneck.
- Why: a Sydney user fetching from Virginia pays 100ms+ per round trip — the edge kills most of that, and offloads your origin.
- Pull: edge fetches from origin on first request then caches — no upload step, but the first user per region eats a slow miss.
- Push: you upload ahead of time — no cold miss, but you manage distribution of everything.
- Cache safely: content-hashed filenames (
app.9f2c.js) + immutable caching; a change makes a new URL instead of a global purge. - The trap: un-versioned files with long TTLs leave users stuck on old versions, and purging every edge isn't instant.
Franchising the popular bakery
Imagine one beloved bakery in a single city. People drive in from all over the country for its bread — some spend a whole day on the road each way. The bread is great, but the distance is the misery. The fix isn't a bigger oven; it's opening a branch in every city that bakes the same recipes. Now almost everyone has a bakery a few minutes away, and the original shop only has to supply a branch the first time it needs a new recipe. A CDN does exactly this for your website: it opens branches (edge servers) near your users, so the painful cross-country trip to your one 'main bakery' (the origin) mostly stops happening.
The problem it solves
Light travels fast, but not instantly. A user in Sydney fetching a file from a server in Virginia pays a round-trip of well over 100ms before anything else happens. A CDN is a network of servers spread across the globe that cache your content close to users, so that distance — and the load on your origin — mostly disappears.
It's worth sitting with why distance costs so much, because it's the one bottleneck no amount of faster code can remove. A signal in fibre crosses the planet in roughly 100–150 milliseconds one way, and a single web page often needs several round trips (DNS, connection setup, the request itself, then follow-up assets). Multiply a 150ms round trip by a handful of trips and you've burned the better part of a second before a single useful byte renders — purely because the server is far away. You cannot optimize the speed of light; you can only shorten the trip.
The core idea, plainly
Instead of every user reaching your one origin server, they reach the nearest edge server. If the edge already has the content, it serves it immediately (a hit). If not, it fetches once from the origin, caches it, and serves everyone else from that copy. You trade a little freshness and some cache-control complexity for dramatically lower latency and origin load.
Two payoffs come from the same move, and it's worth separating them because interviewers probe both. The first is latency: the user talks to something nearby, so the round trip shrinks from oceanic to local. The second is offload: because an edge answers thousands of requests from one cached copy, your origin sees only the trickle of first-time misses instead of the full flood. A good CDN can absorb 90%+ of traffic, which is often the difference between an origin that shrugs off a viral spike and one that melts.
How a user even reaches the nearest edge
A fair first question: if there are hundreds of edges worldwide, how does a browser in Sydney know to talk to the Sydney edge and not the one in London? The answer is mostly DNS plus anycast routing, and it happens before any content moves.
- The browser looks up your CDN hostname via DNS (see DNS). The CDN's DNS is smart: it answers with the IP of an edge close to where the request came from.
- Many CDNs also use anycast — the same IP address is announced from every edge, and the internet's own routing naturally delivers your packets to the nearest one.
- The result: the user connects to a nearby edge without knowing or caring which physical location it is. The 'choose the closest branch' decision is invisible and automatic.
Pull: the lazy, self-filling edge
The most common setup is a pull CDN, and it works exactly like cache-aside applied to geography. You don't upload anything in advance. The first time a user in a region asks for a file, that region's edge has a miss, fetches it once from the origin, caches it, and serves it. Every subsequent user in that region gets a fast hit from the local copy.
def handle_edge_request(url):
cached = edge_cache.get(url)
if cached and not cached.is_expired():
return cached # HIT: served near the user
# MISS: fetch once from the far-away origin, then cache it
resp = fetch_from_origin(url)
ttl = parse_max_age(resp.headers["Cache-Control"])
edge_cache.put(url, resp, ttl=ttl)
return resp # every later user in this region now hitsThe elegance is that the CDN only ever stores what someone actually asked for, and new content needs no deploy step — publish it at the origin and the edges pull it on demand. The one cost is the cold miss: the very first user per region pays the slow origin round trip so everyone after them doesn't. For most catalogs that's a fine trade.
Push vs pull CDNs
The alternative to pulling lazily is push: you upload content to the CDN ahead of time, so it's waiting at the edges before the first user ever asks. No cold miss, full control — at the cost of you managing distribution and storage of everything, including files that may rarely be requested.
| Type | How content arrives | Pros | Cons | Use when |
|---|---|---|---|---|
| Pull | Edge fetches from origin on first request, then caches. | No upload step; only caches what's actually requested. | First user per region pays a slow miss; needs good cache headers. | Large catalogs where most items are rarely hit. |
| Push | You upload content to the CDN ahead of time. | No cold-miss penalty; full control of what's cached. | You manage distribution and storage of everything. | Small, hot, or launch-critical asset sets. |
The gap a CDN can't fill: dynamic and private data
It's tempting to conclude 'put everything behind the CDN and the origin barely works.' But a cache near thousands of strangers can only safely hold content that's the same for everyone and safe for anyone to see. That rules out two big categories, and knowing the line is what separates a working design from a data-leak incident.
- Personalized responses — your logged-in dashboard, your cart, your bank balance. If the edge cached one user's dashboard and served it to the next, you'd leak private data to a stranger. These must be computed per request, usually at the origin.
- Rapidly changing data — a live price, a stock level, a score that updates every second. By the time an edge caches it, it's wrong; caching it just serves stale numbers.
- Write operations — a CDN caches reads. A POST that changes state has to reach the origin; there's nothing to cache about 'please charge my card.'
So the honest mental model is a split: static, shared, public content (images, CSS, JS, video, public pages) loves the edge; dynamic, personalized, private content belongs at the origin. Most real sites are a blend — the CDN serves the heavy static shell fast, and the small dynamic bits are fetched from the origin and stitched in.
What to cache — and how to invalidate
Static assets (images, CSS, JS, video) are the classic fit. The key to safe caching is cache-control headers plus versioned URLs: name files with a content hash (app.9f2c.js) and cache them forever, because a change produces a new name. For content that must update in place, use short TTLs or an explicit purge — but purges are slower and should be the exception, not the strategy.
// Content-hashed filename -> cache forever; a change makes a NEW url
if (/\.[0-9a-f]{8}\.(js|css)$/.test(req.path)) {
res.set("Cache-Control", "public, max-age=31536000, immutable");
}
// Updates in place (e.g. index.html) -> revalidate often, no stale-forever trap
else if (req.path.endsWith(".html")) {
res.set("Cache-Control", "public, max-age=60, must-revalidate");
}The content-hash trick is worth understanding because it sidesteps invalidation entirely. If a file's URL contains a hash of its contents, then changing the file necessarily changes its URL. Old URL, old content, cached forever — harmless, because nobody requests it any more. New URL, new content, fresh fetch. You never have to tell the edges 'forget the old one'; the new name simply routes around it. That's why 'cache forever + versioned URLs' is the gold-standard pattern for static assets.
Choosing: what goes on the CDN, what stays at the origin
| Content | Where it lives | Caching rule |
|---|---|---|
| Hashed JS/CSS bundles | CDN edge | Immutable, max-age one year — URL changes on every build. |
| Images, fonts, video | CDN edge | Long TTL; version the path if they ever change. |
| index.html / entry pages | CDN edge | Short TTL + revalidate, so a deploy is visible quickly. |
| Logged-in dashboards | Origin | Not cached at the shared edge — personalized and private. |
| Live prices / inventory | Origin (or very short TTL) | Changes too fast to cache safely. |
| Writes (POST/PUT/DELETE) | Origin | Nothing to cache; must reach the source of truth. |
A CDN is where caching meets the map — it's the standard answer to the one problem you can't engineer away, the speed of light, by moving content closer to the people asking for it.
Why it matters
- It collapses global latency: users hit a nearby edge instead of a round trip across oceans.
- It shields your origin — the edge absorbs the vast majority of traffic, so your servers only fill misses.
- It's increasingly a place to run logic (auth, routing, personalization) at the edge, not just store bytes.
If ignored
- Distant users suffer slow page loads no amount of backend tuning can fix.
- Your origin takes the full brunt of global traffic and buckles under a spike.
- Un-versioned assets with long TTLs strand users on stale versions after every deploy.
Where it fits
- Sits at the network edge, the very first hop in front of your origin on the read path.
- Extends the caching idea geographically and pairs with versioned URLs for safe invalidation.
- Works with DNS and load balancing to steer each user to their nearest healthy edge.
Related topics
- Caching: a CDN is caching applied at the network edge
- DNS: how users get routed to their nearest edge location
- Load balancing: spreads traffic across edges and across origin servers on a miss
- Latency & throughput: the distance-latency numbers a CDN exists to defeat
Interview lens
Questions it unlocks
- How do you serve images and video to a global audience fast?
- Why did users see a stale version of your site after a deploy?
- How do you reduce load on your origin servers?
60-second answer
I'd front static assets with a pull CDN so each region caches on first use and the origin only serves misses. I'd make caching safe with content-hashed filenames and immutable cache-control, so a new deploy produces new URLs instead of relying on purges. For anything that changes in place I'd use short TTLs. I'd be explicit that personalized and highly dynamic responses stay at the origin, not the shared edge. I'd mention edge functions if we need auth or routing close to the user. The whole point is cutting both latency and origin load at once.
Common traps
- Caching un-versioned assets with long TTLs and then needing global purges.
- Treating the CDN as only storage and ignoring cache-header strategy.
- Trying to cache highly dynamic, per-user responses at the edge without care.