Back to Notes

CDN (Content Delivery Network)

What It Is

A geographically distributed network of edge servers that cache content physically close to users, cutting network latency by avoiding a round trip to the origin server for every request. It's a reverse proxy at global scale (see [[Proxies (Forward vs Reverse)]]).

flowchart LR
    U1[User - US] --> E1[Edge Server - US]
    U2[User - EU] --> E2[Edge Server - EU]
    E1 -->|cache miss| O[(Origin Server)]
    E2 -->|cache miss| O

Two Modes

  • Push CDN: you upload content to the CDN proactively (good for static assets that rarely change — JS bundles, images with versioned filenames).
  • Pull CDN: CDN fetches from origin on first request, then caches it (good for content too large/frequent to push manually — video, user-generated content). First request per edge location pays a cache-miss penalty; subsequent ones are fast.

What Belongs on a CDN

  • Static assets: JS/CSS bundles, images, fonts.
  • Video segments (see the streaming architecture in video-on-demand problems — chunks are cached at edge, manifest files point to the nearest available chunk).
  • Anything cacheable and not personalized — a per-user dashboard doesn't belong on a CDN; a public product image does.

Cache Invalidation — the actual hard part

CDNs solve distribution; they don't solve knowing when content changed. Two practical strategies:

  • Versioned URLs (app.a1b2c3.js): new content gets a new URL, so there's nothing to invalidate — old URL simply stops being requested. This is why most production static-asset pipelines fingerprint filenames.
  • TTL-based expiry: content expires after N seconds/hours, then is re-fetched from origin. Simple, but means updates aren't instant — acceptable for content where a few minutes of staleness doesn't matter, wrong for anything time-sensitive.

Interview Drill

Q: A URL shortener's redirect endpoint returns 301 vs 302. How does this interact with CDN/browser caching? A: 301 Moved Permanently is cached aggressively by browsers and CDNs — great for reducing origin load, but you lose the ability to track click analytics after the first hit (subsequent clicks never even reach your server). 302 Found is not cached, so every click hits your server — worse for load, but you get accurate per-click analytics. This is the same cacheable-vs-personalized trade-off CDNs force everywhere: what you gain in cache efficiency, you lose in per-request visibility.

Cross-links

[[Proxies (Forward vs Reverse)]] · [[Caching & Redis]] · [[Design a URL Shortener]]