ealeng

Episode 15 of 55 · Caching

Cache invalidation and CDN purges: how long readers see old data

Clearing the cache before changing the price left readers seeing the old price for almost a full second after 22 of 24 changes: about twice as long as doing nothing. Why caches serve old data after a change, why the order of the steps matters, why the right order still fails when a copy is slow, and how a version check stops it. Then the same question at the edge: what a CDN's timer, a version tag and stale-while-revalidate save, and why one lost purge means a full timer of old pages.

Lab 08 · Caching and CDNs18 min read
Video transcript9:27

0:00Cold open

0:01

To be careful, I wiped the cache first, and only then changed the price in my database.

0:08

Readers kept seeing the old price for almost a full second, typically.

0:14

Doing nothing at all was better: about half a second.

0:19

How can wiping the cache make it worse?

0:24Intro

0:25

Hands-on system design, part fifteen.

0:28

Today: why caches show old data, and how to keep it short.

0:34Meet Lucía

0:35

I’m Lucía, a platform engineer.

0:38

Here, eight readers read one item’s price through a cache, nonstop. Real Postgres, and Redis as the cache.

0:46

A writer changes the price at random moments, about every one and a half seconds. Each change gets a new version number. And the price on the board has a timer: one second, then it’s wiped. That timer is called the TTL.

1:02

A read is stale if it was sent after a change was confirmed, and still got the older version.

1:10

Think of a café. The database is the kitchen’s price book. The cache is the board by the counter. Readers are customers reading the board. If the board is empty, the customer reads the book and writes the price up for the next person. That’s copying it up.

1:2801 · What you need

1:29

To run it yourself: Python with a few packages, and Docker for the database, the cache, and two more caches I’ll explain later.

1:39

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

1:44

No cloud, and no API keys.

1:4802 · Four ways to write

1:50

Here’s the code that changes the price. There are four ways to handle the cache. The first is to do nothing, and wait for the board’s timer to run out.

2:00

Second: wipe the cache first, then change the database.

2:05

Here’s the change itself: a new price, and a new version number.

2:11

Third: change the database, then wipe the cache.

2:15

And fourth: change the database, then write the new price into the cache.

2:2203 · Do nothing

2:23

First, do nothing. Twenty-four changes. Every one was followed by stale reads.

2:30

Typically for about half a second. A change lands partway through the one-second timer, so about half of it is left.

2:39

Twenty-three percent of all reads got an old price.

2:4504 · Wipe first

2:46

Now the careful one: wipe the board first, then change the book.

2:51

Better or worse than doing nothing?

2:57

Worse. A few fewer changes went stale, twenty-two of twenty-four, but each one for almost a full second, typically. About twice as long.

3:08

Forty percent of all reads got an old price.

3:1305 · Why wiping first hurt

3:15

Here’s the most likely way it happens. The writer wipes the board, and starts changing the book.

3:22

A customer finds the board empty, and reads the book. The change isn’t finished yet, so the book still says the old price.

3:31

The customer copies the old price back up, with a fresh one-second timer.

3:37

That’s why the old price typically lived almost one full second: one whole timer.

3:44

Changing the book first, then wiping or writing the board: zero stale reads, in twenty-four changes each. With no pause in the copying, the gap for a late copy is tiny.

3:5706 · A slow copy

3:59

But zero in twenty-four isn’t never. So I made the copying slow on purpose: a fifty millisecond pause, between reading the book and writing the board.

4:10

A pause like a slow network. To make collisions more likely, the timer is now three hundred milliseconds, and the price changes about twice a second.

4:21

Change-then-wipe and change-then-write both went stale, in ten of eighty changes, for up to about a third of a second: about one full timer here.

4:32

The board’s timer runs out. A customer reads the book: the old price. Then pauses.

4:39

Meanwhile the writer changes the book and updates the board. Then the slow customer writes the old price over it.

4:4907 · A guarded copy

4:50

