SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • CDN
  • Distributed Cache Architecture
  • Cache Stampede
  • Cache Warming
  • Hot Keys
  • Cache Penetration and Cache Avalanche
  • CDN Push vs Pull
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Distributed Caching

CDN

Copies of your files kept in many cities, so users get them from a nearby server.

⏱ 14 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A CDN (Content Delivery Network) is a group of servers spread across many cities. They keep copies of your files, so each user gets them from a server close to them.

  • Close server means less distance, so pages and videos load faster.
  • Your own server (the origin) gets far fewer requests.
  • A CDN also helps with sudden traffic spikes and some attacks.

02Concept: What is it?

Data travels fast, but not instantly. A user in Mumbai who loads an image from a server in New York waits for the signal to cross the world and come back. A CDN fixes this by putting a copy of the image in Mumbai.

With and without a CDN
Without a CDN
🧑User in Mumbai
→↓very far (about 240 ms)
🏢Origin in New York
With a CDN
🧑User in Mumbai
→↓near (about 15 ms)
🗄️Edge in Mumbai
⇢⇣only on a miss
🏢Origin
User Edge (PoP) Origin server
The CDN edge answers most requests. Only a miss travels all the way to the origin.

Some words you will see:

  • Origin: your real server, where the original files live.
  • Edge server: a CDN server near users. It keeps copies.
  • PoP (Point of Presence): a CDN location (a data centre in one city) with many edge servers.
  • Cache hit: the edge has the file and answers. Cache miss: it does not, so it asks the origin.

03Real-Life Example

🍵The Book Shop and the Printing Press
A publisher prints a popular book in one big factory far away. If every reader had to order from the factory, delivery would take weeks. So the publisher sends boxes of books to shops in every city. Readers buy from the shop nearby. The factory only sends more books when a shop runs out.
Book publisher
CDN
Printing factory
Origin server
Shop in each city
Edge server (PoP)
Book on the shelf
Cached file (image, video, script)
Shop has the book: buy at once
Cache hit
Shop is out: order from the factory
Cache miss, fetch from origin
New edition: pull old copies off the shelves
Purge or cache-busting
A request, step by step
🧑1. User askslogo.png
→↓
🗄️2. Edge checksDo I have it?
→↓no
🏢3. Origin sends it
→↓
💾4. Edge saves a copyand replies

04Why Do We Need It?

⚡Faster for users
Less distance means lower delay (latency). Pages feel quick everywhere.
📉Less load on your server
Most requests never reach the origin. You need fewer servers.
🎟️Handles spikes
A viral video is served by hundreds of edges, not one machine.
🛡️Helps against attacks
Edges absorb huge floods of traffic (DDoS) before they reach you.
🔒HTTPS near the user
TLS can end at the edge, so the secure handshake is short and quick.
💰Cheaper bandwidth
Your origin sends each file once per edge, not once per user.
Do not make every user travel to your server. Bring the file to the user.

05Where Do We Use It?

🖼️Images and CSS/JS
Static files on almost every website.
🎬Video streaming
Video is cut into small chunks and cached at the edge.
📦Software downloads
Big updates and app installers.
🛒Online shops
Product photos and pages on sale days.
📰News sites
Pages that many people read at the same time.
🔌APIs
Some responses (like a public product list) can be cached at the edge too.
📝Static and dynamic content
Static content (the same for everyone: images, CSS, JS, video) is perfect for a CDN. Dynamic content (different for each user, like a bank balance) usually goes to the origin. CDNs can still speed it up with fast routes and short-lived caching.

06Types / Parts / How It Works

Pull CDN and Push CDN

Pull CDN
The edge fetches the file on the first request
  • Easy: point the CDN at your origin and it works
  • First user in each region waits (a miss)
  • Files expire after a TTL and are fetched again
  • Most common choice
