ealeng

Episode 14 of 55 · Caching

What a cache buys, and how it breaks

Without a cache, requests to a small Postgres database started failing at 4,000 a second. With Redis in front, 5,000 a second ran with no failures and a p99 under 10 ms. Then 5,000 cached items expired at the same moment and 2,348 requests failed, over two runs. How much a cache answers and why skew decides it, where the bottleneck goes, and the two ways a cache breaks: a stampede on one hot item, and many items expiring together.

Lab 08 · Caching and CDNs19 min read
Video transcript8:43

0:00Cold open

0:01

At four thousand requests a second, requests to my database started failing. Three thousand four hundred, out of about eighty thousand.

0:11

Then I put a cache in front of it. Five thousand a second: zero failed, and the slowest one in a hundred took under ten milliseconds.

0:21

But the cache brought its own failure. When five thousand saved items expired at the same moment, two thousand three hundred requests failed, in two runs.

0:32

So what does a cache really buy, and how does it break?

0:38Intro

0:39

Hands-on system design, part fourteen.

0:43

Today: what a cache buys, and the two ways it falls over.

0:48Meet Lucía

0:49

I’m Lucía, a platform engineer.

0:52

My service reads items from a Postgres database. A hundred thousand of them, one at a time.

1:00

The database is small on purpose: half a CPU. A read takes about a third of a millisecond, when it’s quiet.

1:08

And some items are asked for far more often than others.

1:13

Think of a corner shop. The database is the storeroom in the back. The cache is a small shelf by the till, with copies of what people ask for.

1:24

If it’s on the shelf, that’s a hit. If not, that’s a miss: someone fetches it from the storeroom, and puts a copy on the shelf.

1:3301 · What you need

1:35

To run it yourself: Python with a few packages, and Docker for Postgres, Redis, and the app.

1:42

The quick tests run in a couple of seconds, without Docker.

1:47

No cloud, and no API keys.

1:5202 · The cache, in code

1:54

Here’s one read. First, look on the shelf. Here, the shelf is Redis.

1:59

If the copy is there, hand it over.

2:03

If not, fetch it from the database.

2:06

Then put a copy on the shelf, with a time limit. That limit is called the TTL: time to live.

2:14

This pattern is called cache-aside.

2:1903 · A small shelf

2:20

How much can a small shelf answer? I gave it room for one item in a hundred.

2:26

If every item were equally popular, it answers one request in a hundred. Exactly its size.

2:34

Real traffic is usually skewed. I generated skewed requests: the most popular one percent of items got forty-seven percent of them. That’s the best a perfect shelf could do.

2:47

A real shelf fills up, and has to guess what to throw out. Keeping what was used most recently, it answered thirty percent. Keeping what’s asked for most often, forty-three: it holds on to popular items when one-off requests pass through.

3:04

With even more skew: seventy-six and eighty-three percent.

3:09

So the skew decides what a cache can buy you. Measure yours.

3:1504 · No cache

3:17

Now the real service, with no cache. At a thousand requests a second, the slowest one in a hundred took three milliseconds.

3:26

At two thousand, one run took five seconds and the other three milliseconds. We don’t know exactly why the two differed. The database has half a CPU, on a busy laptop.

3:39

At four thousand, requests started failing: three thousand four hundred.

3:45

At five and six thousand, it got worse, not better. At six thousand, the database did nine hundred seventy-nine reads a second in one run, and almost none in the other. A hundred and five thousand requests failed.

4:01

Past the breaking point, everything did less work. Most failures were refused connections at the app, and even my load tester fell seconds behind. We didn’t pin down which part gave out first.

4:1505 · With the shelf

4:17

Same test, with the shelf.

4:20

The database saw between a hundred eighty and three hundred reads a second, at every rate. Seventy to ninety-six percent of requests came off the shelf.

4:31

The slowest one in a hundred stayed under ten milliseconds, up to five thousand a second. Zero failed.

4:39

At six thousand, it broke again: over a second, and a hundred and four failed. But the database only got about a hundred eighty reads a second. The breaking point had moved to the app itself, most likely its one Python process.

4:55

