System design concepts · Making It Fast

How a CDN Works: Caching at the Edge for System Design

The speed of light is not negotiable. A CDN moves your bytes closer to users so it matters less.

What you'll be able to explain
  • Explain how a CDN serves and fills its caches
  • Design cache keys and Cache-Control headers
  • Use origin shielding and tiered caching
  • Serve private content safely with signed URLs
  • Decide what can run at the edge

How a CDN works

A CDN is a global network of edge servers (POPs). DNS or anycast routes each user to a nearby POP. On a hit, the POP responds immediately. On a miss, it fetches from the origin (your servers or object store), caches the response, and serves it.

CLIENTUsers · DelhiCLIENTUsers · ChennaiCLIENTUsers · DubaiNETWORKEdge POPDelhiNETWORKEdge POPChennaiNETWORKEdge POPDubaiCACHEOrigin shieldMumbaiOBJECT STOREOriginobject store / appmissmissmissrare miss
Tiered CDN with an origin shield: many edges, one mid-tier, very few origin hits.

An origin shield is a mid-tier cache that all edges consult before the origin. Without it, a newly uploaded video might be fetched from your origin once per POP (hundreds of times); with it, once.

What to put on a CDN

Content Cacheable? Typical TTL
Versioned assets (app.3f9a.js) Yes, forever 1 year, immutable
Images, video segments Yes Days to a year
Public pages, product listings Yes, briefly 30 s–5 min, stale-while-revalidate
Public API responses (trending, config) Often Seconds to minutes
Personalised pages, carts No (or edge-composed) private, no-store
Private files (invoices, paid PDFs) Yes, with signed URLs Short-lived signatures

Cache keys and headers

The cache key decides which requests share a cached object. By default it's the URL. Adding unnecessary query parameters, cookies or headers to the key destroys hit ratios; leaving needed ones out serves the wrong content (e.g. Hindi page to an English user).

Key headers:

  • Cache-Control: public, max-age=31536000, immutable for fingerprinted assets.
  • Cache-Control: public, s-maxage=60, stale-while-revalidate=300 lets the CDN serve slightly stale content while refreshing in the background.
  • ETag / Last-Modified let clients revalidate cheaply (304 Not Modified).
  • Vary: Accept-Encoding (fine) vs Vary: Cookie (usually kills caching).
Tip

Never "purge" your way through deploys. Fingerprint asset filenames (app.3f9a.js), so a new deploy uses new URLs and old ones can stay cached forever. Purges are slow, rate-limited and easy to get wrong.

Private content: signed URLs

For paid or private files, generate a URL containing an expiry and a signature (HMAC of path + expiry, made with a secret the CDN knows). The CDN verifies the signature and serves the file without calling your app. Share links expire; users can't guess other files' URLs.