Push CDN
You upload the file to the CDN yourself
  • No miss on the first request
  • You control exactly what is stored and when
  • You must upload and delete files yourself
  • Good for big, rarely changed files (like game updates)

How does the edge know what to keep?

Your origin sends HTTP headers with every file. The CDN reads them. The most useful one is Cache-Control.

Header / valueWhat it tells the cache
max-age=3600Keep this file for 3600 seconds (1 hour). Browsers and CDNs can both use it.
s-maxage=86400Like max-age, but only for shared caches such as a CDN. The browser can use a different time.
no-cacheYou may store it, but ask the origin if it is still fresh before using it.
no-storeDo not store it at all. Use for private data like a bank page.
privateOnly the user's browser may keep it. A CDN must not.
stale-while-revalidate=60After it expires, serve the old copy for up to 60 more seconds while fetching a new one in the background.
ETagA label for the file version. The cache asks “do you still have version X?” and gets a tiny 304 Not Modified if yes.
Example response from your origin
HTTP/1.1 200 OK
Content-Type: image/png
Cache-Control: public, max-age=300, s-maxage=86400
ETag: "v42-a1b2c3"

Where the CDN finds you: Anycast and DNS

A user needs to reach the nearest edge. CDNs do this with DNS (the answer depends on where you are) or with Anycast, where many edges share the same IP address and the network sends you to the closest one. Read more in Anycast Routing and DNS.

VisualizerClick a user and watch a hit or a missClick each city twice. Then try Purge, a new version and a different TTL.
CDN type
🏢Origin serverYour server · file v1
↕
🗄️Mumbai edgeempty
↕
↕
🗄️London edgeempty
↕
↕
🗄️New York edgeempty
↕

All times are illustrative. Real times depend on distance, the network and the load.

Hit ratio
–
0 hits · 0 misses
Average with CDN
–
Average without CDN
–
straight to origin
Click a user to request the file. The first request to each city is a MISS: the edge asks the far-away origin once, then keeps a copy.

07How to Use It / Steps / Implementation

Putting a CDN in front of your site

  1. 1
    Pick what to cache
    Start with static files: images, CSS, JS, fonts, video.
  2. 2
    Point your domain at the CDN
    Change DNS (usually a CNAME) so users reach the CDN first. The CDN knows your origin.
  3. 3
    Set Cache-Control on the origin
    Long max-age for files that never change. Short or no-cache for pages that change often.
  4. 4
    Use versioned file names
    Name files app.4f2a9c.js. A new build means a new name, so there is nothing to purge.
  5. 5
    Turn on HTTPS at the edge
    The CDN holds your certificate. Keep a secure link from the edge to the origin too.
  6. 6
    Protect the origin
    Only accept traffic from the CDN, so attackers cannot skip it.
  7. 7
    Watch the hit ratio
    A low ratio means files are not being cached well. Fix headers or query strings.
💡Cache busting beats purging
Purging asks every edge to forget a file. It can take time and it costs money on some plans. If the file name changes with its content, the old and new files never clash. Cache the old ones for a year and relax.
📝Think about the cache key
The CDN stores a file under a key, usually the URL. /img?size=small and /img?size=large can be two different entries. Random query strings (like tracking ids) can make every request a miss, so ignore them in the key.

08Key Terms to Know

TermMeaning in easy words
OriginYour own server that holds the original files
Edge serverA CDN server near the user that keeps copies
PoP (Point of Presence)A CDN location, a data centre in one city with many edge servers
Cache hit / missHit: the edge had the file. Miss: it had to ask the origin
Hit ratioHits divided by all requests. Higher is better
TTL (Time To Live)How long a copy is allowed to be used before it expires
Purge / invalidateTell the CDN to delete or ignore a stored copy now
Cache bustingChange the file name (or add a version) so the old copy is not used
Cache-ControlA header that tells caches how long and where they may keep a file
ETag / 304A version label, and a short “not changed” reply that saves bandwidth
Origin shieldOne middle cache layer so many edges ask it instead of all asking the origin
Cache keyWhat the CDN uses to decide two requests want the same file (often the URL)