Then I added a tiny shelf inside the app itself, checked before Redis. At six thousand: six and thirty-two milliseconds in the two runs, and nothing failed. The catch: if the app runs several times, each one has its own tiny shelf, and they can disagree. I didn’t test that here.

5:1606 · One popular item expires

5:17

Now, how a cache breaks. One popular item that’s slow to make: a query that took about fifty milliseconds on its own. Its copy lasts three seconds, and it’s asked for five hundred times a second.

5:31

When the copy expires, what happens?

5:37

Everyone who asks before a new copy is ready finds the shelf empty, and runs the same query. That rush is called a cache stampede. In two runs: thirteen times per expiry, and thirty-three. The runs differed a lot: in the slower one, more requests piled up.

5:56

Up to a hundred ninety-six requests were asking the database at once. The slowest took up to three seconds.

6:05

The fix: a lock. Like a note on the shelf: someone’s already fetching this. The first one to find the shelf empty leaves the note and fetches it. Everyone else waits for the copy.

6:17

Exactly one query per expiry. The slowest request: thirty milliseconds.

6:24

Another fix: refresh early, before the copy expires. It helped, but several readers decided to refresh at the same moment: four or five times per expiry.

6:3707 · The lock, in code

6:38

Here’s the lock. Take it only if nobody else has it. It lives in Redis, so every server running the app sees it.

6:47

If someone else has it, keep checking the shelf until the copy arrives.

6:52

If you got the lock, run the query, and put the copy on the shelf.

6:57

Then release the lock.

7:0108 · Many expire at once

7:03

One more way to break it. Five thousand items put on the shelf at the same moment, the way a bulk job or a fresh release can fill it all at once, all with the same ten-second limit. Then four thousand requests a second across them.

7:19

At ten seconds, they all expired together. Database reads went from zero to three thousand four hundred a second, in half a second.

7:29

The slowest requests took seconds, and two thousand three hundred failed, in the two runs.

7:36

The fix: give each copy a slightly different limit, plus or minus twenty percent.

7:43

Now the refills spread over about four seconds. No half-second went above about twelve hundred reads a second. Zero failed.

7:53

That’s called TTL jitter.

7:57Back to Lucía

7:59

So, three lessons.

8:01

Measure your skew. It decides what a cache can buy.

8:06

Plan for an empty shelf. One day it will be empty, and my storeroom alone started failing at four thousand requests a second.

8:16

And make sure each item is refilled once, with a lock, and that the copies don’t all expire together.

8:23

Next time: when the copy on the shelf is out of date.

8:28

For today: plan for an empty shelf.Lucía: Plan for an empty shelf.

8:32Summary

8:33

Measure the skew, plan for an empty shelf, one refill per item, and spread the expiry times.

Key takeaways

  • ✓A cache only answers requests for what it holds, so skew decides what it buys. A cache holding 1% of 100,000 items answered 1.0% of requests when every item was equally popular. When the most popular 1% got 47% of the requests, real Redis answered 30% keeping what was used most recently (LRU) and 43% keeping what's asked for most often (LFU).
  • ✓Without a cache, the database's limit was the service's limit. On half a CPU it was already seconds slow at p99 in some rounds at 2,000–3,000 requests a second, and started failing requests at 4,000 (3,448 of about 80,000). Past that point, everything did less work, not more.
  • ✓With Redis cache-aside, 70–96% of reads came from the cache, the database saw 172–304 reads a second at every rate, and p99 stayed under 10 ms with 0 failures up to 5,000 a second.
  • ✓A cache moves the bottleneck, it doesn't remove it. At 6,000 a second the Redis setup failed 104 requests with the database getting only about 180 reads a second; an in-app cache in front of Redis held p99 at 32 and 6 ms with none failed.
  • ✓Plan for an empty cache. The database behind it has to survive the full load, or at least degrade gracefully, the day the cache is cold or gone.
  • ✓When a popular item's copy expires, everyone who asks before the refill runs the same query: a cache stampede. A 51 ms query ran 13 and 33 times per expiry in two runs, with up to 196 requests asking the database at once. A lock in Redis made it exactly 1, with the slowest request at 30 ms.
  • ✓Copies saved together with one TTL expire together. 5,000 items expiring at once took the database from 0 to 3,426 reads a second in half a second, and 2,348 requests failed over two runs. Plus or minus 20% TTL jitter spread the refills over about 4 s: no half-second above 1,288 reads a second, 0 failed.

