A content delivery network (CDN) is a fleet of caching servers spread across hundreds of cities. Instead of every user fetching your images, scripts, videos and even API responses from one faraway origin, they get them from an edge server a few milliseconds away. CDNs cut latency, offload the vast majority of traffic from your origin, absorb traffic spikes and DDoS attacks, and increasingly run your code at the edge too.
Think of it like
Neighborhood bookstores
A publisher could ship every book from one central warehouse, but readers would wait days. Instead, popular titles are stocked in neighborhood bookstores. When a shop doesn't have a book, it orders one copy from the regional depot (which orders from the warehouse only if it must), sells it, and keeps it on the shelf for the next reader. When a new edition comes out, the shops either pull the old one (a purge) or the new edition simply gets a new ISBN (a versioned URL).
Why CDNs exist
Physics. London to Sydney is about 17,000 km; light in fiber covers roughly 200,000 km per second, so a round trip takes at least 170 ms, and real routes take 250 ms or more. Opening a TCP connection, negotiating TLS and sending a request costs several round trips before the first byte arrives. Moving the content to a server in the user's own city removes most of that distance.
London ↔ Sydney RTT
~250 ms
physics floor ~170 ms in fiber
RTT to a nearby edge
~5–20 ms
PoP in the same metro area
Static asset hit ratio
95–99%
with good cache keys and long TTLs
Origin traffic at 99% hits
1 in 100
requests that reach your servers
How a CDN serves a request
- 1
Route to the nearest edge
The user resolves
cdn.example.com. Anycast or the CDN's own DNS steers them to a nearby point of presence (PoP). - 2
Terminate the connection
TCP and TLS handshakes happen with the edge, a few milliseconds away instead of an ocean away.
- 3
Compute the cache key
The edge derives a key from the request (host, path, selected query parameters and headers).
- 4
Hit or miss
On a hit, the cached object is returned immediately. On a miss, the edge asks an upstream tier (an origin shield) or the origin.
- 5
Store and serve
The response is cached according to its
Cache-Controlheaders and returned to the user.
The simulation above shows hit ratio and origin load changing as you adjust TTLs and traffic. The diagram below follows misses, hits and an uncacheable request through a tiered CDN.
Points of presence and routing
A PoP is a cluster of cache servers (RAM and SSD) in a metro area, usually inside or next to internet exchange points and ISP networks. Large CDNs operate PoPs in hundreds of cities. Getting each user to a good PoP is done in one of two ways, often combined.
DNS-based mapping
- The CDN's authoritative DNS returns the IP of a nearby, healthy PoP
- Can weigh load, cost and real-time network measurements
- Location is inferred from the resolver (improved by EDNS Client Subnet)
- Changes wait on short DNS TTLs
Anycast
- Every PoP announces the same IPs over BGP
- Routers deliver packets to the nearest PoP automatically
- A failing PoP withdraws its routes and traffic shifts in seconds
- Spreads DDoS floods across the whole network. See Domain Name System (DNS) for details
Pull vs push CDNs
Pull (origin pull)
- Edges fetch content lazily on the first request
- No upload pipeline: just point the CDN at your origin
- The first request per PoP is slow (a miss)
- The default for websites, APIs and most assets
Push
- You upload content to the CDN's storage ahead of time
- Great for large, rarely changing files: installers, game patches, video libraries
- No cold misses at launch
- You manage uploads, storage and deletion yourself
Cache keys and HTTP caching headers
The cache key decides which requests share a cached object. By default it is roughly scheme + host + path + query string, plus any request headers listed in Vary. Every irrelevant difference in the key (tracking parameters, parameter order, casing) creates a separate cache entry and quietly destroys your hit ratio.
| Header | Meaning | Example |
|---|---|---|
Cache-Control: max-age=N | Fresh for N seconds in any cache (browser and CDN) | max-age=600 |
s-maxage=N | Overrides max-age for shared caches (CDNs, proxies) only | max-age=60, s-maxage=3600 |
public / private | May shared caches store it? private means only the user's browser may | private for personalized pages |
no-cache | May be stored, but must be revalidated with the origin before every reuse | HTML that must always be current |
no-store | Never store anywhere | Bank statements, PII |
immutable | Will never change; skip revalidation even on reload | Fingerprinted assets |
stale-while-revalidate=N | Serve a stale copy for up to N s while refreshing it in the background | max-age=60, stale-while-revalidate=300 |
stale-if-error=N | Serve stale for up to N s if the origin is failing | Resilience during outages |
ETag / Last-Modified | Validators for conditional requests: If-None-Match → 304 Not Modified | ETag: "a1b2c3" |
Vary | Adds the named request headers to the cache key | Vary: Accept-Encoding |
# Fingerprinted static assets (app.3f9a1c.js): cache for a year, never revalidate
Cache-Control: public, max-age=31536000, immutable
# HTML shell: CDN keeps it 60 s, browsers revalidate, stale served during refresh
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=30, stale-if-error=86400
# Personalized API response: browser only, always revalidate
Cache-Control: private, no-cache
# Sensitive data: never stored anywhere
Cache-Control: no-storecurl -sI https://cdn.example.com/app.3f9a1c.js | grep -iE 'cache-control|^age|x-cache'
# cache-control: public, max-age=31536000, immutable
# age: 5321 <- seconds this copy has been in cache
# x-cache: Hit from cloudfront <- vendor-specific hit/miss headerInvalidation: purge vs versioned assets
Purge (invalidation)
- Tell every PoP to drop a URL, a wildcard or a tag
- Takes seconds to minutes to reach every edge
- Can cost money (CloudFront charges per path beyond 1,000 per month)
- A big purge sends a wave of misses to the origin
Versioned URLs
- Put a content hash in the filename:
app.3f9a1c.js - A new deploy produces new URLs; nothing needs invalidating
- Instant, atomic and free; old and new versions coexist safely
- Cache assets for a year with
immutable
Beyond static files
Dynamic content acceleration
- Edge TLS termination: the handshake round trips happen near the user.
- Warm origin connections: edges keep persistent, pre-established connections to the origin.
- Optimized routing: traffic rides the CDN's backbone, avoiding congested public paths (Cloudflare Argo, Akamai SureRoute).
- Modern protocols: HTTP/2 and HTTP/3 (QUIC) to clients even if the origin only speaks HTTP/1.1. See HTTP, HTTPS & TLS.
- Compression: Brotli or gzip at the edge.
- Micro-caching: caching "dynamic" pages for just 1–5 seconds absorbs flash crowds almost completely.
Edge compute
CDNs now run your code inside the PoP: Cloudflare Workers (V8 isolates), Fastly Compute (WebAssembly), CloudFront Functions and Lambda@Edge, plus Vercel and Netlify edge functions. Good uses are small, latency-sensitive decisions: redirects, auth checks, A/B bucketing, header rewrites, geolocation personalization, image resizing and cache-key normalization. Edge functions have tight CPU and memory limits, and your database is still far away, so heavy data access belongs at the origin.
export default {
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
// 1. Redirects answered at the edge: the origin never sees them
if (url.pathname === "/old-pricing") {
return Response.redirect(new URL("/pricing", url).toString(), 301);
}
// 2. Reject obviously unauthenticated admin traffic before it costs origin CPU
if (url.pathname.startsWith("/admin") && !request.headers.get("Authorization")) {
return new Response("Unauthorized", { status: 401 });
}
// 3. Normalize the cache key: tracking params must not create new cache entries
for (const key of [...url.searchParams.keys()]) {
if (key.startsWith("utm_") || key === "fbclid") url.searchParams.delete(key);
}
url.searchParams.sort();
// 4. Fetch through the edge cache using the normalized URL
return fetch(new Request(url.toString(), request));
},
};Security at the edge
- DDoS absorption: a CDN's aggregate capacity dwarfs any single origin, and anycast spreads floods across every PoP. Volumetric L3/L4 attacks never reach you.
- Web application firewall (WAF): blocks SQL injection, XSS and known exploit patterns; bot management separates humans from scrapers.
- Edge rate limiting: throttle abusive clients before they consume origin resources. See Rate Limiting.
- Managed TLS: automatic certificates and modern cipher suites.
- Signed URLs and cookies: time-limited access to paid or private content (video, downloads).
Cost model
| Cost driver | Notes |
|---|---|
| Edge egress (per GB) | Usually the largest line item; tiered by volume and pricier in some regions (South America, parts of Asia) |
| Requests (per 10k or 1M) | Dominates for small objects such as API responses and thumbnails |
| Origin egress | What your cloud charges to send data to the CDN; transfer from AWS origins to CloudFront is free, other pairings vary |
| Invalidations, edge compute, WAF rules, logs | Add-ons that grow with usage |
| Committed contracts | At large scale, per-GB prices are negotiated |
Key takeaways
- CDNs serve content from PoPs near users, cutting latency that is ultimately bounded by the speed of light.
- Users reach PoPs via anycast or DNS-based mapping; origin shields collapse misses so the origin sees very little traffic.
- Pull CDNs fetch lazily on first request; push CDNs are pre-loaded. Pull in front of object storage is the common default.
- Cache-Control (max-age, s-maxage, stale-while-revalidate), cache keys and Vary decide what is cached and how well.
- Prefer versioned (fingerprinted) URLs over purges; cache them for a year with
immutable. - Modern CDNs also accelerate dynamic traffic, run edge code, absorb DDoS attacks and host WAFs.
Common pitfalls
- Caching personalized responses as
public, leaking one user's data to another. - Letting tracking parameters, header variations or
Vary: Cookiefragment the cache key. - Relying on purges for every deploy instead of fingerprinted asset names.
- Leaving the origin publicly reachable so attackers can bypass the CDN.
- Forgetting that a mass purge or a CDN outage sends full traffic to an origin sized for 1% of it.
Interview tips
- State the cacheability of each response type and the TTL you would use.
- Explain pull vs push and why you chose one (most designs: pull from object storage).
- Quantify: "at a 98% hit ratio, the origin only serves 2% of requests" justifies a much smaller origin.
Real-world applications
- Images, CSS and JavaScript bundles for websites and apps.
- Video streaming segments (HLS/DASH) for on-demand and live video.
- Software downloads and game patches.
- API acceleration and micro-caching for read-heavy endpoints.
- Edge security: DDoS protection, WAF and bot management.
Test yourself
Which header lets a CDN cache a response for an hour while browsers cache it for only one minute?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.