Every round trip from Sydney to an origin in Virginia takes at least 160 ms, and no code can beat light. A cache in Sydney answers in about 10 ms, and each hit is a request the origin never sees.
Pick a setup, then drag the cache size. Watch which cache answers each request, the mean wait and the load on the origin. Then we build, piece by piece, hit ratios, popularity, eviction, HTTP freshness, invalidation, stampedes and the CDN's tiers.
You need what an HTTP request is and what a round trip is. Network Foundations helps. We build the rest from zero.
Illustrative simulation. 2,000 objects with Zipf popularity (s = 1), 200 requests a second from each city, LRU caches, each shield four times an edge. Round trips are made-up values a little above the light-in-fiber minimum; each number is one request on an open connection. Chapter 1 works the wait, Chapter 8 the shields.
Chapter 0
Measure what distance costs before a single byte of the page arrives
A user in Sydney opens your site. Your only server, the origin, sits in Virginia. The fiber path between them is about 16,000 km, through the Pacific and across the United States.
Light in glass travels at about two thirds of its speed in a vacuum: roughly 200,000 km each second. No code makes that faster.
Call the one-way path length d and the speed of light in fiber v. The shortest possible round trip is the trip out plus the trip back.
RTT-min equals two times d, divided by v.
Double the path length d, because the reply comes back the same way. Divide by the speed v. Real networks add queues and detours on top, so this is a floor.
Sydney to Virginia: d = 16,000 km, v = 200,000 km/s. RTT-min = 2 × 16,000 / 200,000 = 0.16 s, so 160 ms for every round trip.
Blue arrows go to the server, teal arrows come back, and the yellow axis is time. A new HTTPS page needs three round trips: TCP, TLS and the GET. Move the distance, or put a server nearby.
Illustrative. Light-in-fiber floor only, with TLS 1.3 (one round trip) and no queueing. The 1,000 km "edge nearby" stands for a server about 10 ms away by round trip.
The worked number: TCP needs one round trip, TLS 1.3 one more, and the GET a third. From Sydney that is 3 × 160 = 480 ms before the HTML starts, and the page then asks for its CSS, scripts and images.
You cannot speed up light. You can move the answer. A cache keeps a copy of a response close to the user and answers from it. A CDN (content delivery network) is a fleet of such caches in many cities, each one called an edge.
Failure. Symptom: a page that loads in 0.3 s in your office takes 2 s abroad. Measure: time to first byte per country, from real user timing data. Cause: every request crosses an ocean to one origin. Fix: serve cacheable responses from an edge near each user.
Chapter 1
Turn the hit ratio and watch the mean wait and the origin load follow it
A request that finds its answer in the cache is a hit. One that does not is a miss: the cache asks the origin, returns the answer and keeps a copy. The hit ratio is the share of requests that hit.
Put an edge in Sydney, 10 ms away by round trip. A new page from it costs 3 × 10 = 30 ms on a hit. On a miss, the edge also fetches from Virginia over a connection it keeps open: 30 + 160 = 190 ms.
Call the hit ratio h, the time of a hit thit and the time of a miss tmiss. The mean wait is the two times, each weighted by how often it happens.
L-bar equals h times t-hit, plus one minus h, times t-miss.
Take the share of hits h and multiply it by the hit time t-hit. Take the share of misses, 1 − h, and multiply it by the miss time t-miss. Add the two.
h = 0.9: L-bar = 0.9 × 30 + 0.1 × 190 = 46 ms. Misses are 10% of requests but 19 of the 46 ms. Without the edge, every page costs 480 ms.
The origin sees only the misses. Call the request rate arriving at the cache R and the rate reaching the origin O.
O equals one minus h, times R.
Multiply the arriving rate R by the miss ratio 1 − h. That is the origin's load O.
R = 10,000 per second. At h = 0.95, O = 0.05 × 10,000 = 500. At h = 0.99, O = 100. Four more points of hit ratio cut the origin's load five times.
Each square is one of 100 requests: green hits stay at the edge, blue misses travel to the origin. The bars show the mean wait and the origin's load. Drag the hit ratio.
Illustrative times: hit 30 ms, miss 190 ms, no cache 480 ms; 10,000 requests a second arrive at the edge.
Failure. Symptom: the dashboard shows a 95% hit ratio, yet the origin is overloaded. Measure: hit ratio by bytes and by request, per path. Cause: small objects hit while large or uncacheable ones miss, so the origin still serves most of the work. Fix: track the byte hit ratio and the origin's request rate, not one global number.
Chapter 2
Size a cache from the shape of popularity, not from the size of the catalog
A news site holds a million articles. Today's front page gets millions of reads, and an article from 2009 gets two. Requests pile onto a few objects. That is why a cache much smaller than the catalog can still answer most requests.
The usual model is Zipf's law: the object of popularity rank i gets requests in proportion to 1/is. The rank-1 object is twice as popular as rank 2 when s = 1. Breslau and colleagues (1999) found that web proxy traffic follows a Zipf-like law, with s below 1 and different for each trace.
Suppose the cache holds the most popular objects. Call the catalog size N, the cache size C objects, and the skew s. The hit ratio is the popularity of the top C over the popularity of all N.
h of C equals the sum over i from one to C of i to the minus s, divided by the sum over i from one to N of i to the minus s.
Give each object a weight of 1 over its rank to the power s. Add the weights of the C objects you cache. Divide by the weights of all N objects. That share is h.
N = 1,000,000 and s = 1. A cache of C = 10,000 objects, 1% of the catalog, gets h = 9.79 / 14.39 = 0.68. At s = 0.8 the same cache gets only 0.36.
The curve is the hit ratio against cache size, on a log scale from 10 objects to the whole catalog. The purple dot is your cache. Drag the size, then make popularity flatter or steeper.
Ideal cache that always holds the top C of 1,000,000 objects, with fixed popularity. A real LRU cache does worse; Chapter 3 measures how much.
Read the curve as diminishing returns. Each tenfold step in size adds about the same few points of hit ratio, so the last points cost the most memory. The objects you cache are your working set: the set that gets most of the requests during a period of time.
Failure. Symptom: you double the cache and the hit ratio rises by 3 points. Measure: the hit ratio at several sizes, from a replay of a day's request log. Cause: the misses are in the long tail, where each object gets one or two requests. Fix: stop buying memory; cut the tail's cost with a shield tier (Chapter 8) or by making those responses cheaper.
Chapter 3
Run three eviction policies on the same traffic and see which one keeps the head
A real cache does not know the ranks. It sees requests one at a time. When it is full and a new object arrives, its eviction policy picks which cached object to drop.
LRU (least recently used) drops the object untouched for the longest time. It is cheap and adapts fast. Redis approximates it: it samples a few keys, 5 by default, and evicts the oldest of them.
LRU has a blind spot: one request is enough to get in. Take a 4-slot LRU and the requests A B C D E A B.
LFU (least frequently used) drops the object with the fewest hits. It keeps the head, but it reacts slowly: yesterday's hit keeps its high count today.
W-TinyLFU (Einziger, Friedman and Manes, 2017) adds an admission test. New objects enter a small LRU window, 1% of the cache. To move into the main cache, a newcomer must have been requested more often than the object it would replace. A compact counter tracks the frequency. After a fixed number of requests the cache halves every counter, so old popularity fades. The Caffeine library for Java uses it.
Each row is one policy on the same 30,000 requests. The green area is its hit ratio over time; blue ticks mark bursts of one-time objects; the yellow line marks a change of popularity. Pick a workload.
Simulated live in your browser: 2,000 objects, a cache of 50 (2.5%). LFU here counts only while an object is cached. W-TinyLFU is a small version of the published design: 1% window, segmented main cache, exact counters halved every 500 requests.
The worked number, on the steady workload: LRU hits 29.1%, LFU 41.0%, W-TinyLFU 42.1%. An oracle that always held the top 50 would hit 44.9%. Under the shift, LFU falls to 23.9% because its old counts keep the old hot set; W-TinyLFU's halving lets it recover to 41.5%.
Failure. Symptom: the hit ratio drops every night, then recovers by morning. Measure: hit ratio over time next to batch job schedules. Cause: a nightly scan reads millions of objects once each, and LRU lets every one of them push out the hot set. Fix: an admission filter such as W-TinyLFU, or route batch reads around the cache.
Chapter 4
Read the Cache-Control header the way a browser and a CDN read it
A cache needs two answers for each response: may I store it, and for how long may I use it without asking? The origin gives both in the Cache-Control header. RFC 9111 defines how every HTTP cache reads it.
There are two kinds of cache. A private cache serves one user, like the browser. A shared cache serves many users, like a CDN edge or a reverse proxy.
max-age=60: the copy is fresh for 60 s.s-maxage=300: shared caches use 300 s instead of max-age.private: shared caches must not store it. Use it for one user's page.no-cache: store it, but check with the origin before each use.no-store: store no part of it, anywhere.immutable (RFC 8246): this URL never changes, so do not revalidate while fresh.Call the copy's freshness lifetime F: s-maxage in a shared cache if present, otherwise max-age. Call its age A: the seconds since the origin made the response, including any time it spent in caches upstream.
The copy is fresh if and only if F is greater than A.
Pick the lifetime F that applies to this kind of cache. Work out the copy's age A. If F is still larger, answer from the copy. If not, the copy is stale and the cache must revalidate it (Chapter 5).
Header max-age=60, s-maxage=300, age A = 65 s. The browser has F = 60, and 60 > 65 is false: stale. The CDN has F = 300, and 300 > 65 is true: fresh. The browser asks the CDN, and the CDN answers at once.
Two lanes: the browser and the CDN edge. Green is the fresh window, pink means "ask the origin first", grey means "not stored". The yellow line is the copy's age. Change the header, then drag the age.
Rules from RFC 9111, sections 4.2 and 5.2. Simplified: one copy, made at age 0, with no Expires header and no heuristic freshness.
Failure. Symptom: one user sees another user's account page. Measure: the response headers of personal pages, and whether the CDN reports them as hits. Cause: a personal page went out with public, max-age=60, and the shared cache served one user's copy to the next. Fix: private or no-store on anything personal, and a cache key rule that never shares it.
public, max-age=60, s-maxage=300. A browser's copy is 90 s old. The user reloads. Who answers?Chapter 5
Ask the origin with a fingerprint and get a reply with no body when nothing changed
A stale copy is often still correct. The page simply has not changed. Downloading 50 KB again to learn that is a waste. Revalidation asks the origin a cheaper question: is my copy still current?
The origin gives each version an ETag, a short fingerprint that changes when the content changes. The cache stores it next to the copy. To revalidate, the cache sends the same GET with If-None-Match: "v7".
304 Not Modified, headers only. The cache resets the copy's age and serves it.200 OK with the new body and the new ETag.Blue arrows are requests, teal arrows are responses; the purple box is the browser's copy and its ETag. Load once, reload a few times, publish a change, then reload again.
Illustrative sizes: the page body is 50 KB, and a 304 is counted as 0.3 KB of headers. The copy is sent with no-cache, so every reload revalidates.
The worked number: ten reloads of an unchanged 50 KB page. Without ETags that is 10 × 50 = 500 KB. With them it is 10 × 0.3 = 3 KB. Each reload still costs one round trip, because the question must reach the origin.
A strong ETag, like "v7", promises identical bytes. A weak one, W/"v7", promises only the same meaning; a byte-range request needs a strong one. The older validator is Last-Modified with If-Modified-Since. Its dates count whole seconds, so it misses two edits in the same second.
Failure. Symptom: every reload downloads the full page although nothing changed. Measure: the share of revalidations that return 304. Cause: each server behind the load balancer computes a different ETag for the same file, for example from its own file inode. Fix: derive the ETag from the content, such as a hash of the bytes.
GET /data with If-None-Match: "v5". The data is unchanged. What comes back?Chapter 6
Price a TTL in stale answers, then remove copies the moment data changes
A product's price changes at the origin. Every cache that holds the old page keeps serving it until its copy expires. A TTL (time to live) is that freshness lifetime. A long one saves origin work and serves wrong data longer.
How much wrong data? Suppose the object changes at random times, on average once every 600 s. Call the change rate μ and the TTL T. The cache fetches a fresh copy, and readers read it evenly until it expires.
Sigma equals one minus, one minus e to the minus mu T, all divided by mu T.
At age a, the copy is stale if a change has happened since the fetch, with chance 1 − e−μa. Average that over all ages from 0 to T. When μT is small, σ is about μT / 2.
μ = 1/600 and T = 60, so μT = 0.1. σ = 1 − (1 − 0.905) / 0.1 = 0.048: about 1 answer in 21 is stale. T = 300 gives 0.21. T = 5 gives 0.004, but each cache then refetches 720 times an hour.
The top lane is the origin's version, changing at random times. The bottom lane is the cached copy: purple while it matches, red while it is stale. Blue ticks are refetches. Drag the TTL, then try a purge on every write.
Illustrative: one object, one cache, changes at random (Poisson) times, reads spread evenly. The purge reaches the cache after an assumed 1 s.
So invalidate actively when it matters. A purge asks the CDN to delete one URL. Cache tags (Fastly's surrogate keys, Cloudflare's cache tags) purge every response that carries a tag, like product-42. Versioned URLs such as app.3f9a1c.js never need a purge: new content gets a new URL, so it can carry max-age=31536000, immutable.
Inside a data center the same idea applies. Facebook's memcache paper (NSDI 2013) describes a look-aside cache. On a write, the web server updates the database, then deletes the key instead of setting the new value. Deletes are idempotent. Daemons read each database's commit log and broadcast those deletes.
Failure. Symptom: users see the old price for minutes after a change. Measure: the time from a database write to the first fresh answer at an edge. Cause: TTL-only expiry, or a purge that misses some URL variants. Fix: purge by tag on every write, and keep a TTL as a backstop for lost purges.
max-age=31536000. How do users get the new code?Chapter 7
Expire one hot key and count the misses that hit the origin at once
The front page gets 2,000 requests a second, and its copy expires. The first request misses and asks the origin, which takes 200 ms to build the page. Every request in those 200 ms also misses, and each one asks the origin too. That pile is a thundering herd, or cache stampede.
Call the request rate for the key R and the time to fill the cache tfill. With no protection, the origin gets every request that arrives before the fill lands.
N-herd equals R times t-fill.
Count the requests that arrive while the first miss is still waiting on the origin. Each one also misses, so the origin gets R times t-fill copies of the same work.
R = 2,000 per second, t-fill = 0.2 s. N-herd = 2,000 × 0.2 = 400 identical requests, all for a page the origin builds once.
Requests arrive from the left along the yellow time axis. Blue dots go to the origin; pink dots wait for one fill; teal dots get an answer. Pick a protection, then press Expire.
Illustrative. The origin is drawn red above an assumed 100 requests in flight. Dots are a sample; counts are exact for the chosen rate and fill time.
There are two fixes. Request collapsing sends the first miss to the origin and holds the others until it returns; Fastly does this by default for cache misses. Serving stale answers from the expired copy while one background request refreshes it; RFC 5861 gives the header, as in max-age=600, stale-while-revalidate=30.
Facebook's memcache uses leases. On a miss, the server hands one client a token to refill the key. It issues at most one token per key every 10 s, and tells other clients to wait a moment and retry. On keys prone to herds, the paper reports the peak database query rate fell from 17K/s to 1.3K/s. The token also blocks a stale set: a delete voids it, so a slow writer cannot put an old value back.
Failure. Symptom: the database load spikes every 5 minutes on the minute. Measure: origin requests per key in the second after each expiry. Cause: hot keys share one TTL and expire together, then stampede. Fix: collapse misses, serve stale while revalidating, and add random jitter to TTLs.
Chapter 8
Stack caches so misses meet one shield, and spread keys over servers that come and go
A CDN has hundreds of edges. Each edge misses on its own, so a new object could reach the origin once per edge. A shield (Fastly's word; Cloudflare says upper tier) is a cache between the edges and the origin. Edges ask the shield, and only the shield asks the origin.
Users reach a nearby edge through the CDN's DNS, or through anycast: many sites announce the same IP address, and internet routing picks a nearby one.
Call the edge hit ratio he and the shield's hit ratio on what the edges miss hs. A request reaches the origin only if it misses both.
h-tot equals one minus, one minus h-e, times one minus h-s.
Multiply the two miss shares: that is the part that reaches the origin. Everything else is a hit somewhere.
h-e = 0.85, h-s = 0.80. Origin share = 0.15 × 0.20 = 0.03, so h-tot = 0.97. The shield cuts the origin's load from 15% to 3% of requests.
One site holds many cache servers. Which one owns a key? With hash(key) mod N, adding an 11th server to 10 moves 10 of every 11 keys, and the caches go cold. Consistent hashing puts servers and keys on a ring, and each key belongs to the next server clockwise. Karger and colleagues introduced it in 1997 to spread web cache load.
Moved equals one divided by N plus one.
The new server takes an even share of the ring, 1 of N + 1 parts. Only the keys in that share move, and they all move to the new server.
N = 10. Moved = 1/11 = 9.1% of keys. With mod N, 10/11 = 90.9% move.
Warm ticks are servers on the ring, purple dots are keys, and blue dots are keys that moved. The bars below are each server's share of keys. Add the 11th server, then give each server more points.
Simulated: 20,000 keys, a 32-bit hash. With one point per server the shares are uneven; many points per server ("virtual nodes") even them out.
One point per server gives uneven arcs. In this simulation the busiest of 10 servers holds 2.68 times its fair share, and server 11 takes 15.4% of keys instead of 9.1%. With 100 points per server, the busiest holds 1.24 times and 10.0% move. Those extra points are virtual nodes.
Failure. Symptom: after a cache server is added, the database load jumps for an hour. Measure: the hit ratio of every cache server just after the change. Cause: mod N placement moved 91% of keys to cold servers. Fix: consistent hashing with virtual nodes, so about 1/(N + 1) of keys move.
Chapter 9
Run two minutes of traffic, then purge everything or lose a shield and watch the origin
The hero's CDN, now with a clock. Six cities send 200 requests a second each for two minutes. Choose the cache size, the TTL and the shields, and pick an event at the one-minute mark. The chart shows what the origin sees each second.
Top: requests per second reaching the origin, with its red capacity line. Bottom: each city's mean wait in yellow and its edge hit ratio. Set it up, pick an event, and run.
Illustrative simulation, the same engine as the hero: 2,000 objects, Zipf s = 1, LRU caches, made-up round trips. The origin capacity of 400 requests a second is an assumption for the red line.
Things to try:
The worked number: shields on, 200 objects per edge, TTL 1 h. Edges hit 61% and the shields 58% of the rest, so h-tot = 1 − 0.39 × 0.42 = 0.84. The formula predicts 0.16 × 1,200 = 196 origin requests a second, and the simulation measures 196.
Failure. Symptom: the origin falls over minutes after a deploy. Measure: origin requests per second, next to the purge log. Cause: a full purge emptied every tier at once, and the cold caches sent the full miss load to the origin. Fix: purge by tag or by URL, keep a shield, and serve stale while caches refill.
Chapter 10
Keep the numbers, the headers and the code for the next cache you put in front of an origin
Light sets a floor of 2d/v on every round trip, so a cache moves the answer near the user. The hit ratio sets both the mean wait and the origin's load. Skewed popularity lets a small cache catch most requests, if its eviction policy keeps the head. HTTP headers say how long each copy stays fresh, ETags make revalidation cheap, and TTLs trade staleness for origin work. Herds, purges and new servers are the moments a cache stops protecting the origin. Collapsing, stale-while-revalidate, shields and consistent hashing keep those moments small.
| Term | What it is | This lesson's number |
|---|---|---|
| Round trip floor | RTTmin = 2d / v | Sydney to Virginia: 160 ms; 3 trips: 480 ms |
| Mean wait | L̄ = h · thit + (1 − h) · tmiss | h = 0.9: 46 ms |
| Origin load | O = (1 − h) · R | 10,000/s at 0.95: 500; at 0.99: 100 |
| Zipf head | h(C) = top C weight / all | 1% of 106, s = 1: 68% |
| Eviction | LRU, LFU, W-TinyLFU | steady: 29.1, 41.0, 42.1% |
| Freshness | fresh ⇔ F > A | age 65: browser stale (60), CDN fresh (300) |
| Staleness | σ = 1 − (1 − e−μT) / (μT) | change every 600 s, TTL 60: 4.8% |
| Herd | Nherd = R · tfill | 2,000/s × 0.2 s = 400 |
| Tiers | htot = 1 − (1 − he)(1 − hs) | 0.85 and 0.80: 0.97 |
| Ring | moved = 1 / (N + 1) | 10 to 11 servers: 9.1%, mod N 90.9% |
| Response | Cache-Control | How it changes |
|---|---|---|
| Versioned assets (app.3f9a1c.js) | public, max-age=31536000, immutable | a new file name |
| HTML pages | no-cache, with an ETag | 304 when unchanged |
| Public API responses | public, s-maxage=60, stale-while-revalidate=30 | purge by tag on write |
| One user's data | private, max-age=30 | short TTL |
| Sensitive data | no-store | never cached |
maxmemory-samples 5) and offers LFU with decaying counters.immutable.private or no-store on anything personal.stale-while-revalidate.python# a look-aside cache with TTLs, collapsed misses and stale-while-revalidate (sketch) import time, threading from collections import OrderedDict class Cache: def __init__(self, cap, ttl, swr): self.cap, self.ttl, self.swr = cap, ttl, swr # swr: seconds a stale copy may still be served self.d = OrderedDict() # key -> (value, made_at), kept in LRU order self.fills = {} # key -> Event: one fill per key (collapsing) self.lock = threading.Lock() def get(self, key, load): with self.lock: hit = self.d.get(key) if hit: self.d.move_to_end(key) # LRU: most recent at the end age = time.time() - hit[1] if age < self.ttl: # fresh: F > A return hit[0] if age < self.ttl + self.swr: # stale but allowed: refresh in the background self._start_fill(key, load) return hit[0] ev, mine = self._start_fill(key, load) ev.wait() # every other miss waits on the one fill return self.d[key][0] def _start_fill(self, key, load): # caller holds the lock if key in self.fills: return self.fills[key], False ev = self.fills[key] = threading.Event() def run(): v = load(key) # the one origin request: N_herd becomes 1 with self.lock: self.d[key] = (v, time.time()); self.d.move_to_end(key) while len(self.d) > self.cap: self.d.popitem(last=False) # evict the least recently used del self.fills[key] ev.set() threading.Thread(target=run).start() return ev, True def invalidate(self, key): # on write: delete, do not set (idempotent) with self.lock: self.d.pop(key, None)
Now press Present or Teach and explain five things from memory. Explain why 95% and 99% hit ratios differ five times in origin load, and why 1% of a Zipf catalog can catch two thirds of requests. Explain why no-cache is not no-store, and how a TTL turns into stale answers. Explain how one expiry becomes 400 origin requests. Then go back to the hero, add the shields, and watch the origin's load drop.