The fix: every price on the board carries its version number. And copying it up is done by a small script inside Redis, all in one step, so no one can sneak in between the check and the write.

5:03

It looks at the newest version already on the board.

5:08

If the new copy is older, it refuses.

5:12

Otherwise, it writes it.

5:1608 · No more late copies

5:17

After a wipe, there’s nothing to compare against. So instead of wiping, the writer can leave a note. Say the new price is version eight. The note says: eight or newer only. That’s called a tombstone.

5:31

Readers see an empty board, read the book, and only a version-eight price gets in.

5:37

Same slow copies, same eighty changes. Writing the new price, with guarded copies: zero stale. The tombstone, with guarded copies: zero.

5:48

The script refused ninety-seven late copies in one run, and seventy-two in the other: several readers at a time try to copy up. Those were old prices that never got in.

6:0209 · Copies far away

6:03

Now copies far away. A CDN is a set of caches near your users, called edges. In the café: other branches, each with its own copy of the page, and the origin is the main kitchen. Here, two Varnish caches on my laptop play the edges.

6:21

Keeping copies longer saves the kitchen work, but each copy can be old for longer. First, the saving. With no copy kept, every request reached the main kitchen.

6:34

Keep the branch’s copy for one second: fifty-eight percent still reached it.

6:40

Five seconds: thirty-nine. Thirty seconds: twenty-one.

6:45

A version tag, called an ETag, helps too. When its copy runs out, the branch asks the kitchen: is my page still the same as before? If yes, no page is sent. At five seconds, the kitchen prepared about six thousand five hundred pages with the tag, against eleven thousand seven hundred without.

7:0610 · A slow kitchen

7:08

One popular page, and I made the kitchen take two hundred milliseconds to prepare it, on purpose. The branch keeps its copy for two seconds.

7:18

Each time the copy ran out, everyone who arrived while the kitchen prepared it again waited. Two hundred thirty-seven requests took over a hundred milliseconds.

7:30

With a version tag, the check was a quick “unchanged”. Twenty-seven slow requests, most likely from the very first fill, when the branch had nothing yet.

7:40

With stale-while-revalidate, the branch shows its old copy while it fetches a new one in the background. It’s allowed to show old data, for up to ten seconds past its timer, in exchange for speed. Also twenty-seven slow requests.

7:57

The slowest one in a hundred: a hundred ninety milliseconds with nothing. Thirty-nine with the tag, twenty-seven with this: about the same.

8:0811 · Tell every branch

8:09

Last: after a page changes, phone every branch to wipe its copy. That’s a purge. Here, the branch’s copy has a ten-second timer.

8:20

Phone both branches: the old page was gone within about two milliseconds.

8:26

Now I skipped one branch’s purge, as if the call got lost. That branch showed the old page for about ten seconds: its full timer. Phone nobody, and both branches showed it for about ten seconds.

8:41

So the worst case after a change isn’t the purge time. It’s the timer.

8:48Back to Lucía

8:49

So, three lessons.

8:52

Change the database first, then wipe the cache. Never the other way round.

8:58

A slow copy can still put old data back. Guard it with a version number.

9:04

And tell every branch. The timer is your worst case.

9:09

Next time: copies of the whole database, and replication.

9:14

For today: the book first, then the board.Lucía: Book first, then the board.

9:18Summary

9:20

The database first, guarded copies, and every branch told.