A cache can make a small database carry several times its load, and it can also take a service down. This chapter measures both. Without a cache, requests to a Postgres database with half a CPU started failing at 4,000 a second. With Redis in front, 5,000 a second ran with zero failures. Then 5,000 cached items expired at the same moment, and 2,348 requests failed, over two runs. Here's what a cache buys, what decides how much, and the two ways it breaks.

The examples come from Lab 08 (Caching and CDNs) of the system design labs, scripts 01_hit_ratio.py (how much a cache answers, by size, skew and eviction policy), 02_cache_speedup.py (the same load with no cache, with Redis, and with a cache inside the app in front of Redis) and 04_stampede.py (one popular item expiring, and many items expiring together). The same lab's scripts on stale data after a write and on CDN caching (03_staleness.py and 05_cdn.py) are the next chapter, cache invalidation and CDN purges. The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): Postgres 18.6 limited to half a CPU with 100,000 items, Redis 7.4 as the cache, and the item service, a Python web app (FastAPI) running as one process, all in Docker, with the load generator in Docker too. The lab's 398 unit tests (its cache simulator, metrics and cache logic) run in a few seconds without Docker; they all pass. Other work kept the laptop busy (a load average, the number of processes wanting a core, of 7–15), and every load test ran twice, so this chapter shows both runs wherever they differ.

A shelf by the till

Think of a corner shop. The database is the storeroom in the back. The cache is a small shelf by the till, with copies of what people ask for. If the item is on the shelf, that's a hit. If not, it's a miss: someone fetches it from the storeroom and puts a copy on the shelf.

In the lab, the shelf is Redis, an in-memory key-value store that every copy of the app can reach over the network. Reading an item takes a third of a millisecond (0.35 ms) from the database when it's quiet: one query for the item and its ~50 reviews. Here's the read, shortened from the lab's service/app.py:

raw = await redis.get(key)                    # look on the shelf
if raw is not None:
    return json.loads(raw)                    # a hit: hand it over
v = await read_item_db(item_id)               # a miss: fetch it from the database
await redis.set(key, json.dumps(v), px=ttl_ms)    # put a copy on the shelf, with a time limit
return v

The time limit is the TTL (time to live): Redis deletes the copy after it (px sets it in milliseconds). This pattern is cache-aside: the app checks the cache, and on a miss reads the database and fills the cache itself. It's the usual default: the cache only holds what someone asked for, and losing it loses no data, only speed.

The shelf is small, so when it's full, something has to go. The rule for what goes is the eviction policy. Two common ones:

  • LRU (least recently used): throw out whatever was used longest ago.
  • LFU (least frequently used): throw out whatever has been asked for least often.

How much a small shelf answers

The share of requests the cache answers is its hit ratio. What decides it is skew: how unevenly requests spread over items. The lab generates skewed requests with a Zipf distribution: the item ranked k in popularity is asked for in proportion to 1/k^s. With s = 0 every item is equally popular; around s = 1, a few items get most of the requests (s is the skew, nothing more). The lab ran 400,000 requests over 100,000 items through real Redis, with a memory limit set so it held a chosen share of the items; the first 100,000 requests only filled the shelf and weren't counted.

Skew s Shelf holds Best possible Redis, LRU Redis, LFU
0 (every item equally popular) 1% 1.0% 1.0% 1.0%
0 25% 25.0% 25.1% 25.2%
0.6 1% 15.2% 4.9% 11.0%
0.9 1% 47.4% 30.3% 43.4%
0.9 5% 63.1% 47.5% 57.7%
0.9 25% 81.6% 72.8% 76.4%
1.2 1% 85.2% 75.9% 83.1%
1.2 25% 96.9% 94.5% 94.5%

