Content Delivery Networks
A content delivery network (CDN) is a fleet of caching servers spread over hundreds of cities, called edge locations or points of presence (PoPs). Users connect to the nearest edge instead of your origin servers. A CDN cuts latency (shorter distance), offloads traffic from your origin (most requests never reach it) and absorbs traffic spikes and DDoS attacks.
user in Tokyo ----> [edge Tokyo] --miss--+
user in Paris ----> [edge Paris] --miss--+--> [origin shield] --> [your origin]
user in Lima ----> [edge Lima] --hit (S3 bucket, web servers)An origin shield is a mid-tier cache: edges that miss ask the shield first, so your origin sees one request per object instead of one per edge.
How much does an edge save?
Latency is dominated by round trips. A new HTTPS connection needs about 2 round trips (TCP + TLS 1.3) before the first byte of the response, plus one for the request itself. Shortening each round trip from 150 ms to 10 ms changes everything:
def first_byte_ms(rtt_ms, round_trips=3, server_ms=5):
return rtt_ms * round_trips + server_ms
users = {"Paris": 150, "Tokyo": 230, "Sao Paulo": 190} # RTT to an origin in Virginia
EDGE_RTT = 10
for city, rtt in users.items():
origin = first_byte_ms(rtt)
edge_hit = first_byte_ms(EDGE_RTT)
print(f"{city:<10} origin {origin:4} ms edge hit {edge_hit:3} ms {origin / edge_hit:4.1f}x faster")Paris origin 455 ms edge hit 35 ms 13.0x faster
Tokyo origin 695 ms edge hit 35 ms 19.9x faster
Sao Paulo origin 575 ms edge hit 35 ms 16.4x faster
Push vs pull
| Pull CDN | Push CDN | |
|---|---|---|
| How content gets there | Edge fetches from the origin on the first miss, then caches | You upload content to the CDN ahead of time |
| Good for | Websites, APIs, anything with many objects | Large, predictable files: game patches, video catalogues |
| Downside | The first user per edge pays a miss | You manage uploads and storage |
Cache keys and headers
The CDN decides what to cache from HTTP headers set by your origin:
Cache-Control: public, max-age=31536000, immutable # app.3f9a1c.js, versioned file name
Cache-Control: public, max-age=60, stale-while-revalidate=30 # a product listing
Cache-Control: private, no-store # a user's account pageThe cache key is usually the URL plus selected headers. Including too much (every cookie, every query parameter) splits one object into thousands of variants and destroys the hit ratio. Versioned file names (app.3f9a1c.js) let you cache forever and "invalidate" by deploying a new name.
Simulating edges and a shield
The model below routes a seeded stream of requests through three edges. Each edge is an LRU cache; misses go to a shared origin shield and only shield misses reach the origin.
import random
from collections import OrderedDict
class LRU:
def __init__(self, capacity):
self.capacity, self.items = capacity, OrderedDict()
def lookup(self, key):
if key in self.items:
self.items.move_to_end(key)
return True
self.items[key] = True
if len(self.items) > self.capacity:
self.items.popitem(last=False)
return False
# Zipf-like popularity: object k is chosen with probability ~ 1/k
OBJECTS = range(1000)
WEIGHTS = [1 / k for k in range(1, 1001)]
def popular_object(rng):
return rng.choices(OBJECTS, weights=WEIGHTS)[0]
def run(use_shield, n=30_000, seed=42):
rng = random.Random(seed)
edges = {city: LRU(100) for city in ["paris", "tokyo", "lima"]}
shield = LRU(400)
edge_hits = origin_requests = 0
for _ in range(n):
edge = edges[rng.choice(list(edges))]
obj = popular_object(rng)
if edge.lookup(obj):
edge_hits += 1
elif not use_shield or not shield.lookup(obj):
origin_requests += 1
return edge_hits / n, origin_requests
for use_shield in [False, True]:
hit, origin = run(use_shield)
label = "with shield " if use_shield else "without shield"
print(f"{label}: edge hit ratio {hit:.1%}, origin requests {origin:,} of 30,000")without shield: edge hit ratio 57.6%, origin requests 12,726 of 30,000
with shield : edge hit ratio 57.6%, origin requests 5,356 of 30,000
The edge hit ratio is identical in both runs (same edges, same requests), but the shield answers more than half of the edge misses, so origin traffic drops from 12,726 to 5,356 requests. A popular object now costs the origin one fetch instead of one per edge.
Invalidation
When content changes before its TTL runs out, you can:
- Purge the URL (or a tag / prefix) through the CDN's API. Fast, but it takes seconds to reach every edge.
- Version the URL: reference
logo.v2.pngfrom your HTML. Instant and reliable; the old object just expires. - Short TTL +
stale-while-revalidate: serve the cached copy while fetching a fresh one in the background.
manifest = {"app.js": "app.3f9a1c.js", "style.css": "style.88b2d0.css"}
def deploy(manifest, name, new_hash):
stem, ext = name.rsplit(".", 1)
updated = dict(manifest)
updated[name] = f"{stem}.{new_hash}.{ext}"
return updated
new = deploy(manifest, "app.js", "c41e07")
for name in manifest:
changed = "new URL, cached forever" if new[name] != manifest[name] else "unchanged, still cached"
print(f"{name:<10} {manifest[name]:<18} -> {new[name]:<18} {changed}")app.js app.3f9a1c.js -> app.c41e07.js new URL, cached forever
style.css style.88b2d0.css -> style.88b2d0.css unchanged, still cached
What a CDN can serve
- Static assets: images, JS, CSS, fonts, downloads.
- Video segments for streaming (see Design Video Streaming).
- Cacheable API responses (public product data) with short TTLs.
- Dynamic pages too: even uncached requests benefit, because the edge terminates TLS near the user and keeps warm connections to the origin.
Tip: Never let a CDN cache responses that depend on who the user is unless the cache key includes that (or the response says
private). Leaking one user's page to another is a real, recurring incident.
Test yourself
What is the main purpose of an origin shield?
- Encrypt traffic between users and edges
- Collapse misses from many edges so the origin receives fewer requests
- Block bots
- Compress images
Why are versioned file names like app.3f9a1c.js popular?
- They are shorter
- They can be cached forever, and a new deploy simply uses a new URL
- Browsers require them
- They prevent DDoS attacks
What happens if the CDN cache key includes every cookie?
- Hit ratio improves
- Each user gets their own cache variant, so the hit ratio collapses
- Cookies are deleted
- Nothing changes