Key takeaways

  • ✓A cached copy is stale from the moment the database changes until the copy is replaced. With a 1 s timer (TTL) and nothing else, every one of 24 price changes was followed by old reads, for 542 ms at the median: about half the timer, because a change lands partway through it.
  • ✓Deleting the cached copy before updating the database was worse than doing nothing: 22 of 24 changes went stale, but for 981 ms at the median, and 40.1% of all reads got an old price against 23.3%. A reader misses in the gap, reads the old row and copies it back with a fresh timer.
  • ✓Updating the database first, then deleting or overwriting the copy, gave 0 stale changes in 24. Zero in 24 isn't never: with a 50 ms pause injected between a reader's database read and its cache write, both went stale after 10 of 80 changes, each for about one full timer (up to 325 and 346 ms with a 300 ms timer).
  • ✓A guarded fill stores a version with every copy and lets a small script inside Redis refuse any copy older than what's there. After a delete there's nothing to compare against, so the writer leaves a tombstone, a marker that says which version is the oldest allowed. Both gave 0 stale changes in 80, refusing 97 and 72 late copies.
  • ✓At the edge, a timer keeps traffic from the origin: 100% of requests reached it with no copy kept, 57.6% with a 1 s timer, 39.3% with 5 s and 21.4% with 30 s. A version tag (ETag) turns a refetch of an unchanged page into a bodyless 304: at 5 s the origin built 6,451 pages with it and 11,738 without.
  • ✓With a slow origin (200 ms, injected), every expiry made the users arriving during the refetch wait: 237 requests over 100 ms, p99 190 ms. With a version tag or stale-while-revalidate, 27 each and a p99 of 39 or 27 ms, about the same given their wide confidence intervals.
  • ✓A purge that reaches an edge ends the old page within about 2 ms here. An edge it misses keeps the old page for its whole timer: 10.0 s with a 10 s timer. The worst case after a change is the timer, not the purge time.

A shop changes a price. To be careful, the code clears the cache first and only then writes the new price to the database. Readers then see the old price for almost a full second after nearly every change, about twice as long as if the code had done nothing at all. This chapter measures how long readers see old data after a change, for each way of handling the cache, then the same question one layer further out, at a CDN's edge caches.

The examples come from Lab 08 (Caching and CDNs) of the system design labs, scripts 03_staleness.py (how long readers see an old value after a write, for each write strategy) and 05_cdn.py (HTTP caching at the edge, with two Varnish caches standing in for a CDN), with the lab's modules staleness.py (the stale-window measure), probe.py (the probes that read and write) and service/cache_logic.py (the guarded fill). Chapter 14 covers the same lab's first half: what a cache buys (scripts 01_hit_ratio.py and 02_cache_speedup.py) and cache stampedes (04_stampede.py). The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): Postgres 18.6 as the database, Redis 7.4.2 as the cache, Varnish 8.0.2 for the edges and a Python web service (FastAPI) in between, all in Docker. The lab's 398 unit tests (the stale-window measure on hand-made timelines, the cache simulator, the percentile code) run in about 2 seconds without Docker; they all pass. Other work kept the laptop busy (a load average, the number of processes wanting a core, of about 6 to 12), so read the shapes, not the last digit.

What "old data" means

A cache keeps a copy of something that's slow to get, so the next reader gets it fast. Here the service reads one item from Postgres and keeps a copy in Redis, an in-memory key-value store. The pattern is cache-aside: a reader checks Redis first; on a miss (nothing there) it reads the database and fills the cache, writing the row to Redis for the next reader. Each copy has a TTL (time to live): a timer after which Redis drops it.

Think of a café. The database is the kitchen's price book. The cache is the board by the counter. Customers read the board; if it's empty, a customer reads the book and writes the price up for the next person. The board's timer is the TTL.

When the price changes in the book, the board is wrong until someone fixes it. The lab measures exactly how long:

  • Every change bumps the item's version number (v7 becomes v8).
  • 8 readers read the item in a tight loop, about 7,500 reads a second together in the first run, and record the version each read got.
  • A writer changes the price at random moments, on average every 1.5 s, for 45 s: 24 changes. The gaps between changes are random (exponential) but come from a fixed seed, so every strategy gets the same schedule.
  • A read is stale if it was sent after a change was confirmed to the writer and still got an older version. A change's stale window is how long after its confirmation the last stale read was sent: 0 if there was none.

Four ways to write

The lab's set_price in service/app.py can handle the Redis copy four ways, chosen per request (shortened):

