CDNs & Edge Delivery
How content lands close to users, push vs pull, cache keys and invalidation, and why the CDN is often the single largest scaling decision in a media-heavy design.
#The problem it solves
Physics. A user in Mumbai fetching from a Virginia datacenter pays ~200 ms round trip minimum, before any server does work. TCP handshake plus TLS handshake plus the request is 3–4 round trips — nearly a second before the first byte, and no amount of server optimization touches it.
A CDN — content delivery network — is a fleet of caching servers scattered around the world, each one called a point of presence or PoP. Content is served from whichever PoP is nearest the user, turning a 200 ms trip into a 10 ms one. Your own servers, wherever they live, are the origin.
Two benefits, and candidates usually name only the first:
- Latency — content is physically closer.
- Origin offload — a 95% edge hit rate means your origin serves 1/20th of the traffic. For a media-heavy product this is not an optimization, it's the only reason the design is affordable. Serving 1 Tbps from your own fleet is a completely different business than serving it from a CDN.
#How a request reaches the nearest PoP
Two mechanisms, and knowing the difference is a good depth signal:
DNS-based. When a browser looks up cdn.example.com, it gets a different answer depending on where the question came from. Simple, works everywhere. It has two weaknesses. First, it sees the location of the user's DNS resolver — the server that looks up names on the user's behalf, such as their ISP's or a public one like 8.8.8.8 — not the user. Someone using a far-away public resolver can be pointed at the wrong continent. Second, switching away from a broken PoP is slow, because clients keep using the old answer until their cached copy expires.
Anycast. The same IP address is announced from every PoP, and the internet's own routing carries each user's packets to the nearest one. Removing a failed PoP is just withdrawing that announcement — fast, with no DNS caching to wait out. Downside: route changes can move a client mid-connection, which matters for long-lived TCP.
Most large CDNs use both — anycast for the entry point, DNS/application logic for finer control.
#Push vs pull
Pull (origin pull) — the default. The edge fetches from your origin on first miss and caches per TTL.
user → PoP (miss) → origin → PoP caches → user
user → PoP (hit) → user (fast)Nothing to manage; only requested content is stored. Cost: the first user in each region pays the full origin latency, and a burst of misses can hammer the origin — CDNs mitigate this with origin shield, a mid-tier cache that collapses many PoP misses into one origin fetch.
Push — you upload content to the CDN ahead of demand.
Right when you know exactly what will be hot and when: a game patch, a product launch, a video release with a known drop time. Avoids the cold-miss stampede entirely. Cost: you manage distribution and storage for content nobody may request.
Most systems are pull with selective pre-warming for known events.
#Cache keys — where the bugs live
The cache key determines what counts as "the same" object. By default it's the URL, but you often need more:
- Query strings —
?utm_source=…shouldn't create a separate cached copy. Strip or allow-list parameters, or you fragment your cache and destroy the hit rate. - Vary headers — a
Varyresponse header tells caches "the response depends on this request header, so store a separate copy for each value of it".Vary: Accept-Encodinggives separate gzip/brotli copies (correct — clients that can't decode brotli need the gzip one).Vary: User-Agentgives you thousands of copies, one per browser version string, and effectively no caching (almost always a mistake). - Cookies — if the cache key includes cookies, every user gets their own copy. Strip cookies for static assets.
- Device class / geo — deliberate segmentation, e.g. mobile vs desktop variants.
#Invalidation
The hard part, as always. Options in increasing order of preference:
1. TTL expiry. Send a Cache-Control: max-age=3600 header — an instruction to every cache along the way saying "this is good for 3,600 seconds" — and accept up to an hour of staleness. Simple, and nothing has to coordinate with anything.
2. Purge / invalidate. Explicitly tell the CDN to drop an object. Propagation takes seconds to minutes across all PoPs, and purging is rate-limited by most providers, so it doesn't scale to high-frequency changes.
3. Versioned URLs (cache busting). The right answer for static assets. Include a content hash in the filename:
/static/app.a3f9c2b1.js Cache-Control: max-age=31536000, immutableBecause the URL changes when the content changes, you never invalidate anything — you just reference a new URL. Old versions age out naturally. This lets you cache forever, which maximizes hit rate and eliminates revalidation traffic entirely — browsers and edges never need to ask the origin "has this file changed?", because a given URL's content never does.
4. Stale-while-revalidate. Cache-Control: max-age=60, stale-while-revalidate=600 — serve the cached copy instantly after expiry while refreshing in the background. Users never wait for a revalidation. Excellent for content that should be fresh-ish but must always be fast.
#What to cache
Always: images, video segments, CSS, JS, fonts, downloads. Immutable, versioned, cached for a year.
Often, and underused: API responses that are identical across users — product catalogs, public profiles, search results for common queries, configuration. A short TTL (10–60 s) on a hot endpoint can remove the large majority of origin traffic. Candidates rarely propose this and it's frequently the biggest available win.
Never: anything personalized or authenticated, unless you're using signed URLs or edge-side personalization. Serving user A's data to user B from a shared cache is a real and recurring class of security incident — driven by exactly the cache-key mistakes above.
#Video: the segment model
For video streaming, CDNs are the whole architecture. Video is transcoded into multiple bitrates and chopped into 2–10 second segments, each an independently cacheable file, described by a manifest:
manifest.m3u8
├── 1080p/seg_001.ts, seg_002.ts, ...
├── 720p/ seg_001.ts, seg_002.ts, ...
└── 480p/ seg_001.ts, seg_002.ts, ...
Client measures its own bandwidth and picks the next
segment's quality → adaptive bitrate (ABR)Why this design wins: segments are static files (perfectly cacheable), quality adaptation happens on the client with no server state, and a bandwidth drop degrades quality rather than buffering. Popular content is served almost entirely from edge cache.
#Edge compute
Modern CDNs run code at the PoP (Cloudflare Workers, Lambda@Edge, Fastly Compute). Useful for:
- Auth and token validation at the edge — reject unauthorized requests before they cross an ocean.
- A/B routing and personalization without breaking cacheability. For example, edge code decides which experiment group a user is in and rewrites the request to
/home-v2. Both/home-v1and/home-v2remain shared, cacheable pages; only the choice between them is per-user. - Header rewriting, redirects, bot filtering.
- Assembling a page from cached fragments plus one small dynamic call.
The pattern worth naming: cache the expensive, shared 95% at the edge and fetch only the small personalized fragment from origin. It's how you make a "personalized" page mostly cacheable.
#Security at the edge
The CDN is your first line of defense, and this is worth a sentence in any design:
- DDoS absorption — a distributed edge with terabits of capacity absorbs volumetric attacks your origin never could. This is a primary reason to use a CDN even if you don't need the caching.
- WAF (web application firewall) — inspects requests and blocks attacks such as SQL injection and other known-bad patterns before they reach you.
- TLS termination and modern cipher support without touching your origin.
- Origin shielding — lock the origin to accept traffic only from the CDN, so attackers can't bypass it by hitting your IP directly.
- Signed URLs — time-limited, per-user access to otherwise-cacheable private content.
#In an interview
For any design serving images, video, or static assets, propose the CDN early and quantify it:
"Peak egress (data sent out to users) is ~150 GB/s. That's not something we serve from origin — it has to be CDN. At a 95% hit rate the origin sees ~7.5 GB/s, which is a manageable fleet. That makes CDN hit rate a primary metric for us, so I'd version asset URLs for immutable caching and normalize cache keys to avoid fragmentation."
That's the CDN treated as an architectural decision with a number attached, rather than a box drawn out of habit.
#Check yourself
Name the two benefits of a CDN — the one people forget is often bigger.Show answer
DNS-based routing versus anycast for reaching the nearest edge: what's the weakness of each?Show answer
Push versus pull CDNs: when is push the right choice?Show answer
What is an origin shield?Show answer
What usually wrecks a CDN's hit rate, and how do you fix it?Show answer
Why are versioned URLs the best invalidation strategy for static assets?Show answer
What does stale-while-revalidate do?Show answer
Why is video delivery a natural fit for CDNs?Show answer
#What to carry forward
- A CDN beats physics by serving from nearby, and — just as important — offloads the origin.
- Pull is the default; push or pre-warm for known launches; an origin shield collapses misses.
- Normalise cache keys: fragmentation is the usual reason a CDN "isn't helping".
- Version static asset URLs and cache them forever; use stale-while-revalidate for fresh-ish content.
- Cache shared API responses briefly at the edge, never personalised data — and let the edge absorb attacks.