Courses / System Design Interview / Chapter 10
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 10 of 49
Content Delivery Networks
Builds on Building Blocks: The Parts Every Design Reuses and DNS: Turning Names into Addresses. Next up: Unique IDs: Sequencers, UUIDs and Snowflake IDs.
Part 1 · Why distance matters
The speed limit of distance
A user in Mumbai who loads a page from a server in London waits for the signal to cross the planet, and fast server code cannot change that. A content delivery network (CDN) is a set of servers placed in many cities that keep copies of your content, so that the user talks to one nearby instead.
Latency has several parts: the time the signal spends travelling, the time it waits in queues, and the time a machine spends working. Only the first is fixed by physics. A signal in optical fibre travels at roughly two thirds of the speed of light in a vacuum. This lesson uses 2,00,000 km per second, or 200 km per millisecond, as an assumption, and takes distances along the great circle between two cities. Real cables are longer than the straight line, so the numbers below are minimums.
from math import asin, cos, radians, sin, sqrt CITIES = {"Mumbai": (19.08, 72.88), "Delhi": (28.61, 77.21), "London": (51.51, -0.13), "San Francisco": (37.77, -122.42)} KM_PER_MS = 200 # assumption: light in fibre, about 200,000 km/s def km(a, b): la1, lo1, la2, lo2 = map(radians, (*CITIES[a], *CITIES[b])) h = sin((la2 - la1) / 2) ** 2 h += cos(la1) * cos(la2) * sin((lo2 - lo1) / 2) ** 2 return 2 * 6371 * asin(sqrt(h)) for a, b in [("Mumbai", "Delhi"), ("Mumbai", "London"), ("Delhi", "San Francisco")]: d = km(a, b) rtt = 2 * d / KM_PER_MS print(f"{a} to {b}: {d:,.0f} km, round trip at least {rtt:.0f} ms")
rtt.py: round-trip time bound from distance
Mumbai to Delhi: 1,147 km, round trip at least 11 ms Mumbai to London: 7,192 km, round trip at least 72 ms Delhi to San Francisco: 12,356 km, round trip at least 124 ms
Python 3.12.10. Deterministic: the inputs are fixed coordinates.
Mumbai to Delhi is about 1,150 km and costs at least 11 ms for a round trip. Mumbai to London is about 7,200 km and costs at least 72 ms. Delhi to San Francisco is about 12,400 km and costs at least 124 ms. These are floors: they leave out every router and every queue on the way.
Round trips add up
A single round trip is not what a user pays. Before a browser receives the first byte of a page from a distant server on a new connection, it makes several trips in sequence. One round trip opens the TCP connection. With TLS 1.3, one more sets up encryption. One more carries the request and brings the first bytes of the reply. That is about three round trips.
| Distance | One round trip, at least | Three round trips, at least |
|---|---|---|
| Mumbai to Delhi | 11 ms | 33 ms |
| Mumbai to London | 72 ms | 216 ms |
| Delhi to San Francisco | 124 ms | 372 ms |
A user far from the server waits a third of a second before anything arrives, even when the server is instant. A CDN attacks this from two sides. The user's connection ends at an edge server in a nearby city, so those round trips are short. And the edge answers from its copy when it has one, so there is no long trip at all. When it has no copy it fetches one from the origin, the server where your content lives, over a connection it keeps open for the next time.
Fewer round trips
The count of three depends on the protocol. TLS 1.2 needed two round trips for a full handshake, so the same request took four. TLS 1.3 (RFC 8446) cut that to one. HTTP/3 (RFC 9114) runs over QUIC (RFC 9000), which sets up the transport and the encryption in the same round trip, so a new connection needs about two round trips before the first byte. Each step down helps a distant user most, because every round trip removed is worth 124 ms from Delhi to San Francisco and only 11 ms from Mumbai to Delhi. Reusing an open connection removes the setup trips altogether, as the curl run in the building blocks chapter showed.
The places where the CDN keeps its servers are called points of presence. The user reaches the nearest one through DNS answers that depend on location, or through anycast routing, both described in the dns chapter.
The calculation gives at least 72 ms for Mumbai to London. Why 'at least'?
- It assumes a straight great-circle path and no delay in routers or queues. Real cables and equipment only add time.
A user in Delhi opens a new connection to a server in San Francisco. Roughly how long, at least, before the first byte over TCP with TLS 1.3, and over HTTP/3?
- TCP plus TLS 1.3 plus the request is about three round trips: at least 372 ms. HTTP/3 needs about two: at least 248 ms.
- Both assume an instant server and the straight-line distance, so real numbers are higher. An edge in Delhi cuts each trip to a few milliseconds.
What does an edge server change about those round trips?
- The user's connection ends at a nearby city, so each trip is short, and a cached copy means no trip to the origin at all.
Part 2 · Edge caching and cache headers
How an edge decides
An edge server is a shared cache. It stores a response and reuses it for later requests, and two rules decide whether it may. The cache key says which requests count as the same. By default it is the request method and the URL, so a second GET for the same URL can reuse the first answer. A header called Vary can add more, such as the request's language. The freshness lifetime says how long a stored response may be reused without asking the origin.
The origin sets that lifetime with the Cache-Control response header. RFC 9111, the HTTP caching standard, lists the order in which a shared cache works it out: s-maxage if present, otherwise max-age, otherwise Expires minus Date, and otherwise a heuristic. A response is fresh while its age is below that lifetime and stale after.
| Directive | Means | Applies to |
|---|---|---|
| max-age=N | Fresh for N seconds from when it was generated | Every cache, including the browser |
| s-maxage=N | Fresh for N seconds, and overrides max-age | Shared caches such as a CDN |
| public | May be stored by shared caches, even where they otherwise would not, such as a request with an Authorization header | Shared caches |
| private | Only the user's own browser may store it | Shared caches must not |
| no-store | Do not keep a copy anywhere | Every cache |
The cache also reports how old its copy is in an Age header, in seconds. A client reading Age: 12 with max-age=60 knows the answer has 48 seconds of freshness left.
A small origin and an edge you can run
To see the headers at work, the next programs build an origin and an edge cache. Python 3.12.10 and curl 8.21.0 on this machine, with the origin on port 55446 and the edge on 55447. The origin is a plain HTTP server. It counts its requests, and for /logo.png it replies with public, max-age=10, s-maxage=60. It also has a switch that makes it fail, which a later lesson uses.
import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer hits = {"n": 0, "down": False} class Origin(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/admin/down": # toggle failure mode hits["down"] = not hits["down"] return self.reply(200, b"toggled", {}) hits["n"] += 1 print(f"origin: request #{hits['n']} {self.path}", flush=True) if hits["down"]: return self.reply(503, b"down", {}) if self.path == "/logo.png": cc = "public, max-age=10, s-maxage=60" else: cc = "max-age=2, stale-while-revalidate=4, " cc += "stale-if-error=20" body = f"page v{hits['n']}".encode()
origin.py, part 1: counts requests, sets Cache-Control
self.reply(200, body, {"Cache-Control": cc}) def reply(self, code, body, headers): self.send_response(code) for k, v in headers.items(): self.send_header(k, v) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass ThreadingHTTPServer(("127.0.0.1", 55446), Origin).serve_forever()
origin.py, part 2: the reply helper and the server
The edge keeps a dictionary of stored responses. lifetime reads the headers the way RFC 9111 orders them for a shared cache, with s-maxage first. On a request it serves a copy younger than its lifetime and tags the response HIT. Otherwise it asks the origin, stores the result, and tags it MISS. Every response carries an Age header. To stay short, this edge ignores private and no-store and caches every reply; a real shared cache must honour both.
import re import time import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer ORIGIN, store = "http://127.0.0.1:55446", {} def lifetime(cc): """Seconds the response stays fresh in a shared cache.""" for name in ("s-maxage", "max-age"): # s-maxage wins m = re.search(name + r"=(\d+)", cc) if m: return int(m.group(1)) return 0
edge_basic.py, part 1: reading the lifetime
What the headers showed
A script fetched /logo.png through the edge three times, with a 3 second and then a 9 second pause between requests, and printed the cache tag and the Age.
URL=http://127.0.0.1:55447/logo.png show() { curl -s -D - -o /dev/null $URL | grep -E "X-Cache|Age" | tr -d '\r' \ | tr '\n' ' ' echo } show; sleep 3; show; sleep 9; show
demo_basic.sh: three requests through the edge
X-Cache: MISS Age: 0 X-Cache: HIT Age: 3 X-Cache: HIT Age: 12
Python 3.12.10 and curl 8.21.0 on this machine, with the origin on port 55446 and the edge on 55447.
The first request missed, and the origin log shows it received one request. The second, three seconds later, was a hit with Age: 3. The third, twelve seconds after the first, was still a hit even though max-age=10 had passed, because the edge applies s-maxage=60. A browser would have used max-age=10 and asked again. That split lets an origin say 'browsers, check back soon; CDN, keep it a minute'.
A response has Cache-Control: max-age=10, s-maxage=60. How long does a CDN treat it as fresh?
- Sixty seconds. For a shared cache,
s-maxageoverridesmax-age. - The browser still uses ten seconds.
In the run, the third request had Age: 12 and was still a HIT. Why was that correct?
- The edge's freshness lifetime came from
s-maxage=60, and 12 is below 60.
Which directive keeps a user's account page out of a CDN's cache?
private, which forbids shared caches from storing it, orno-storeto forbid every cache.- The server must send it, because the CDN cannot guess.
Part 3 · Pull and push, and what belongs on a CDN
Two ways to fill an edge
There are two ways for content to reach an edge server. In a pull CDN the edge starts empty and fetches from your origin the first time a user asks, as the scene above showed. In a push CDN you upload content to the CDN's own storage ahead of time, and the CDN distributes it to its edges. You, not the first user, trigger the transfer.
| Pull | Push | |
|---|---|---|
| Who fills the edge | The first request after a miss | You, when you publish |
| First user in a region | Pays the trip to the origin | Finds it already there |
| Origin needs to stay up | Yes, for misses | Not for content already pushed |
| Effort | Almost none: set headers | You manage uploads and removals |
| Good for | Many small files, sites that change often | Large files with a known release time, such as a video or a game patch |
Most sites use pull because it needs nothing but correct headers. Push suits a large file released at a known time, where you want it spread before the first user arrives and do not want the first viewers to hit your origin together.
What belongs on the edge
The test for a CDN is simple: can one stored response safely serve many users? If the answer is yes, put it there.
| Content | On the edge? | Why |
|---|---|---|
| Images, scripts, style sheets | Yes | Identical for everyone, rarely changed |
| Video segments | Yes | Large, identical, requested again and again |
| A public article or product page | Yes, with a short lifetime | Same for all, changes occasionally |
| A page with the user's name or cart | No | Different per user; mark it private |
| A response that sets a cookie | Usually no | The cookie belongs to one user |
| A write such as a payment | No | A cached answer is not the action |
A page is often a mix. The product photos are the same for everyone, and the cart count is not. The usual fix is to split them: serve the shared parts from the CDN and load the personal part from the origin with a separate request. A cache that wrongly stores a personal response and serves it to someone else is a serious leak, so when in doubt, mark the response private or no-store.
The cache key matters here too. If the origin returns different content by language and the key ignores language, one user's version is served to another. The Vary header tells the cache which request headers to add to the key. The cost is more entries, so vary on as little as you can.
A cache key that splits
The opposite mistake is a key that holds too much. Marketing links add tracking parameters such as utm_source to a URL, and the page does not change with them. If the key is the whole URL, every variant is a separate entry and a separate trip to the origin. The program below sends five requests for one shoes page to an origin on port 55448, through an edge modelled as a function, once with the whole URL as the key and once with a key that keeps only size, the one parameter that does change the page.
import threading import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qsl, urlencode, urlsplit ORIGIN = "http://127.0.0.1:55448" class Origin(BaseHTTPRequestHandler): hits = 0 def do_GET(self): Origin.hits += 1 body = f"shoes page for {self.path}".encode() self.send_response(200) self.send_header("Cache-Control", "public, max-age=300") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass
cache_key.py, part 1: an origin that counts its requests
def whole_url(path): return path def kept_params(path): # only "size" changes the page url = urlsplit(path) keep = [(k, v) for k, v in parse_qsl(url.query) if k == "size"] return url.path + ("?" + urlencode(keep) if keep else "") def edge(paths, key): store, tags, Origin.hits = {}, [], 0 for path in paths: k = key(path) if k in store: tags.append("HIT") continue with urllib.request.urlopen(ORIGIN + path) as r: store[k] = r.read() tags.append("MISS") tags = " ".join(tags) print(f"{key.__name__:11} {tags:24} origin: {Origin.hits}") server = ThreadingHTTPServer(("127.0.0.1", 55448), Origin) threading.Thread(target=server.serve_forever, daemon=True).start() PATHS = ["/shoes?utm_source=mail", "/shoes?utm_source=ads", "/shoes?utm_source=app", "/shoes?size=9", "/shoes?size=9&utm_source=mail"] edge(PATHS, whole_url) edge(PATHS, kept_params) server.shutdown()
cache_key.py, part 2: two cache keys and the same five requests
whole_url MISS MISS MISS MISS MISS origin: 5 kept_params MISS HIT HIT MISS HIT origin: 2
One real run on Python 3.12.10. The output is the same on every run.
With the whole URL as the key, all five requests missed and the origin served five times for what is two distinct pages. With the cleaned key, the three tracking variants shared one entry, the two size=9 requests shared another, and the origin served twice. Keeping size in the key matters as much as dropping utm_source: a key that dropped every parameter would serve the size 9 page to someone who asked for the plain one. CDNs let you set the key, usually as a list of parameters to keep or to ignore.
Part 4 · Invalidation and versioned file names
Changing something that is cached everywhere
A cached copy is a promise that the content will not change until it expires. When you do change it, you have two choices: wait for the lifetime to pass, or invalidate, which means asking the CDN to drop its copies. Most CDNs offer a purge for a URL or a path.
A purge has awkward edges. It reaches many edge servers, and for a short time some may still hold the old copy. Browsers keep their own copies, and a purge cannot reach them. And you must remember to do it on every deploy, for every changed file.
There is a cleaner way to avoid the problem. If a file's name changes whenever its content changes, the old name never needs to be purged, because nobody asks for it any more. This is versioned file names, or fingerprinting: the build puts a hash of the content in the file name, app.fc787e30.js, and the page that refers to it is regenerated to use the new name.
Names that carry a hash
The program below names three files by the first eight characters of a SHA-256 hash of their bytes, simulates a new deploy in which only app.js changed, and prints each file's name before and after.
import hashlib def build(files): """Name each file by a hash of its content and rewrite the page.""" names = {} for name, data in files.items(): stem, ext = name.rsplit(".", 1) digest = hashlib.sha256(data).hexdigest()[:8] names[name] = f"{stem}.{digest}.{ext}" return names v1 = {"app.js": b"console.log('v1')", "style.css": b"body{margin:0}", "logo.png": b"\x89PNG-bytes"} v2 = dict(v1, **{"app.js": b"console.log('v2')"}) # app.js only n1, n2 = build(v1), build(v2) for name in v1: state = "same" if n1[name] == n2[name] else "NEW NAME" print(f"{name:10} {n1[name]:20} -> {n2[name]:20} {state}")
hashed.py: content-hashed names across a deploy
app.js app.fc787e30.js -> app.a23d0f93.js NEW NAME style.css style.20077037.css -> style.20077037.css same logo.png logo.7c5ee53a.png -> logo.7c5ee53a.png same
Python 3.12.10. Deterministic: SHA-256 of fixed bytes.
Only app.js got a new name. The style sheet and the logo kept theirs, so every cached copy of them, in browsers and on edges, stays valid across the deploy. The file whose name changed starts as a miss and gets cached on its own.
This allows a very long lifetime for such files. If a name is tied to its content, the file at that name never changes, so you can give it Cache-Control: public, max-age=31536000, a year in seconds, without risk. The one file that must stay short-lived is the page that lists the hashed names, because it is how users learn about the new ones. Give the page a short lifetime or revalidate it every time, and give the fingerprinted files a long one.
Long lifetimes, safely
One more directive fits these files. immutable, defined in RFC 8246, tells a browser that the response will not change while it is fresh, so it should not revalidate it even when the user reloads the page. Without it, a reload can make the browser ask the server about every file, and the answer for a fingerprinted file is always 'not modified'. The full header for such a file is often public, max-age=31536000, immutable.
The common mistake is to apply the long lifetime by file type rather than by name: a rule that gives every .js file a year also catches a script that is not fingerprinted, such as a third-party loader included by a fixed name. When that file changes, users keep the old one for up to a year and no purge can reach their browsers. Long lifetimes belong only to names that change with the content.
Purging keeps one legitimate use. If a wrong file was published under a name that is already cached, such as a page with a mistake in it, a purge is the fastest way to remove it everywhere. Treat it as an emergency tool, and use versioned names for the routine case of shipping new code.
After a deploy, style.20077037.css has the same name as before. What does that mean for caches?
- The file's content has not changed, so every cached copy is still correct and stays valid.
Why can a hashed file be given a one-year lifetime safely?
- Its name is derived from its content, so the same name always means the same bytes. A change produces a new name.
- The page that refers to the name must stay short-lived.
Name two problems with purging as the main way to update content.
- Browsers keep their own copies that a purge cannot reach, and some edges may serve the old copy briefly.
- You must also remember to purge on every deploy.
Part 5 · Stale content, origin shielding and tiered caches
Serving a copy that has expired
A strict cache stops serving a response the moment it expires, and the next user waits for the origin. Two extensions in RFC 5861 relax that rule on purpose.
stale-while-revalidate=N lets a cache serve an expired response for up to N more seconds while it fetches a new one in the background. The user gets an answer at once, and the copy is fresh by the next request. stale-if-error=N lets a cache serve an expired response when the origin returns an error, a 500, 502, 503 or 504, for up to N seconds past expiry. The user gets an old page instead of an error.
Watch for the edge: it answers from an expired copy and refreshes behind it
Read it as steps
The edge answers at once from a stale copy and fetches a new one in the background.
The two extensions trade freshness for speed and availability. They suit content that is fine to be a few seconds old, such as a news list, and they do not suit an account balance. The origin sets them in the same header, for example max-age=2, stale-while-revalidate=4, stale-if-error=20.
An edge that serves stale content
The second edge handles both directives. decide returns a tag for each request: HIT while fresh, STALE-REVALIDATING when the copy has expired but is inside the revalidation window (a background thread then refreshes it), MISS when it must fetch, and STALE-IF-ERROR when the origin fails but the copy is still inside the error window. Otherwise the error passes through as a 502.
import re import threading import time import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer ORIGIN, store = "http://127.0.0.1:55446", {} def directive(cc, name): m = re.search(name + r"=(\d+)", cc) return int(m.group(1)) if m else 0 def fetch(path): """Ask the origin and store the answer; 5xx raises an error.""" with urllib.request.urlopen(ORIGIN + path, timeout=2) as r: cc = r.headers.get("Cache-Control", "") store[path] = {"body": r.read(), "at": time.time(), "cc": cc}
edge_stale.py, part 1: reading directives and fetching
def decide(path): """Return (tag, entry): fresh, stale-while-revalidate or error.""" e, age = store.get(path), 0 if e: age = time.time() - e["at"] fresh = directive(e["cc"], "max-age") if age < fresh: return "HIT", e if age < fresh + directive(e["cc"], "stale-while-revalidate"): threading.Thread(target=refresh, args=(path,)).start() return "STALE-REVALIDATING", e try: fetch(path) return "MISS", store[path] except OSError: # HTTPError is a kind of OSError if e and age < directive(e["cc"], "max-age") + directive( e["cc"], "stale-if-error"): return "STALE-IF-ERROR", e raise def refresh(path): try: fetch(path) except OSError: pass
edge_stale.py, part 2: the decision
The last part is the handler and the server start. It turns the tag into an X-Cache header, adds Age, and answers 502 when no copy can be used. Save the three parts together as edge_stale.py, with the imports at the top of part 1.
class Edge(BaseHTTPRequestHandler): def do_GET(self): try: tag, e = decide(self.path) except OSError: self.send_response(502) self.send_header("Content-Length", "0") return self.end_headers() self.send_response(200) self.send_header("X-Cache", tag) self.send_header("Age", str(int(time.time() - e["at"]))) self.send_header("Content-Length", str(len(e["body"]))) self.end_headers() self.wfile.write(e["body"]) def log_message(self, *args): pass ThreadingHTTPServer(("127.0.0.1", 55447), Edge).serve_forever()
edge_stale.py, part 3: the handler and the server
Shields and tiers
A CDN with hundreds of edges has a problem: a popular file that expires everywhere causes hundreds of edges to ask the origin at about the same time. Origin shielding puts one more cache in front of the origin. Edges that miss ask the shield, and only the shield asks the origin, so the origin sees one request for the file instead of one per edge. A tiered cache generalises the idea into layers: edge, then regional, then shield, then origin.
Shields also help the cold start. When a new file is requested in ten regions at once, the first miss fills the shield and the other nine are served from it, provided the shield merges misses that arrive at the same moment. A related rule, request coalescing, makes an edge that has several simultaneous misses for the same URL send only one request to the next layer and answer them all from its reply.
What does stale-while-revalidate=30 allow, and what does the user gain?
- A cache may serve the copy up to 30 seconds past expiry while it refreshes in the background. The user gets an immediate answer.
- The cost is that the answer can be up to 30 seconds past its lifetime.
When does stale-if-error apply?
- When the origin fails with a 500, 502, 503 or 504 and the copy is within the allowed staleness. The cache serves the old copy rather than the error.
What load problem does origin shielding solve?
- Many edges asking the origin for the same file at once. The shield takes the misses from the edges and sends one request on.
- Request coalescing does the same inside one edge.
Part 6 · Dynamic content and security at the edge
Beyond static files
Some content cannot be cached: a search result, a cart, a response to a form. A CDN can still help with it. The user's connection ends at a nearby edge, which keeps a long-lived, already-warm connection to the origin and forwards the request over it. The expensive connection setup happens between user and a nearby edge, and the long-distance leg reuses a connection that was opened earlier. This is dynamic acceleration: it does not cache the response, but it shortens the path.
An edge can also take work off the origin without caching whole pages. It can compress responses, resize images for the user's screen, and answer simple requests from small programs that run at the edge. Each of these is a trade: more logic at hundreds of places is harder to test and update than logic in one.
Security at the edge
A CDN sits in front of the origin, so it takes the first contact from every user and every attacker. That makes it a natural place for several protections.
| Protection | How the edge helps |
|---|---|
| TLS | Ends the encrypted connection near the user, so the handshake round trips are short; holds certificates |
| Denial of service | Absorbs floods across many sites, so no single site carries the whole attack |
| Hiding the origin | Allows the origin to accept traffic only from the CDN, so attackers cannot go around it |
| Filtering | Blocks known bad requests before they reach the origin |
| Protected downloads | Checks a signed URL or token before serving a private file |
These help only when the origin is closed to everyone else. If an attacker learns the origin's address, a flood sent straight to it skips the CDN. So the origin should accept connections only from the CDN's published address ranges, or require proof that a request came through the CDN, such as a secret header or a client certificate that only the CDN holds.
Locking the origin
The program below shows the secret-header version on this machine. The origin, on port 55450, answers only requests that carry X-Edge-Secret with the right value. The CDN would add that header to every request it forwards, so the second request carries it the way the edge would send it. Python 3.12.10.
import threading import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer SECRET = "demo-edge-secret" # known to the CDN and the origin only class Origin(BaseHTTPRequestHandler): def do_GET(self): ok = self.headers.get("X-Edge-Secret") == SECRET body = b"product page" if ok else b"forbidden" self.send_response(200 if ok else 403) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass
origin_lock.py, part 1: an origin that answers only the edge
def get(headers): req = urllib.request.Request("http://127.0.0.1:55450/shoes", headers=headers) try: with urllib.request.urlopen(req) as r: return r.status, r.read().decode() except urllib.error.HTTPError as e: return e.code, e.read().decode() server = ThreadingHTTPServer(("127.0.0.1", 55450), Origin) threading.Thread(target=server.serve_forever, daemon=True).start() print("straight to origin:", *get({})) print("through the edge: ", *get({"X-Edge-Secret": SECRET})) server.shutdown()
origin_lock.py, part 2: one request without the header, one with it
straight to origin: 403 forbidden through the edge: 200 product page
One real run. The output is the same on every run.
A request that goes straight to the origin gets a 403, so learning the origin's address no longer lets an attacker skip the CDN's protections. A header check still costs the origin a little work for each rejected request, so a large flood is better stopped earlier, by a firewall that admits only the CDN's address ranges. The secret itself must be treated like a password: kept out of code repositories, and changed when people who knew it leave.
Measuring the edge
Once a CDN is in place, one number tells you whether it is working: the cache hit ratio, the share of requests answered from an edge without going to the origin. A ratio that is lower than expected usually points to a cause you can fix, such as an origin that sends no-store by mistake, URLs with a changing query string that make every request a new cache key, as in the cache key run earlier in this chapter, or lifetimes that are too short.
| Term | Meaning |
|---|---|
| CDN | A network of servers in many cities that serve copies of your content |
| Edge server | The CDN server nearest the user |
| Origin | The server where the content really lives |
| Cache key | What decides whether two requests share a stored response |
| s-maxage | A freshness lifetime that applies only to shared caches |
| Origin shield | A cache between the edges and the origin that merges misses |
Why can a CDN speed up a request whose response it cannot cache?
- The user connects to a nearby edge, which forwards the request over a connection to the origin that is already open, so the slow setup steps cover a short distance.
An attacker finds your origin's address and floods it directly. What went wrong in the design, and what would the run's origin have done?
- The origin accepts traffic from anywhere, so the CDN can be skipped. It should accept connections only from the CDN.
- The locked origin in the run answered such requests with a
403; a firewall that admits only the CDN's ranges would drop them before they reach the server.
All chapters · Previous: Design a Distributed Key-Value Store