if strategy == "delete_before":
    await redis.delete(key)                    # wipe first...
async with conn.transaction():                 # ...then change the price and bump the version
    version = await conn.fetchval("UPDATE items SET price_cents = ..., version = version + 1 ...")
if strategy == "delete_after":
    await redis.delete(key)                    # change, then wipe
elif strategy == "write_through":
    await redis.set(key, json.dumps(new_row), px=ttl_ms)    # change, then write the new copy
# ttl_only: nothing; wait for the timer
The lab's name What the writer does In the café
ttl_only Nothing; the copy expires on its timer Wait for the board's timer
delete_before Delete the copy, then update the database Wipe the board, then change the book
delete_after Update the database, then delete the copy Change the book, then wipe the board
write_through Update the database, then write the new copy Change the book, then write the new price up

Deleting before the update is the lab's planted bug: a mistake put there on purpose, to see whether the probe catches it.

Do nothing, or wipe first

Timer 1 s, 24 changes each:

Write strategy Changes followed by stale reads Stale window, median Longest Reads that were stale
do nothing 24 of 24 542 ms 817 ms 23.3%
wipe first, then change 22 of 24 981 ms 999 ms 40.1%
change, then wipe 0 of 24 0 0 0%
change, then write 0 of 24 0 0 0%

Doing nothing is stale after every change, for about half the timer. A change lands at a random point of the copy's 1 s timer, so on average about half of it is left: 542 ms at the median.

Wiping first was worse. A few fewer changes went stale, 22 of 24, but each one for almost the full second, about twice as long, and 40% of all reads got an old price. The probe caught the planted bug.

Try it · The board and the price bookLab 08 · 03_staleness.py · 8 readers, one item, 45 s per row

One price change at the café · illustration of the mechanism, not a recorded trace

0250 ms500 ms750 ms1000 mschange confirmedPrice bookPostgresBoardRedisCustomera readerv7v8v7 copied back · a fresh 1 s timerv812345
Old price (v7) New price (v8) Empty board Customers see the old price after the change
  1. To be careful, the writer wipes the board first.
  2. A customer finds the board empty and reads the book. The change isn't saved yet, so the book still says version 7.
  3. The customer copies v7 back up, with a fresh 1 s timer.
  4. Now the change is saved and confirmed. The board still shows v7.
  5. The old price lives until that fresh timer runs out: almost a full second after the change.

The recorded run: 24 changes, timer 1000 ms

Changes followed by old reads
22/24
Old for, median
981 ms
Reads that got the old price
40.1%
Old copies refused
0

A few fewer changes went stale than doing nothing (22 of 24 against 24), but each for almost the whole timer: 981 ms at the median against 542, longest 999 ms. 40.1% of reads got an old price, against 23.3%.

The timelines are drawn from the lab's code paths (service/app.py) and settings, not recorded: the steps before the change is confirmed are stretched so you can see them (in the lab they take a few milliseconds), and one customer stands for eight readers. v7 and v8 stand for the version number every change adds. The counts are the recorded runs, one 45 s run per row, with the same random change schedule (exponential gaps, fixed seed) in every row. The window is measured from the confirmation to the last read sent after it that still got an older version.

Why wiping first hurt

The lab doesn't trace individual reads, but the code allows one way for this to happen, and the windows of about one timer fit it:

  1. The writer wipes the board and starts changing the book.
  2. A customer finds the board empty and reads the book. The change isn't saved yet, so the book still says v7.
  3. The customer copies v7 back up, with a fresh 1 s timer.
  4. The change is saved and confirmed. The board shows v7 for the rest of that new timer: almost a full second.

Changing the book first closes that gap: any reader that misses after the change reads v8. In 24 changes each, both "change, then wipe" and "change, then write" (often called write-through) had no stale reads at all.

A slow copy

Zero in 24 isn't never. The right order still leaves a race: a reader that read the old row just before the change can write its copy just after the writer's wipe or write. With a copy that takes well under a millisecond, that window almost never opens.

