Content Delivery Networks (CDNs)

Use CDNs to serve static and media content from edge locations close to users, and understand push vs pull CDNs, cache keys and invalidation.

Beginner · about 2 hours · difficulty 2/5

Learn first: DNS in System Design, HTTP, Connections and Real-Time Protocols

A CDN is a network of edge servers spread across cities. Users fetch content from the nearest edge instead of your origin server, which cuts latency and offloads huge amounts of traffic. Hotstar streaming a cricket final to crores of viewers is only possible because of CDNs.

What to put on a CDN

  • Static assets: JS, CSS, fonts, images.
  • Media: video segments, thumbnails, downloadable files.
  • Cacheable API responses: product catalogue pages, public config.
  • Increasingly, edge compute: redirects, A/B routing, auth checks at the edge.

Pull vs push

  • Pull CDN: the edge fetches from your origin on the first miss, then caches per the Cache-Control headers. Easy to set up; first users pay the miss.
  • Push CDN: you upload content ahead of time. Good for large, predictable files such as a new episode release.

Cache keys and invalidation

The edge caches by a cache key (usually URL plus some headers). Include only what really changes the response; adding cookies to the key destroys the hit ratio. For updates, prefer versioned file names (app.3f9c1.js) over purge requests: a new name is a guaranteed miss, while purges take time to propagate.

Origin protection

A shield or mid-tier cache sits between edges and your origin, so a cache miss storm from 200 edges becomes one request to origin. Combine with request collapsing for hot objects.

Pitfalls

  • Caching personalised responses publicly and leaking one user's data to another.
  • Long TTLs on files whose names never change, so fixes never reach users.

You are ready to move on when you can explain how a CDN would serve product images for a Flipkart sale, including cache keys, TTLs and how a changed image reaches users.

Key concepts

  • Edge locations and PoPs
  • Pull vs push CDN
  • Cache keys and Cache-Control
  • Versioned assets vs purging
  • Origin shield and request collapsing
  • Edge compute

Mini project

Put a small static site behind a free CDN tier, set different Cache-Control headers on HTML and hashed assets, and use response headers to show hits vs misses. Document what changes when you redeploy.

Check yourself

Why is renaming a file (app.v2.js) usually a better way to update cached content than sending a purge request?

Free resources