09Pros, Cons and Trade-offs

✅ Pros
  • Much lower latency for far-away users
  • Less traffic and load on the origin
  • Survives traffic spikes
  • Extra protection from attacks
  • Often lowers bandwidth bills
⚠️ Cons
  • Old content may be shown until it expires or is purged
  • Extra cost and another service to manage
  • Private or personal data needs care
  • Hard to debug: which edge served this?
  • A bad cache rule can serve the wrong file to many users

Trade-offs

ChoiceWe gainWe lose
Long TTLHigher hit ratio, faster, cheaperChanges show up late
Short TTLFresher contentMore misses, more origin load
Pull CDNSimple to runA slow first request in each region
Push CDNNo cold first request, full controlYou manage uploads and cleanup
Cache dynamic pagesBig speed and load winRisk of showing the wrong user's data

10Common Problems and Mistakes

Common mistakes

  1. Caching private data. A page with a user’s name or account gets stored and shown to someone else. Use private or no-store.
  2. No versioned file names. You ship a fix, but users keep the old JS for hours.
  3. Very long TTL on a file you must change soon. You can only fix it by purging everywhere.
  4. Random query strings in the cache key. Every request looks new, so the hit ratio drops to near zero.
  5. Leaving the origin open. Attackers go straight to it and skip all the protection.
  6. Not watching the hit ratio. You pay for a CDN that is not helping.

Problems to know

🕰️Stale content
The edge keeps serving an old copy until the TTL ends.
🥶Cold cache
A new edge or a freshly purged file has no copy, so the first users wait.
🐘Origin overload on purge
If you purge everything, every edge asks the origin at once (see Cache Stampede).
🔀Different edges, different copies
For a short time two users can see two versions.

11Real-World Examples

☁️Cloudflare, Akamai, Fastly, Amazon CloudFront
Big CDN providers. Thousands of sites rent edge servers from them.
🎬Video streaming apps
Video chunks are cached at the edge, near the viewer. Some big services also place their own cache boxes inside internet providers (general idea).
🛒Shopping sites on sale day
Product images and static pages come from the edge. Only checkout needs the origin.
📦Software updates
Large updates are downloaded from nearby edges, not one central server.
📰News sites
A breaking story is read by millions. The edge shares the load.
🧰Package and library downloads
Public libraries for web apps are often served from a CDN.
📝Note
These are general ideas. Each provider has its own design and settings.
Mini case: a product launch
👥Millions of visitors
→↓
🗄️Edge A
🗄️Edge B
🗄️Edge C
⇢⇣misses and checkout
🛡️Origin shield
🏢Origin
Millions view the page. The edges answer almost all requests. The origin handles only the misses and the checkout.

12Related Topics to Read Next

What is Caching?→

A CDN is a cache for files, spread across the world.

Cache Invalidation→

How to remove or refresh old copies.

Cache Stampede→

What happens when many edges miss at the same moment.

Anycast Routing→

How a user is sent to the nearest edge.

DNS→

How your domain is pointed at the CDN.

HTTP / HTTPS→

The headers and TLS that the edge uses.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: servers in many cities that keep copies of your files near users.
  • ✔Why: lower latency, less origin load, spike and attack protection.
  • ✔Pull vs push: pull fetches on a miss. Push means you upload.
  • ✔Control it with: Cache-Control (max-age, s-maxage, no-store, private), ETag, stale-while-revalidate.
  • ✔Update files: use versioned names first. Purge only when you must.
  • ✔Never cache: private, per-user data.
  • ✔Watch: the hit ratio, and protect the origin.
  • ✔One line: “A CDN brings the file to the user instead of making the user travel to your server.”
← Previous
Local Cache vs Distributed Cache
Next →
Distributed Cache Architecture