So the lab opens it on purpose: a 50 ms pause between reading the database and writing Redis, like a garbage-collection pause or a slow network. To make collisions more likely, the timer is now 300 ms and the price changes about twice a second (on average every 0.5 s): 80 changes in 45 s.

Write strategy Changes followed by stale reads Stale window, p99 Longest Old copies refused
change, then wipe 10 of 80 322 ms 325 ms
change, then write 10 of 80 336 ms 346 ms
change, then write + guarded fill 0 of 80 0 0 97
tombstone + guarded fill 0 of 80 0 0 72

Both "safe" orders went stale after 12.5% of changes, each time for about one full timer (300 ms here). The most likely sequence, again from the code: a copy expires; a reader reads the old row and pauses; the writer changes the book and wipes the board, or writes the new price up; then the paused reader writes the old price over it with a fresh timer. Stale windows are counted over all changes, so the median is 0 here: 70 of the 80 had none. That's why the table shows the p99 (the 99th percentile, the window only 1% of changes exceeded).

A guarded copy

The fix is to make a late copy unable to overwrite newer data. Every copy in Redis carries its version, and the fill goes through a small Lua script that Redis runs in one step, so nothing can slip in between the check and the write. The lab's GUARDED_SET, in service/cache_logic.py:

local cur = redis.call('GET', KEYS[1])
if cur then
  local ok, obj = pcall(cjson.decode, cur)
  if ok and type(obj) == 'table' then
    local newest = obj['min_version'] or obj['version']
    if newest and tonumber(ARGV[2]) < tonumber(newest) then return 0 end   -- older: refuse
  end
end
redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[3])                        -- otherwise: write
return 1

It reads what's in the cache, takes the newest version there, and refuses the copy (return 0) if the copy is older. With "change, then write", the writer's v8 is already on the board when the late v7 arrives, so the script refuses it.

After a wipe, there's nothing to compare against. So instead of wiping, the writer leaves a note: a tombstone, a small value that says "version 8 or newer only" ({"min_version": 8} in the lab). Readers treat it as a miss, read the database and fill through the script; only a v8 or newer gets in.

Same slow copies, same 80 changes: 0 stale with either. The script refused 97 late copies in one run and 72 in the other. There are more refusals than the 10 stale changes before, because several readers miss at the same time and each tries to fill. Those were old prices that never got in.

