Content Delivery Networks (CDN)
A CDN is a globally distributed cache in front of your origin. It buys four things:
- Lower latency — content is served from a nearby edge.
- Origin offload — repeated requests never reach your servers.
- Absorption capacity — spikes and DDoS traffic terminate at the edge.
- TLS/edge features — certificates, compression, WAF, image resizing, edge logic.
It also introduces a second copy of the truth, with its own invalidation problem.
Pull vs push
| Pull | Push | |
|---|---|---|
| How content arrives | edge fetches from origin on first miss | you upload to the CDN |
| Best for | web assets, images, API GETs | large media, releases, software artifacts |
| Invalidation | TTL + purge | explicit replace/delete |
| Risk | origin stampede on cold cache | storage duplication, sync logic |
Most sites use pull for assets and APIs, push for big media pipelines.
Cache keys and TTLs
The CDN decides what "the same resource" means. A cache key usually includes:
- host/path,
- query string (all of it, or an allowlist),
Varyheaders (e.g.,Accept-Encoding,Accept-Language),- optionally device/geo/tenant.
Mistakes here cause the worst bugs:
- Query-string chaos —
?utm_source=...fragments the cache into thousands of misses. Normalise or ignore tracking params. - Missing
Vary: Accept-Encoding— a gzip response served to a client that cannot decode it. - Over-varying —
Vary: User-Agentmakes the cache nearly useless. - Personalised content cached publicly — user A sees user B's data. Mark authenticated responses
Cache-Control: private, no-store.
TTL guidance:
| Content | TTL | Notes |
|---|---|---|
Immutable assets (app.3f9c1.js) |
1 year | content-hashed filenames |
| HTML shell | seconds–minutes | stale-while-revalidate |
| Public API GET | seconds–minutes | depends on staleness tolerance |
| User-specific | no shared cache | private |
| Images | days–weeks | version by URL |
Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=30
s-maxage applies to shared caches; stale-while-revalidate lets the edge serve a slightly stale object while refreshing — a cheap way to avoid stampedes.
Invalidation
Three strategies, in order of preference:
- Versioned URLs —
app.<hash>.js,avatar.jpg?v=42. Deploy a new URL; old caches expire naturally. No purge needed. - Short TTL + background refresh — acceptable staleness, no purge machinery.
- Explicit purge — necessary for corrections, but propagates slowly and can cause stampedes.
A purge is not instant everywhere. After purging a popular object:
- edges miss and hit the origin simultaneously;
- origin load spikes (thundering herd);
- if the origin is down, users get errors instead of stale content.
Mitigations: origin shield (a mid-tier cache), request coalescing, stale-if-error, and jittered TTLs.
Dynamic acceleration
CDNs also help uncacheable traffic:
- Anycast + persistent connections: TLS and TCP handshakes terminate near the user; the edge keeps warm connections to the origin.
- Origin shield: one edge tier fetches from the origin, reducing fan-in.
- Protocol optimisation: HTTP/2/3, Brotli, early hints.
- Edge compute: auth checks, redirects, A/B routing, header normalisation.
Do not put business logic that requires strong consistency at the edge. Edge state is per-POP and eventually consistent.
Security and access
- Signed URLs/cookies for private media (expiry + HMAC).
- WAF for common attacks; rate limiting at the edge (see Rate Limiting).
- Geo restrictions and bot management.
- TLS: certificates managed at the edge; HSTS.
- Origin protection: allow traffic only from the CDN (mTLS or provider IP ranges), otherwise attackers bypass the edge.
Failure modes
| Failure | Symptom | Mitigation |
|---|---|---|
| Cache stampede | origin 5xx/timeouts after expiry or purge | origin shield, single-flight, stale-while-revalidate |
| Cache poisoning | wrong content served to many users | strict cache keys, validate Host, never cache errors |
| Vary explosion | low hit ratio, high origin load | minimal vary, normalise params |
| Private data cached | data leak | private, no-store on authenticated responses |
| Purge storm | origin overload | versioned URLs, coalescing |
| Stale after deploy | users see old bundle/API | content hashes, short TTLs for HTML |
| Provider outage | some regions degraded | multi-CDN DNS or graceful origin fallback |
| Cost surprise | egress bill | cache hit ratio, compression, request collapsing |
[!WARNING] Never cache a response that depends on
Authorizationwithout including it in the key or marking it private. This is one of the few CDN bugs that becomes an incident with legal consequences.
Measuring a CDN
- Hit ratio (bytes and requests) — overall and per content type.
- Origin offload — requests reaching the origin.
- p50/p95 TTFB per region.
- Purge latency and stale-object rate.
- Error rate by status at the edge vs origin.
A high hit ratio on tiny assets can hide a low hit ratio on the expensive ones; measure bytes.
Interview drill
1. "Design image delivery for 100M users."
- Cover: object storage + CDN; signed URLs; edge transforms; versioned URLs; TTLs; multi-CDN.
- Follow-up: "How do private images work?" (short-lived signed URLs, no shared cache).
- Common miss: serving images from the application origin.
2. "How do you deploy a new frontend without stale caches?"
- Cover: content-hashed bundles; short HTML TTL; atomic index switch; purge only as a fallback.
- Follow-up: "How do you roll back?" (previous index + hashed assets still cached).
- Common miss: long-caching HTML.
3. "A popular video is purged and the origin melts. What happened?"
- Cover: stampede; origin shield; request coalescing; stale-if-error; jittered TTLs.
- Follow-up: "Which metrics reveal it?" (origin QPS, hit ratio, 5xx).
- Common miss: blaming the CDN instead of the invalidation design.
Checklist
- Cache keys include exactly the dimensions that change the response.
- Authenticated responses are never publicly cacheable.
- Immutable assets use content-hashed URLs with long TTLs.
- HTML and API TTLs match the product's staleness tolerance.
- Purges are rare; versioning is the default.
- Origin is protected from direct access and stampedes.
- Edge errors fall back to stale content where acceptable.
- Hit ratio and origin offload are monitored.
Next: Load Balancing — algorithms, health checks, and the tail-latency traps.