"Best possible" is the share of requests the most popular items get: a shelf that always held exactly the top 1% couldn't do better. (All 16 combinations are in the widget below.)

  • With no skew, the hit ratio is the shelf's size. 1% of the items answered 1.0% of requests, whatever the policy. No item is worth more than another, so there's nothing to choose.
  • With skew, a small shelf answers a lot. At s = 0.9 the top 1% of items got 47% of the requests. A real shelf has to guess what to keep: LRU answered 30%, LFU 43%.
  • LFU won by up to 13 points, because this stream's popularity never changed. LRU throws popular items out to make room for one-off requests; LFU remembers they're popular. Real popularity drifts (yesterday's hot item goes cold), and LFU is slow to notice, which this test can't show.
  • Redis cuts corners, and it shows. It doesn't keep a full list of items by age: it samples 5 keys and evicts the oldest of those, and its clock for "last used" ticks once a second. The lab's own simulator, with an exact LRU, guessed up to 4 points too high. Adding those two shortcuts brought it within about half a point of real Redis, and almost all the difference was the 1-second clock: at the 70,000–110,000 requests a second this test sent, every item used within the last second looks equally recent. At a few hundred requests a second it would matter far less.
Try it · A shelf by the tillLab 08 · 01_hit_ratio.py · 100,000 items · real Redis

100 requests, one dot each · coloured by where the answer came from

RequestsShelf · the cache1,000 items30.3% hitsStoreroom · Postgresall 100,000 items69.7% missesfetched, then copied

This skew and shelf size, three ways to choose what stays on the shelf

Best possible: always holds the most popular items47.4%
Keep what was used last (LRU): Redis, throwing out the least recently used30.3%
Keep what's asked for most (LFU): Redis, throwing out the least frequently used43.4%

Real Redis: 30.3% keeping what was used last, 43.4% keeping what's asked for most (13.1 points apart), against 47.4% for the best possible. LFU keeps popular items when one-off requests pass through; LRU throws them out to make room.

Recorded hit ratios: real Redis 7.4 under a memory limit set so it holds about 1% of the keys, on a generated stream of 400,000 requests (the first 100,000 fill the shelf and aren't counted). "Best possible" is the share the top 1,000 items get, computed from the same skew. The skew s is a Zipf exponent: the item ranked k is asked for in proportion to 1/k^s. The dots and arrows redraw the same hit ratio as a picture.

The lesson is practical: measure your skew before you size a cache. Count requests per item over a day; the share the top 1% gets is the best a 1% cache can do.

No cache

Now the real service, with no cache: every read is a database query. The load is open-loop (as in Chapter 2): requests are sent on schedule whether or not earlier ones have answered, like real users. Requests are skewed (s = 0.9) over all 100,000 items, 10 s per rate, in two rounds. p99 is the time the slowest 1 in 100 requests took. The app reaches Postgres through a pool of 16 connections; a request waits for a free one before its query runs.

Requests a second p99, round 1 / 2 Failed (both rounds) Database reads a second, round 1 / 2 Median wait for a connection, round 1 / 2
1,000 3.3 / 2.9 ms 0 1,007 / 987 0.01 / 0.01 ms
2,000 5.0 s / 2.9 ms 0 2,009 / 1,992 639 / 0.00 ms
3,000 1.1 / 2.9 s 0 3,027 / 3,002 110 / 647 ms
4,000 9.7 / 9.7 s 3,448 of 80,395 3,710 / 3,840 5.9 / 3.8 s
5,000 11.0 / 9.1 s 30,561 of 100,611 2,127 / 2,516 3.0 / 2.1 s
6,000 21.8 / 16.0 s 104,898 of 120,429 979 / 6 286 / 0.01 ms
  • At 1,000 a second, it's fast. p99 3 ms.
  • At 2,000, the two rounds disagree: 5 seconds in one, 3 milliseconds in the other. In the slow round requests waited a median 639 ms for a connection; in the fast one, not at all. The lab didn't find out why. The database has half a CPU on a busy laptop, and Docker enforces that half as a quota every 100 ms, so how much CPU it really gets varies.
  • At 4,000, requests started failing: 3,448 of about 80,000, timeouts and refused connections.
  • At 5,000 and 6,000 it got worse, not better. The database did fewer reads than at 4,000: 979 a second in one round at 6,000, and 6 in the other. Most failures were refused connections (the app wouldn't accept another connection: 55,903 of the 59,929 failures in that second round), and the load generator itself fell seconds behind schedule (its p99 delay in sending was 8.5 and 14.8 s). Past the breaking point, everything did less work. The lab didn't pin down which part gave out first.

So without a cache, the database's limit is the service's limit, and it isn't a sharp line: somewhere between 2,000 and 4,000 a second on this machine, depending on the round.

With the shelf

The same test, with Redis cache-aside (copies kept 120 s), and then with a second, tiny shelf inside the app in front of Redis: an in-process cache, a dictionary in the app's own memory holding up to 20,000 items, checked before Redis.

Requests a second Redis: p99, round 1 / 2 From the cache Database reads a second Failed In-app + Redis: p99, round 1 / 2 Failed
1,000 3.4 / 2.9 ms 69.5% 304 0 2.8 / 3.2 ms 0
2,000 4.0 / 2.6 ms 85.9% 282 0 2.9 / 5.0 ms 0
3,000 3.8 / 3.1 ms 91.5% 257 0 3.2 / 2.4 ms 0
4,000 5.6 / 3.5 ms 94.0% 242 0 5.9 / 3.8 ms 0
5,000 6.1 / 9.1 ms 95.3% 234 0 4.6 / 4.8 ms 0
6,000 1.0 / 1.5 s 96.4% 191 / 172 104 32.2 / 5.9 ms 0
  • The database saw 172–304 reads a second at every rate, because only misses reach it: (1 − hit ratio) × requests. At 3,000 a second, (1 − 0.915) × 3,015 ≈ 256; the app's log counted 257. The hit ratio rose with the rate: copies last 120 s, so at a higher rate more of the less popular items are already on the shelf.
  • p99 stayed under 10 ms with 0 failures up to 5,000 a second, in both rounds. The cache also hid the database's moods: no 5-second rounds.
  • At 6,000 a second, it broke again: p99 over a second, 104 failed (as server errors from the app). But the database got only about 180 reads a second, the fewest of the sweep. The breaking point had moved off the database, most likely to the app's single Python process (the lab's reading; the app's CPU wasn't measured).
  • The in-app shelf moved it again. A hit there skips the network trip to Redis, so the median fell from 0.47 to 0.30 ms at 3,000 a second, and at 6,000 p99 was 32 and 6 ms with nothing failed. The catch: if the app runs as several processes, each has its own in-app shelf, and after a write they can disagree. The lab didn't test that.
Try it · The same load, with and without the shelfLab 08 · 02_cache_speedup.py · Postgres on half a CPU · 2 rounds

p99 latency (the slowest 1 in 100), each round a dot · log scale

1 ms10 ms100 ms1 s10 s1,000/s2,000/s3,000/s4,000/s5,000/s6,000/s✕✕✕✕
No cache Redis (cache-aside) In-app shelf + Redis✕ requests failed (red ring: that round)
No cache
p99, round 1 / 2
9.7 s / 9.7 s
failed, both
3,448 of 80,395
database reads/s
3,710 / 3,840
from the shelf
—

storeroom trips, scale 0–4,000/s

Redis (cache-aside)
p99, round 1 / 2
5.6 ms / 3.5 ms
failed, both
0 of 80,395
database reads/s
240 / 244
from the shelf
94%

storeroom trips, scale 0–4,000/s

In-app shelf + Redis
p99, round 1 / 2
5.9 ms / 3.8 ms
failed, both
0 of 80,395
database reads/s
239 / 246
from the shelf
94%

storeroom trips, scale 0–4,000/s

Without a cache, requests start failing: 3,448 of about 80,000, half of them timeouts and half refused connections in round 1. With the shelf, the database saw about 242 reads a second and nothing failed.

Recorded runs: open-loop load (requests sent on schedule whatever the answers), skewed (s = 0.9) over 100,000 items, 10 s per point, two interleaved rounds. One app process; Redis copies last 120 s. "Failed" counts timeouts, refused connections and server errors from both rounds together. Database reads come from the app's query log. Click a column or a rate to see its numbers.

The cache is now part of your capacity. Suppose 95% of reads are hits and the cache disappears (a restart, a failover, a new empty cluster): the database gets 20 times its usual reads at once, and the no-cache table shows what happens to this one at 4,000 a second. So plan for an empty shelf: keep enough database headroom, fill a new cache before switching to it, or shed load until it fills.

Now, how a cache breaks. One popular item that's slow to make: the ten most-reviewed of the first 200 items, an aggregate over about 10,000 reviews, which took 51 ms alone. Its copy lasts 3 s, and it's asked for 500 times a second for 20 s: 7 expiries per run.

When the copy expires, everyone who asks before the new copy is saved finds the shelf empty and runs the same query. That rush is a cache stampede (also called a dog-pile or thundering herd). Two fixes:

  • A lock (also called request coalescing): a note on the shelf, "someone's already fetching this". The first request to find the shelf empty leaves the note and runs the query; everyone else waits for the copy.
  • Refresh early (the lab uses XFetch, a published rule for this): before the copy expires, each reader rolls a die, with a chance of refreshing that grows as expiry gets near and as the query gets slower. Someone usually refreshes just before it expires, and nobody waits.
Protection Queries per expiry, round 1 / 2 Most asking the database at once p99 Slowest request
none 13 / 33 38 / 196 7 ms / 1.8 s 744 ms / 3.2 s
lock 1 / 1 1 / 1 2.5 / 2.6 ms 26 / 30 ms
refresh early 3.9 / 5.0 18 / 23 2.7 / 2.5 ms 227 / 335 ms

"Most asking at once" counts copies of the query waiting for or holding one of the app's 16 database connections.

  • Without protection, each expiry ran the same query 13 times in one round and 33 in the other. Running together on half a CPU, each copy took a median 87 and 206 ms instead of 51 (up to 692 ms), so the gap before the new copy lasted longer, and more requests fell into it. In the second round the pile got past the 16 connections: up to 196 requests asking at once, and the slowest request took 3.2 s. The two rounds differed a lot because once a stampede gets big, it feeds itself.
  • The lock made it exactly one query per expiry. 30 and 35 requests found the note and waited; the slowest request in either run took 30 ms.
  • Refreshing early meant the copy never expired, but it was refreshed 3.9 and 5.0 times per period instead of once. Several readers rolled a refresh in the same moment, and a slow database makes a refresh take longer, so more readers roll. Nobody waited at p99; the slowest request took 227 and 335 ms, when a refresh fell behind.

The lock, shortened from the lab's /top handler:

if not await r.set(f"lock:{key}", "1", nx=True, px=10_000):   # take the lock, only if nobody has it
    for _ in range(500):                                       # someone has it: check the shelf every 10 ms, up to 5 s
        await asyncio.sleep(0.01)
        raw = await r.get(key)
        if raw is not None:
            return json.loads(raw)["rows"]                     # the copy arrived
rows, delta = await compute_top(scope)                         # got the lock: run the query
await r.set(key, json.dumps({"rows": rows, ...}), px=ttl_ms)   # put the copy on the shelf
await r.delete(f"lock:{key}")                                  # release the lock

nx=True means "set only if the key doesn't exist", so only one request gets the lock. The lock lives in Redis, so every copy of the app sees it. It expires by itself after 10 s (px=10_000), and a waiter gives up after 5 s and runs the query itself, so a request that crashes while holding the lock can't block the item forever.

Many expire at once

The other way to break it. 5,000 items put on the shelf at the same moment, the way a bulk job or a fresh release can fill a cache all at once, all with the same 10 s TTL. Then 4,000 requests a second spread evenly over them.

At 10 s, they all expire together. The fix is TTL jitter: give each copy a slightly different limit, here 10 s ± 20%, so the copies expire anywhere between 8 and 12 s.

TTL Peak database reads a second, 100 ms bins Peak, half-second steps p99 from 1 s before to 5 s after expiry Failed
10 s for all 4,000 / 3,910 3,426 / 3,150 4.1 / 2.4 s 1,623 / 725
10 s ± 20% 1,340 / 1,510 1,220 / 1,288 6.8 / 31.6 ms 0 / 0

(Round 1 / round 2 in each cell.)

  • Without jitter, database reads went from zero to 3,426 a second in one half-second step, about what the no-cache test had already shown this database can't carry. The slowest requests took seconds, and 2,348 failed in the two runs, as errors from the overloaded app. The database also did more reads (6,685 in the 9 s around the expiry) than there were items, most likely because, with refills this slow, several requests for the same item missed before its new copy landed.
  • With jitter, the same refills spread over about 4 s. No half-second step went above 1,288 reads a second (1,510 in the busiest 100 ms), p99 stayed in milliseconds, and nothing failed.
  • Jitter only helps if it's wider than the refill. The lab's first version used 20,000 items, each asked for only every 5 s, so refilling took longer than the ±2 s jitter spread and both versions overloaded the database. With 5,000 items, each is asked for about every 1.25 s.
Try it · When the copies expireLab 08 · 04_stampede.py · 2 rounds each
·

Each time the copy expires: who goes to the storeroom · from the recorded average per expiry

Shelfcopy expiredStoreroomthe 51 ms query32.9×the same query, per expiry
Queries per expiry
32.9
Most asking at once
196
p99 request
1.8 s
Slowest request
3.2 s

230 recomputes in 7 expiries. Everyone who asked before the new copy landed found the shelf empty and ran the query. Running together on half a CPU, each copy took a median 206 ms instead of 51, so the gap lasted longer and more piled in. This round went past the app's 16 database connections: up to 196 requests waiting for or holding one.

Recorded: one hot item whose query takes 50.8 ms alone, 500 requests a second for 20 s, 7 expiries per round. The people are the recorded queries per expiry, rounded; the lab counted totals per round, not per expiry. "Most asking at once" counts queries waiting for or holding one of the app's 16 database connections. The slowest request is the longest whole request; waits weren't timed on their own.

Caveats

  • One laptop, two runs per row, generated traffic. The skew is a Zipf distribution chosen by the lab, not a real trace, and the machine's load average was 7–15. Where the two runs disagree (2,000 a second without a cache, the unprotected stampede), the chapter shows both; don't read either as typical.
  • The database is small on purpose. Half a CPU makes it the scarce part. A real database breaks at a different rate; the shapes (the cliff, the stampede, the step at a mass expiry) are what carry over.
  • The 6,000-a-second Redis failure is blamed on the app, not measured there. The database got only about 180 reads a second, and the in-app shelf fixed it, but the app's CPU wasn't recorded. The app's own timings at that point (queries taking a median 19 ms and waiting 176 ms for a connection) may be inflated by a busy app, which times everything late.
  • The two in-app shelves were not tested against each other. Several app processes, each with its own in-app copy, can disagree after a write. That kind of staleness is the next chapter's subject.
  • The stampede's query is 51 ms in the recorded run. The lab's README describes it as 39 ms; the recorded solo_query_ms is 50.8.
  • The people in the stampede widget are averages per expiry, rounded from the recorded totals per run. The lab didn't record each expiry separately.

The checklist

  1. Measure your skew. The share of requests your top 1% of items get is the best a 1% cache can do.
  2. Pick the eviction policy for your traffic. LFU for stable popularity with lots of one-off requests; LRU when popularity shifts.
  3. Know how much load the cache takes off the database: (1 − hit ratio) × requests. Then ask what happens when it's zero.
  4. Plan for an empty cache: database headroom, warming a new cache before using it, or shedding load until it fills.
  5. Watch where the bottleneck goes. After the cache, it moved to the app; a cache inside the app moved it again, at the cost of copies that can disagree.
  6. Protect expensive popular items from stampedes: a lock so one request refills while the others wait, with a timeout on the lock; or refresh early.
  7. Don't let copies saved together expire together. Add TTL jitter wider than the time the refill takes.

Practice: hit ratios and stampedes

Write the lab's logic: the best hit ratio a cache of k items can get under Zipf skew (checked against the recorded 47.4%), an LRU and an LFU cache (checked against the lab's own simulator on a smaller stream), the database's share of the load, the half-second steps of the recorded mass expiry (3,426 and 1,220), TTL jitter, the early-refresh rule, and queries per expiry from the recorded counts.

Try it · Practice in PythonRuns in your browser · ⌘/Ctrl + Enter to run
cache_practice.py67 lines

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.A cache holds 1% of your items, and every item is equally popular. What share of requests can it answer?

  2. 2.On the same skewed stream, real Redis answered 30% keeping the most recently used items and 43% keeping the most frequently used. Why did LFU win here?

  3. 3.With Redis, 91.5% of 3,015 reads a second came from the cache. Roughly how many reached the database?

  4. 4.At 6,000 requests a second, Redis cache-aside failed 104 requests while the database got only about 180 reads a second. What does that say?

  5. 5.A popular item's query takes 51 ms and it is asked for 500 times a second. Its copy expires. Without protection, what happens?

  6. 6.5,000 items were loaded into the cache at once with the same 10 s TTL. What does TTL jitter of ±20% change?

Check your understanding

Try each question before opening its answer.

Why did a cache holding 1% of the items answer 1% of requests in one test and 30–43% in another?

A cache only answers requests for items it holds. When every item was equally popular, 1% of the items got 1% of the requests. With skew (s = 0.9), the top 1% got 47% of requests, and real Redis answered 30% keeping recently used items and 43% keeping frequently used ones. Skew decides what a cache can buy.

Why did LFU beat LRU by 13 points here, and when might LRU win instead?

The generated stream's popularity never changed, so counting uses kept popular items through runs of one-off requests, which LRU lets push them out. When popularity drifts, LFU keeps yesterday's popular items too long, and LRU, which follows recent use, adapts faster.

Without a cache, the database did fewer reads at 6,000 requests a second than at 4,000. How can more load mean less work?

Past the breaking point, the whole path jammed: most requests were refused at the app before reaching the database, and the load generator itself fell seconds behind. In one round at 6,000 the database did 979 reads a second, in the other 6. The lab didn't pin down which part gave out first, only that everything did less.

Your cache answers 95% of reads and the database runs comfortably. The cache cluster restarts empty. What happens, and what would you prepare beforehand?

Every read goes to the database: 20 times its usual load, all at once. In the lab, this database started failing requests at 4,000 a second without a cache. Prepare by keeping database headroom for a cold cache, warming a new cache before switching traffic to it, or shedding load until it fills.

What is a cache stampede, and why did one expiry cause 33 identical queries in one run but 13 in the other?

When a popular copy expires, every request that arrives before the new copy is saved misses and runs the same query. The copies run together on half a CPU and slow each other down (a median 206 ms instead of 51 in the bad run), so the gap lasts longer and more requests fall into it. Once a stampede gets big, it feeds itself, which is why the two runs differed so much.

How does the lock stop a stampede, and what happens if the request holding it crashes?

The first request to miss sets a lock key in Redis only if nobody else has (set with nx), runs the query and saves the copy; the rest check the shelf every 10 ms until it appears. In the lab that meant exactly one query per expiry and a slowest request of 30 ms. If the holder crashes, the lock expires by itself after 10 s, and waiters give up after 5 s and run the query themselves.

Why did refreshing early still run the query about four or five times per period?

Every reader near expiry rolls the dice, and at 500 requests a second several win in the same moment, before the first refresh has saved a new copy. A slow database makes each refresh take longer, so even more readers roll. It kept the copy from ever expiring and nobody waited at p99, but the lock was the only fix that gave exactly one query.

5,000 items were cached at once with the same 10 s TTL. Why did ±20% jitter take failures from 2,348 to 0?

Without jitter, every copy expired at the same moment and the database went from zero to 3,426 reads a second in one half-second step, more than it could carry. With jitter, the copies expired anywhere between 8 and 12 s, so the same refills spread over about 4 s and no half-second step went above 1,288 reads a second.

Next up: Chapter 15, cache invalidation and CDN purges. When the copy on the shelf is out of date: how long readers see an old value after a write, the classic order-of-operations bug, and a CDN edge that missed its purge.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.