The guarded fill isn't in the lab's unit tests (it's Lua, run inside Redis), so the measured runs above are its evidence. The lab's README lists what else shrinks the race if you can't store versions, none of them measured here: keep the fill short (no work between the read and the write), use short timers for data that changes, or delete twice, once after the update and again a moment later (the "delayed double delete"). Facebook's memcache uses leases for the same problem: only a reader holding a token issued on its miss may fill, and a delete cancels the tokens.

Copies far away: the edge

The same question, one layer further out. A CDN (content delivery network) is a set of caches near your users, called edges; your own servers behind them are the origin. In the café: other branches, each with its own copy of the page, and the main kitchen. Here, two Varnish caches (an open-source HTTP cache) on the laptop play two edges, edge1 and edge2, in front of the lab's service.

The origin tells the edges what to do with HTTP headers:

  • Cache-Control: no-store: don't keep a copy.
  • Cache-Control: max-age=5: any cache may keep this copy for 5 s: the edge's TTL.
  • ETag: "v42": a version tag. When its copy runs out, the edge asks "is it still v42?" (an If-None-Match request). If yes, the origin answers 304 Not Modified, with no body: it doesn't build or send the page, though it still reads the database to check the version. A full page is a 200.

The first run sends 1,000 requests a second through edge1 for 30 s, over 10,000 pages with a few popular ones and many rare ones (a Zipf distribution with s = 0.9, as in Chapter 14). Each setting gets its own URLs, so nothing is cached at the start.

The origin sends Reached the origin Full pages (200) Unchanged (304) p50 through the edge
no-store 100.0% 30,181 0 0.80 ms
max-age=1 + ETag 57.6% 6,427 10,971 0.65 ms
max-age=5 + ETag 39.3% 6,451 5,287 0.29 ms
max-age=5, no ETag 39.3% 11,738 0 0.30 ms
max-age=30 + ETag 21.4% 6,372 0 0.23 ms

A longer timer keeps more away from the origin, and each copy can be old for longer. 1 s kept 42% of requests at the edge, 5 s kept 61%, 30 s kept 79%. About 6,400 full pages reached the origin in every row with a tag: that's the number of different pages the 30 s run touched, and a page's first request misses whatever the timer. A longer run would push the 30 s share much lower.

The version tag saves the work, not the trip. At 5 s, with and without the tag, the same requests (each row with the same timer used the same random requests) and the same 39.3% reached the origin. With the tag, 5,287 of them were quick 304s, so the origin built 6,451 pages; without it, 11,738.

Try it · What reaches the main kitchenLab 08 · 05_cdn.py · Varnish edges in front of the service

1,000 requests a second for 30 s, a few popular pages and many rare ones (10,000 in all)

The origin sends: Cache-Control: public, max-age=5 · ETag: "v<version>"

answered by the branch: 18,133 “still the same?” → yes (304, no page sent): 5,287 full page prepared (200): 6,451
Reached the kitchen
39.3%
Pages prepared
6,451
“Still the same?” yes
5,287
p50 through the branch
0.29 ms

5 s: 39.3% reached the origin. 5,287 of those were 304s (45%), so the origin prepared 6,451 pages. Compare “5 s, no tag”.

A slow kitchen: one popular page, 200 ms to prepare (injected), timer 2 s, 200 requests a second for 20 s

wait after the copy runs out · modelled: a request every 5 ms, one 200 ms refetch100 ms200 ms0 ms100 ms200 ms300 mseveryone arriving during the refetch waits for it: 20 wait over 100 ms
Over 100 ms
237
p99
190 ms
Pages prepared
10
304s
0

The branch sent one refetch per expiry and made everyone else wait for it, so the origin prepared the page 10 times in 20 s, and 237 requests waited over 100 ms. The model gives 20 per refetch; real arrivals were random, about 24 per refetch here.

One Varnish cache stands in for a CDN branch; the origin is the lab's Python service. Each row is one recorded run; rows with the same timer used the same random requests. The strip is modelled arithmetic for one expiry, not a trace; the counts and p99s are recorded. A 304 skips preparing the page but still reads the database.

A slow kitchen

Now one popular page, and an origin that takes 200 ms to build it (a pause injected on purpose). The timer is 2 s, and 200 requests a second arrive for 20 s:

The origin sends Requests over 100 ms p99 Full pages 304s
max-age=2 237 190 ms 10 0
max-age=2 + ETag 27 39 ms 1 9
max-age=2, stale-while-revalidate=10 (no ETag) 27 27 ms 9 0

With the timer only, every expiry made a crowd wait. Varnish sent one refetch per expiry and parked everyone else on it (its own request coalescing, so the origin saw just 10 requests in 20 s). But everyone who arrived during those 200 ms waited for the page: 237 requests took over 100 ms.

With a version tag, the refetch was a quick "unchanged". One page built, 9 cheap 304s, 27 slow requests: most likely all from the very first fill, when the edge had nothing yet (the lab kept no per-request times to confirm it).

stale-while-revalidate=10 serves the old copy while refetching in the background. For up to 10 s past its timer, the edge answers at once with the expired copy and fetches a new one behind the scenes. That's showing old data on purpose, in exchange for speed. The page was still built 9 times, but nobody waited for those builds: 27 slow requests again, most likely the first fill.

The p99s of 39 and 27 ms are about the same: their 95% confidence intervals (the range the true p99 probably lies in, which the lab computes from the sorted latencies) are 3.3–99.9 ms and 2.7–89.3 ms, and overlap almost completely. The 190 ms is clearly different (185–197 ms).

Tell every branch

Last: after a page changes, tell every edge to drop its copy. That's a purge (here an HTTP PURGE request to each edge). The page has a 10 s timer; both edges hold a copy, the price changes, and the probe polls each edge every 5 ms until it serves the new version. 10 changes per row:

After the change edge1: old page for (median / longest) edge2: old page for (median / longest)
purge both edges 0.6 / 1.8 ms 0.6 / 2.1 ms
purge edge1 only (edge2's purge "lost") 1.1 / 2.2 ms 9,997 / 10,100 ms
no purge 10,002 / 10,004 ms 9,713 / 9,728 ms

A purge that arrives ends the old page at once: within about 2 ms. An edge the purge misses keeps the old page for its whole timer: here 10 s. So the worst case after a change isn't the purge time. It's the timer. A real CDN with hundreds of edges needs purges that are retried until every edge confirms.

Try it · Tell every branchLab 08 · 05_cdn.py · timer 10 s · 10 price changes per row
0 s2 s4 s6 s8 s10 sthe timerBranch 1purgedold page gone in 1.1 ms (longest 2.2 ms)Branch 2call lost10.0 s
Old page shown, median of 10 changes Longest
Branch 1, longest
2.2 ms
Branch 2, longest
10.10 s

Branch 1 was purged and served the new page within 2.2 ms. Branch 2's purge was skipped on purpose, as if the call was lost: it showed the old page for 10.0 s at the median, its whole 10 s timer.

Two Varnish caches on one laptop. The clock starts when the purges have been answered and stops when the branch first serves the new version, polled every 5 ms, so a purge's own travel time isn't in these numbers. A real CDN with hundreds of edges takes longer to reach all of them. Recorded values, 10 changes per row.

The lab's README adds a layer no purge reaches: browsers keep copies too. For pages that change, give browsers a short max-age and the CDN a longer s-maxage (the same as max-age, but for shared caches like CDNs only). It isn't measured here.

Caveats

  • One run per row, on a busy laptop. The counts of 24 and 80 changes are small: "0 of 24" means the race didn't happen in this run, not that it can't, which is the point of the slow-copy run.
  • The mechanisms are inferred, not traced. The lab records each read's send time and version, not which reader filled the cache when. The café timelines in the first widget are drawn from the code paths and settings, with the steps before the change stretched so you can see them; the windows of about one timer fit them.
  • The 50 ms pause and the 200 ms render are injected. They stand for real slowness (a pause, a slow network, a heavy template), chosen to make the effects visible in 45 or 20 s.
  • The purge numbers start after the purges were answered, on one laptop's network. They don't include how long a purge takes to reach the edges; a real CDN takes longer to reach all of them.
  • Edge2's 9.7 s without any purge is shorter than edge1's 10.0 s, most likely because its copy happened to be a little older when the price changed; the lab doesn't say. Both are "the rest of the timer".
  • Varnish serves expired copies for 10 s by default (its default_grace setting), even when the origin didn't ask for that. The lab's edge/default.vcl turns it off unless the origin sends stale-while-revalidate; without that, the first row of the slow-kitchen table would have looked like the third. Know your CDN's defaults before you trust a staleness bound.
  • Not covered: the "delayed double delete" and leases are described in the lab's README but not measured.

The checklist

  1. Measure staleness, don't guess it. Read in a loop while writing, record the version each read got, and compute how long after each confirmed change an old version was still served.
  2. Change the database first, then delete or overwrite the cached copy. Never the other way round: a reader in the gap puts the old row back with a fresh timer.
  3. Assume fills can be slow. A copy read before a change and written after it puts the old value back for a whole timer.
  4. Guard the fill with a version, checked and written in one step inside the cache, and leave a tombstone instead of a plain delete.
  5. Pick each edge timer as a trade: a longer one keeps more from the origin and lets each copy be old for longer.
  6. Send a version tag (ETag) so refetches of unchanged pages are cheap 304s, and use stale-while-revalidate only where showing old data for a while is acceptable.
  7. Purge every edge, retry until each confirms, and treat the timer as your worst case. Know your CDN's grace defaults, and remember that browsers can't be purged.

Practice: measure the old data, and guard the copy

Write the lab's logic: the stale-window measure from staleness.py (checked against the lab's own tests), a linear percentile, a cache fill with the lab's version guard and tombstone, the share of requests that reach the origin and the share answered with 304s, and the worst case after a lost purge. The tests replay the wipe-first race and the slow-copy race with and without the guard, and use the recorded counts: 57.6% to the origin at 1 s, 63% and 45% of origin requests answered with 304s at 1 s and 5 s.

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

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.With a 1 s cache timer and nothing done on writes, how long did readers see the old price after a change, at the median?

  2. 2.Why was deleting the cached copy before updating the database worse than doing nothing?

  3. 3.Updating first and then deleting gave 0 stale changes in 24. When did it go stale?

  4. 4.What does a guarded fill do, and why does it need a tombstone after a delete?

  5. 5.At a 5 s edge timer, what did a version tag (ETag) change?

  6. 6.One of two edges never got its purge, and the page has a 10 s timer. How long can that edge show the old page?

Check your understanding

Try each question before opening its answer.

Why is a cache with only a timer stale for about half the timer after a change, not the full timer?

The change lands at a random moment of the copy's life, so on average about half the timer is left when it happens. With a 1 s timer, every one of 24 changes was followed by old reads, for 542 ms at the median and 817 ms at most.

Deleting the cache entry before updating the database sounds careful. What goes wrong?

Between the delete and the commit, the database still holds the old row. A reader that misses then reads it and fills the cache with a fresh timer, so the old value outlives the change by almost a whole timer. In the lab: 981 ms at the median after 22 of 24 changes, against 542 ms with no delete at all, and 40.1% of reads stale against 23.3%.

If update-then-delete had no stale reads in 24 changes, why isn't it enough?

A reader can read the old row just before the update and write its copy just after the delete. It's rare when the fill takes under a millisecond, but a 50 ms pause made it happen after 10 of 80 changes, each for about one 300 ms timer. Writing the new value instead of deleting had the same race, with the same 10 of 80.

How does the guarded fill stop a late copy, and what does the tombstone add?

Every cached copy carries its version, and the fill runs as one script inside Redis that refuses a copy older than what's there. After a plain delete there's nothing to compare against, so the writer leaves a tombstone saying the oldest version allowed. With either, 0 of 80 changes went stale, and 97 or 72 late copies were refused.

An edge cache keeps pages for 5 s. What does adding a version tag change, and what doesn't it change?

It doesn't change how many requests reach the origin: 39.3% with or without it. It changes what they cost: an unchanged page is answered with a 304 and no body, so the origin built 6,451 pages instead of 11,738.

A popular page takes 200 ms to build and its edge copy expires every 2 s. What do users notice, and what are two fixes?

At each expiry, everyone arriving during the refetch waits for it: 237 requests over 100 ms and a p99 of 190 ms in the lab. A version tag makes the refetch a quick "unchanged", and stale-while-revalidate serves the old copy while refetching in the background. Both brought it to 27 slow requests, most likely the very first fill.

You purge both edges after every price change. One purge is lost. How long can that edge show the old price, and what bounds it?

Until its copy expires: the full 10 s timer in the lab (9,997 ms at the median), while the purged edge served the new page within about 2 ms. The timer is the worst case, plus any grace or stale-while-revalidate window, so retry purges until every edge confirms and pick the timer you can live with.

Next up: Chapter 16, replication lag and read-your-writes. A cache is a copy you keep on purpose and clear by hand. A database replica is a copy the database keeps for you, and it falls behind on its own schedule: after a write, how long can a reader see the old value there?

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.