A board-exam results page is read lakhs of times in an hour and changes once. Answering every read from the database repeats the same work lakhs of times.
A cache is a small, fast store that keeps copies of data that lives in a slower place, so that repeat reads skip the slow trip. It works because of locality: a few items, such as today's results or the most popular products, are read far more often than the rest, and an item read a moment ago is likely to be read again soon.
A cache is a copy and never the source of truth. If you throw it away, nothing is lost, because every entry can be rebuilt from the database. That one fact shapes every design choice in this chapter: a cache can be small, can be lost, and can be wrong for a while, and the design has to be comfortable with all three.
A read that finds its item in the cache is a hit. A read that does not is a miss, and it must go to the slower store. The hit ratio, the number the cdn chapter tracked at the edge, is hits divided by all reads. It is the number that tells you whether a cache is earning its place.
Where caches sit
Caches appear at every layer between a person and the data. Each layer answers some reads so that the layer behind it does not have to.
Layer
Shared by
What it saves
Main risk
Browser
One user
A trip over the network
The user sees an old copy
CDN edge
Everyone near that edge
A trip to the origin
A stale copy at many edges
In-process cache in an app server
One server
A network call to anything
Each server holds its own copy, and they can disagree
Distributed cache
Every app server
A trip to the database
One more service that can fail or lag
Database buffer pool
Every query
A disk read
Little control from your code
Browser
Shared byOne user
What it savesA trip over the network
Main riskThe user sees an old copy
CDN edge
Shared byEveryone near that edge
What it savesA trip to the origin
Main riskA stale copy at many edges
In-process cache in an app server
Shared byOne server
What it savesA network call to anything
Main riskEach server holds its own copy, and they can disagree
Distributed cache
Shared byEvery app server
What it savesA trip to the database
Main riskOne more service that can fail or lag
Database buffer pool
Shared byEvery query
What it savesA disk read
Main riskLittle control from your code
The cdn chapter covered the edge layer. This chapter is about the fourth row. A distributed cache is a separate service, run on several machines, that all app servers call over the network. Because it is shared, a value that one server loads helps all the others. An in-process cache has no such sharing: with twenty servers you hold twenty copies, you pay for twenty times the memory, and a change has to reach all twenty.
The price of the shared cache is a network call on every read, about as long as one round trip inside a data centre, which the latency ladder in the estimates chapter puts at about half a millisecond; the program below rounds it up to 1 ms to include a little work. That is still far faster than a database query that has to look at disk, and it is the trade a distributed cache makes.
What a hit ratio buys
The effect of a cache is easy to compute. A hit costs one cache lookup. A miss costs the cache lookup, which found nothing, plus the database query. The average read time is a weighted mix of the two. The program below assumes 1 ms for the cache and 20 ms for the database, and varies only the hit ratio.
python
CACHE_MS = 1.0# round trip plus lookup
DB_MS = 20.0# one query on the database
print("hit ratio average read database reads per 1000")
for hit in (0.0, 0.5, 0.8, 0.9, 0.95, 0.99):
# a miss pays for the cache lookup and then the database query
avg = hit * CACHE_MS + (1 - hit) * (CACHE_MS + DB_MS)
print(f"{hit:>9.0%} {avg:>8.1f} ms {1000 * (1 - hit):>12.0f}")
l1_effective.py: average read time for each hit ratio
It was run with Python 3.12.10. The arithmetic is exact, so it prints the same on every run.
text
hit ratio average read database reads per 10000% 21.0 ms 100050% 11.0 ms 50080% 5.0 ms 20090% 3.0 ms 10095% 2.0 ms 5099% 1.2 ms 10
Reading the table
Read the table from the bottom. A 99% hit ratio brings the average read to 1.2 ms, close to the cache's own speed. At 50% the average is still 11.0 ms, about half of the uncached 21.0 ms, because half of all reads still pay for both trips. Most of the gain arrives only when the hit ratio is high.
The last column matters as much as the middle one. At 90% the database sees 100 reads per thousand, a tenth of the traffic. At 99% it sees 10. A cache is therefore also a shield for the database, and that is why a database is often sized assuming the cache is there. If the hit ratio falls from 99% to 90% because the cache restarted or a key pattern changed, the database suddenly receives ten times the reads. Later lessons return to this cliff.
The hit ratio is not a property of the cache alone. It depends on the workload: how skewed the popularity is, how big the cache is compared with the data that is read, and how fast the data changes. The next lessons show where the hit ratio comes from and how it is lost.
With a 1 ms cache and a 20 ms database, what is the average read time at a 95% hit ratio?
2.0 ms, as in the table: 0.95 of reads cost 1 ms and the other 0.05 cost 21 ms.
Going from 95% to 99% saves only 0.8 ms more per read, but it cuts the database reads from 50 to 10 per thousand.
Why is a cache shared by all app servers usually better than one in-process cache per server?
A value loaded by one server is then available to all of them, so the hit ratio is higher for the same memory.
A change has to be made in one place, not twenty, though every read now needs a network call.
Your hit ratio drops from 99% to 90% overnight. How does the database load change?
It rises tenfold, from 10 to 100 reads per thousand requests.
A cache that is a shield for the database can become the reason the database is overwhelmed when it stops working.
Part 2 · Cache-aside and the other write patterns
Four ways to keep a cache and a database together
There are four common patterns, and they differ in who talks to the database and in what order writes happen.
In cache-aside, also called lazy loading, the application owns the logic. On a read it looks in the cache; on a miss it reads the database and puts the answer in the cache. On a write it updates the database and then removes the cached entry. The cache knows nothing about the database.
In read-through, the application asks only the cache. The cache itself is configured with a loader that fetches the value from the database on a miss, so the loading code lives in one place instead of every caller.
In write-through, every write goes to the cache and the database together, and the caller is told it succeeded only when both have it. The cache is never behind the database.
In write-behind, also called write-back, a write goes only to the cache, which confirms at once and copies the value to the database a little later, often in batches.
Pattern
Read path
Write path
Strength
Risk
Cache-aside
App checks cache, loads on miss
Write the database, delete the entry
Simple, and a dead cache only slows reads
Misses are slow, and stale entries are possible
Read-through
Cache loads on miss
Not defined by the pattern
Loading logic in one place
Needs a cache that supports loaders
Write-through
Hits are always fresh
Cache and database together
Reads never see old data
Every write is as slow as the database
Write-behind
Hits are fresh
Cache first, database later
Fast writes, fewer database writes
Writes can be lost if the cache dies
Cache-aside
Read pathApp checks cache, loads on miss
Write pathWrite the database, delete the entry
StrengthSimple, and a dead cache only slows reads
RiskMisses are slow, and stale entries are possible
Read-through
Read pathCache loads on miss
Write pathNot defined by the pattern
StrengthLoading logic in one place
RiskNeeds a cache that supports loaders
Write-through
Read pathHits are always fresh
Write pathCache and database together
StrengthReads never see old data
RiskEvery write is as slow as the database
Write-behind
Read pathHits are fresh
Write pathCache first, database later
StrengthFast writes, fewer database writes
RiskWrites can be lost if the cache dies
Cache-aside is the most common because it works with any cache and any database, and because the system keeps working if the cache is down. The rest of this chapter assumes it unless it says otherwise.
Animated sceneCache-aside: a miss, then a hit0:21
Watch for the first read: the cache is empty, so it costs a database trip
Read it as steps
The first read pays for a database trip and fills the cache. The next read is answered from memory.
The scene shows the two paths. The first read for an item misses, goes to the database, fills the cache and costs about 21 ms in the numbers of the last lesson. The next read for the same item costs 1 ms and never touches the database. The cache does not need to be told anything: it fills itself from the reads.
Cache-aside in code
The program below builds a database of 1 lakh products in SQLite and a dictionary standing in for the cache. It reads 10,000 products twice, first with every product equally likely, then with popularity that falls off as one over the rank, so product 0 is read far more than product 99,999. The cache is unbounded here. Eviction is the next lesson.
python
import random
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE product (id INTEGER PRIMARY KEY, name TEXT)")
db.executemany("INSERT INTO product VALUES (?, ?)",
[(i, f"item-{i}") for i in range(100_000)])
cache, stats = {}, {"hit": 0, "miss": 0}
def get_product(pid):
if pid in cache: # 1. look in the cache
stats["hit"] += 1return cache[pid]
stats["miss"] += 1# 2. miss: ask the database
row = db.execute("SELECT name FROM product WHERE id = ?",
(pid,)).fetchone()
cache[pid] = row[0] # 3. remember the answerreturn row[0]
l2_aside.py, part 1: the cache-aside read
python
def run(label, picker):
cache.clear(); stats.update(hit=0, miss=0)
for _ in range(10_000):
get_product(picker())
h, m = stats["hit"], stats["miss"]
ratio = h / 10_000
print(f"{label:<8} hits {h:>5} misses {m:>5} "
f"hit ratio {ratio:.1%}")
rng = random.Random(7)
run("uniform", lambda: rng.randrange(100_000))
weights = [1 / (rank + 1) for rank in range(100_000)]
run("skewed", lambda: rng.choices(range(100_000), weights)[0])
l2_aside.py, part 2: two workloads
It was run with Python 3.12.10. The random generator is seeded, so the counts repeat exactly.
text
uniform hits 468 misses 9532 hit ratio 4.7%
skewed hits 5735 misses 4265 hit ratio 57.4%
The same cache and the same code give a 4.7% hit ratio on one workload and 57.4% on the other. With uniform reads, almost every read asks for a product that has not been read before, so almost every read is a miss. With skewed reads, the popular products are read again and again, and a miss happens only the first time. A cache pays off when some items are read much more than others. It does not help a workload that never repeats itself.
The write side of cache-aside is the delete. After updating the database, the code removes the cached entry, and the next reader fills it with the new value. Deleting is safer than writing the new value into the cache, for a reason that the invalidation lesson shows with a run.
Write-behind and its risk
Write-behind is the pattern with the clearest danger. The cache is the only place that holds a write until the flush happens, so a lost cache node loses acknowledged writes. The next program keeps a dictionary for the database and one for the cache's pending writes.
python
store, buffer = {}, {} # database, pending writesdef put_write_behind(key, value):
buffer[key] = value # acknowledged to the caller at oncedef flush():
store.update(buffer) # a background job, every few seconds
buffer.clear()
put_write_behind("cart:1", "2 items")
put_write_behind("cart:2", "5 items")
flush()
put_write_behind("cart:1", "3 items") # newer value, not flushed yet
print("database: ", store)
print("pending in cache:", buffer)
buffer.clear() # the cache node dies
print("after the crash: ", store)
l2_behind.py: one flush, one new write, then a crash
text
database: {'cart:1': '2 items', 'cart:2': '5 items'}
pending in cache: {'cart:1': '3 items'}
after the crash: {'cart:1': '2 items', 'cart:2': '5 items'}
The first two writes were flushed, so they are safe. The third write, an update of the first cart, was acknowledged to the caller but was still pending when the cache node died. After the crash the database holds the old value and nothing records that a newer one ever existed. The caller was told it worked.
Write-behind is a fair choice when losing the last few seconds of writes is acceptable and the load on the database matters more: view counters, last-seen times, game scores. It is the wrong choice for orders, payments and anything a person would call data. When the cache must not lose writes, use write-through, or write the database first as cache-aside does.
Which of the four patterns still works if the cache goes down completely, and why?
Cache-aside: the application talks to the database itself, so reads become slower but nothing is lost.
Write-behind would lose its pending writes, and read-through and write-through depend on the cache sitting in front of the database.
In the run, one workload gave a 4.7% hit ratio and the other 57.4% with the same code. What explains the gap?
The skewed workload reads the same popular products again and again, so most reads find them in the cache.
The uniform workload mostly asks for products it has not seen before, so each read is a first-time miss.
An update is acknowledged by a write-behind cache and the node then crashes before the flush. What does the database hold?
The previous value. The run above shows cart 1 back at 2 items after the crash.
This is why write-behind suits counters and similar data, not orders.
Part 3 · Eviction: LRU, LFU and TTL
Choosing what to throw away
A cache has less memory than the data behind it, so when it is full and a new item arrives, something must leave. The rule that picks the victim is the eviction policy. A good policy keeps the items most likely to be read next. Nobody knows the future, so every policy bets on a pattern from the past.
Least recently used (LRU) bets that an item used a moment ago will be used again soon. It evicts the item whose last use is the oldest. Least frequently used (LFU) bets on popularity: it counts uses and evicts the item with the fewest. Random eviction picks any item and needs no bookkeeping at all.
Time to live (TTL) is a different idea, because it is about age and not about space. Each entry is stored with an expiry time and disappears when it comes, whether or not the cache is full. A TTL limits how stale a copy can be, and it also removes entries that nobody reads. Most caches use a TTL together with an eviction policy.
Redis, a widely used in-memory store, names its policies in this way. Its documentation lists allkeys-lru, allkeys-lfu and allkeys-random, the volatile- versions that only consider keys that have a TTL, volatile-ttl which evicts the keys closest to expiry, and noeviction, which keeps every key and returns an error to commands that would add data, while reads keep working. Redis 8.6 added allkeys-lrm and volatile-lrm, which evict the key least recently written rather than read. Two details catch people out. The default policy in the shipped configuration file is noeviction, so a Redis used as a cache must have a policy set or it starts refusing writes when full. And the volatile- policies behave like noeviction when no key has a TTL. The same page says that its LRU and LFU are approximations: Redis samples a small number of keys, maxmemory-samples with a default of 5, and evicts the best candidate among them, which avoids the memory cost of tracking exact order. It also says that allkeys-lru is a good default when a subset of keys is read far more often than the rest.
Three policies on the same traces
The next program implements LRU with an ordered dictionary, LFU with a use counter per key, and random eviction. LFU breaks ties in favour of evicting the key that was used longest ago.
python
import random
from collections import OrderedDict
def lru(trace, cap):
cache, hits = OrderedDict(), 0for k in trace:
if k in cache:
hits += 1
cache.move_to_end(k) # most recent goes lastelse:
cache[k] = Trueif len(cache) > cap:
cache.popitem(last=False) # evict the oldest usereturn hits / len(trace)
def lfu(trace, cap):
count, hits = OrderedDict(), 0for k in trace:
if k in count:
hits += 1
count[k] += 1
count.move_to_end(k)
else:
count[k] = 1if len(count) > cap:
# fewest uses; ties go to the longest-unused key
victim = min(count, key=count.get)
del count[victim]
return hits / len(trace)
l3_policies.py, part 1: LRU and LFU
python
def rand(trace, cap, seed=1):
r, cache, hits = random.Random(seed), [], 0for k in trace:
if k in cache:
hits += 1else:
if len(cache) >= cap:
cache.pop(r.randrange(len(cache)))
cache.append(k)
return hits / len(trace)
l3_policies.py, part 2: random eviction
The runner builds three traces of requests over 5,000 keys with popularity falling off as one over the rank. The steady trace has 30,000 requests. The scan trace inserts a one-time read of 400 new keys in the middle, like a report that walks a table. The shift trace has 15,000 requests, and then another 15,000 after the popular keys change to a different set. Every cache holds 200 keys.
python
import random
from l3_policies import lru, lfu, rand
rng = random.Random(11)
keys = range(5000)
weights = [1 / (i + 1) for i in keys] # skewed popularitydef draw(n, offset=0):
picks = rng.choices(keys, weights, k=n)
return [(k + offset) % 5000for k in picks]
steady = draw(30_000)
scan = draw(10_000) + list(range(10_000, 10_400)) + draw(10_000)
shift = draw(15_000) + draw(15_000, offset=2500) # hot keys change
print(f"{'trace':<8}{'LRU':>8}{'LFU':>8}{'random':>8} (capacity 200)")
for name, t in (("steady", steady), ("scan", scan), ("shift", shift)):
print(f"{name:<8}{lru(t, 200):>8.1%}{lfu(t, 200):>8.1%}"
f"{rand(t, 200):>8.1%}")
l3_run.py: three traces, three policies
It was run with Python 3.12.10, with a fixed seed, so the numbers repeat.
On the steady trace, LFU wins with 60.7%, LRU gets 53.0% and random 48.0%. When popularity is stable, counting uses finds the truly popular keys and keeps them. LRU is only a proxy, because a key that was used once a moment ago looks as important as one used a thousand times.
The scan trace is where LRU is expected to suffer, but here it barely shows: LRU falls from 53.0% to 51.3% and LFU from 60.7% to 58.2%. The traces are different random draws of different length, so part of each fall is just extra first-time misses. A one-time scan can make LRU treat 400 keys that will never be read again as the freshest data in the cache, and with a longer scan or a smaller cache the damage would be larger.
Where LFU fails
The shift trace is where LFU fails. Its hit ratio drops to 36.0% while LRU holds at 52.7%. The old popular keys have large counts, and nothing ever reduces them, so they stay in the cache long after nobody asks for them, while the new popular keys start with a count of one and are the first to be evicted. This is why real LFU implementations let counts decay with time. The Redis documentation describes a probabilistic counter with a decay period, one minute by default, so that a key that was once popular does not stay forever.
These traces are made up, and your workload will differ, so treat the numbers as an illustration of three behaviours and not as a ranking. The method carries over: take a log of real reads, replay it against each policy at the cache size you can afford, and compare the hit ratios.
Expiry is not eviction
A TTL removes an entry because it is old. Eviction removes an entry because memory is full. A cache with a short TTL may never need to evict, and a cache with no TTL relies on eviction alone.
On a steady, skewed workload, which policy did best in the run, and by how much over LRU?
LFU, with 60.7% against 53.0% for LRU, a gain of 7.7 points.
Random eviction was lowest at 48.0%.
Why did LFU fall to 36.0% when the popular keys changed?
The old keys kept large use counts that never decayed, so they stayed in the cache.
The new popular keys started with a count of one and were evicted first, before they could build up a count.
What does a TTL do that an eviction policy does not?
It removes an entry when it gets old, even if the cache is not full, which bounds how stale a copy can be.
Eviction only acts when memory runs out.
Part 4 · Sharding and replicating a cache
Splitting the keys over several nodes
One cache machine has limited memory and limited network capacity. To hold more data and serve more reads, the keys are split over several cache nodes. This is sharding, the same idea as partitioning a database, and the key-value store chapter explained how consistent hashing keeps most keys in place when nodes change.
As in the key-value store chapter, the keys sit on a consistent hash ring of virtual nodes. The logic can live in the client library, in a proxy in front of the cache, or in the cache cluster itself. Here it lives in the client, which keeps the sketch small.
python
import bisect
import hashlib
def h(text):
return int(hashlib.md5(text.encode()).hexdigest(), 16)
class Ring:
def __init__(self, nodes, vnodes=100):
self.points = sorted((h(f"{n}#{i}"), n)
for n in nodes for i in range(vnodes))
self.hashes = [p[0] for p inself.points]
def owners(self, key, n=1):
"""The first n distinct nodes clockwise from the key."""
i = bisect.bisect(self.hashes, h(key))
found = []
while len(found) < n:
node = self.points[i % len(self.points)][1]
if node notin found:
found.append(node)
i += 1return found
def owner(self, key):
returnself.owners(key)[0]
l4_ring.py: a ring with 100 virtual nodes per node
The method owners returns the first few distinct nodes clockwise from a key, not only the first. That list is what a replica set is built from, and the next page uses it.
Adding a node moves only the keys that fall in the new node's arcs. The program at the end of this lesson counts how many of 5,000 keys change owner when a fourth node joins a ring of three. The ideal is one quarter, which is the share the new node should own.
Hot keys
Hashing spreads keys evenly, but not requests. A hot key is a key that receives so many reads that the node holding it becomes the bottleneck, however well the other keys are spread. A viral post, a flash-sale product or a celebrity profile can send a large fraction of all traffic to one key.
The program below sends 20,000 reads with popularity proportional to one over the rank across 5,000 users, to three cache nodes. It prints each node's share of the reads. It then keeps the top key, and later the top ten keys, on all three nodes and picks a random replica for each read.
python
import random
from collections import Counter
from l4_ring import Ring
rng = random.Random(5)
keys = [f"user:{i}"for i in range(5000)]
weights = [1 / (i + 1) for i in range(5000)]
trace = rng.choices(keys, weights, k=20_000)
ring = Ring(["cache-a", "cache-b", "cache-c"])
top = [k for k, _ in Counter(trace).most_common(10)]
def show(label, hot):
def owner_of(key):
if key in hot: # hot keys live on all 3 nodesreturn rng.choice(ring.owners(key, 3))
return ring.owner(key)
load = Counter(owner_of(k) for k in trace)
cells = " ".join(f"{n[-1]} {c / len(trace):5.1%}"for n, c in sorted(load.items()))
print(f"{label:<20}{cells}")
share = Counter(trace)[top[0]] / len(trace)
l4_run.py, part 1: the workload and the load per node
python
print(f"hottest key {top[0]} takes {share:.1%} of reads")
print(f"{'':<20}node load")
show("one copy per key", set())
show("top 1 on 3 nodes", set(top[:1]))
show("top 10 on 3 nodes", set(top))
bigger = Ring(["cache-a", "cache-b", "cache-c", "cache-d"])
moved = sum(ring.owner(k) != bigger.owner(k) for k in keys)
print(f"adding cache-d moved {moved / len(keys):.1%} of the keys")
l4_run.py, part 2: the hottest key and a new node
It was run with Python 3.12.10, with a fixed seed.
text
hottest key user:0 takes 10.9% of reads
node load
one copy per key a 40.9% b 34.5% c 24.7%
top 1 on 3 nodes a 44.6% b 27.2% c 28.2%
top 10 on 3 nodes a 36.8% b 29.3% c 33.9%
adding cache-d moved 27.2% of the keys
The hottest key, user:0, takes 10.9% of all reads by itself, so whichever node owns it carries a large extra load. With one copy of each key the nodes carry 40.9%, 34.5% and 24.7%, which is far from an even third each. Replicating only the top key made the busiest node busier. user:0 lived on cache-b, so spreading it took load off b and handed a third of it to a, which rose from 40.9% to 44.6%. Node a was busy because it holds other heavy keys (in this ring, user:1, user:3 and user:4 among them), and replicating user:0 did not move them. Spreading the top ten keys over all three nodes brought the loads to 36.8%, 29.3% and 33.9%. The lesson is to look at the load per node, not only at the single hottest key.
Adding a fourth node moved 27.2% of the keys, close to the ideal quarter. That is the benefit of consistent hashing: the other 72.8% stayed where they were and kept their cached entries.
There are three ways to deal with a hot key. Replicate it on several nodes and read from a random replica, as the run did, which costs memory and makes an update touch every copy. Keep a very small, short-lived copy in each app server's own memory in front of the shared cache. Or split the key itself into several keys, which is how a hot counter is handled. All three need a way to find the hot keys, which usually means counting reads by key over a sample of traffic.
When a node fails
A node that dies takes its keys with it. On a ring of three, a third of the cache is gone, those reads become misses, and the database receives all of them at once. The database was sized for the hit ratio of the whole cache, so the loss of one node can become an overload.
Two measures help. Keep a replica of each shard on another node, so that a failure moves reads to a copy that is already warm. Or use many small nodes, so that one failure removes a small share of the keys and the database sees a small bump. The cost of replication is memory and write traffic. The cost of many small nodes is more machines to run. The stampede lesson covers what happens at the database when a lot of entries are missing together.
Why does consistent hashing not fix a hot key?
It spreads different keys evenly, but a single key still lands on one node, so that node carries all of its reads.
In the run, one key alone took 10.9% of the reads.
In the run, replicating only user:0 raised the busiest node from 40.9% to 44.6%. Why?
user:0 lived on cache-b, so spreading it moved part of its reads onto cache-a, which was already the busiest node.
Cache-a was busy because of other heavy keys, which stayed where they were. Replicating the top ten keys brought the three nodes to 36.8%, 29.3% and 33.9%.
What happened when a fourth node joined the ring of three?
27.2% of the keys changed owner, close to the ideal quarter.
The other keys stayed in their nodes, so their cached entries were not lost.
Part 5 · Invalidation and stale data
Three ways to keep the copy right
When the database changes, the cached copy is wrong. There are three ways to deal with that. A TTL waits: the entry is removed after a fixed time, so a copy is never stale for longer than that time. An invalidation removes the entry when a write happens. An update writes the new value into the cache at the same time as the database.
The TTL is the safety net and costs nothing, but it allows staleness for its whole length. Invalidation keeps staleness short, but the delete has to be made by the writer, in every cache that holds the entry. Updating the cache looks like the best idea and is the riskiest, because two writers can reach the cache in a different order from the order in which they reached the database. That ordering problem is what the rest of this lesson is about, and it also affects the delete.
With cache-aside the writer deletes the entry, and the next reader fills it. The reader and the writer are two separate processes, and nothing makes the reader's steps and the writer's steps happen in a fixed order.
A race that leaves old data
Take a price of 100. A reader misses and reads 100 from the database. Before the reader writes that to the cache, a writer changes the price to 120 and deletes the cache entry, which is not there. The reader then stores the 100 it read earlier. The database says 120 and the cache says 100.
python
db = {"price": 100}
cache = {}
def read_db(): # reader A: miss, read the databasereturn db["price"]
def writer(): # writer B: update, then invalidate
db["price"] = 120
cache.pop("price", None)
old = read_db() # A reads 100
writer() # B writes 120 and deletes the key
cache["price"] = old # A sets the value it read earlier
print("database:", db["price"])
print("cache: ", cache["price"])
print("later reads see", cache.get("price"), "until the entry expires")
l5_race.py: the interleaving, written out in order
It was run with Python 3.12.10. The interleaving is forced by the order of the lines, which is the same order a slow reader could produce in a real system.
text
database: 120
cache: 100
later reads see 100 until the entry expires
The cache now holds a value that the database no longer has, and nothing will correct it except the entry expiring. The delete did its job, but it ran before the reader's late write. The same thing happens if you update the cache instead of deleting: whichever write reaches the cache last wins, whether or not it is the newest.
The cause is that the reader's write is based on a read that happened before the change. The fix is to let the cache refuse such a write. Give every row in the database a version number that rises with each update. The reader brings the version it read to the cache, and the cache accepts the value only if no invalidation has passed since. To make that work, an invalidation must leave a marker, not just remove the entry.
python
db = {"price": (100, 1)} # (value, version)
cache = {} # key -> (value, version)
floor = {} # key -> lowest version alloweddef set_if_fresh(key, value, version):
if version < floor.get(key, 0):
returnFalse# an invalidation passed this reader
cache[key] = (value, version)
returnTruedef invalidate(key, new_version):
cache.pop(key, None)
floor[key] = new_version # leave a marker, not just a gap
value, version = db["price"] # A reads (100, 1)
db["price"] = (120, 2) # B writes version 2 ...
invalidate("price", 2) # ... and invalidates
print("A sets its copy:", set_if_fresh("price", value, version))
print("cache:", cache)
value, version = db["price"] # the next reader misses, reads v2
print("next reader sets:", set_if_fresh("price", value, version))
print("cache:", cache)
l5_fix.py: versions and a marker left by the delete
text
A sets its copy: False
cache: {}
next reader sets: True
cache: {'price': (120, 2)}
The late write of version 1 is refused because the marker says that nothing below version 2 may be stored. The next reader loads version 2 and is accepted. The cost is that the marker takes memory until it can be dropped, which is safe after a time longer than any reader could take.
This is the same idea as the lease mechanism in the paper about Facebook's memcache deployment, published at NSDI in 2013. There, the cache gives a client a 64-bit token when it misses, bound to the key, and the client must present the token to store a value. A delete of the key invalidates the token, so a late store is refused. The authors note that this is similar to load-link and store-conditional in processors. Whatever the mechanism, the rule is the same: a write into the cache must prove that it is not older than a change that has already happened.
What to do in practice
Choose by the cost of staleness. For data that may be a little old, such as a product description or a follower count, delete on write and keep a TTL as a backstop. For data that must not be wrong, such as a seat count in a booking, do not cache it, or read it from the database inside the transaction.
Keep the TTL on every entry even when you invalidate. Invalidation can fail: a message is lost, a node is unreachable, a bug skips a code path. The TTL turns a permanent error into a temporary one. When several caches in different regions hold the same data, publish the change as an event that each region applies, which is what publish-subscribe messaging is for, covered in a later chapter.
Why can a cache-aside delete still leave stale data?
A reader that read the old value before the write can store it after the delete, so the old value returns.
The delete ran at the right time, but the reader's write was based on older data.
In the fix, why must the delete leave a marker and not just remove the entry?
Without a marker, an empty cache accepts any value, including the late one with version 1.
With the marker, the cache knows that nothing older than version 2 may be stored.
Why keep a TTL on entries that you also invalidate?
Invalidation can fail, and the TTL limits how long a missed invalidation can leave a stale value.
Part 6 · Cache stampedes
When many readers miss together
A popular entry expires. In the same instant, fifty requests arrive for it. Each finds the cache empty and each goes to the database, which was built for a trickle of misses and now receives fifty identical expensive queries. This is a cache stampede, also called a thundering herd. It happens when a hot entry expires, when many entries expire together because they were all given the same TTL, and when a cache node restarts empty.
It is dangerous because it feeds itself. The database slows down under the burst, so the loads take longer, so more requests pile up behind them, and the entries that were being loaded are still missing when the next requests arrive.
Animated sceneA stampede, then coalescing0:23
Watch for the database: a popular entry has expired and fifty readers arrive together
Read it as steps
Fifty requests find the entry missing at once. Without coalescing all fifty query the database; with it, one does.
The scene compares the two outcomes. Without any protection all fifty requests query the database. With coalescing the first one loads and the rest wait for its answer, so the database does the work once.
Coalescing the loads
Single-flight, the request coalescing an edge uses in the cdn chapter, makes sure that only one load for a key runs at a time. The first request to miss becomes the leader and loads the value. Every other request for the same key waits for the leader's result and then reads it from the cache. The program below runs 50 threads against a database call that takes 0.2 s and counts how many times the database is called.
python
import threading
import time
loads = 0
lock = threading.Lock()
cache = {}
inflight = {} # key -> Event, for single-flightdef slow_database(key):
global loads
with lock:
loads += 1
time.sleep(0.2) # an expensive queryreturn f"value-of-{key}"def get_naive(key):
if key notin cache:
cache[key] = slow_database(key)
return cache[key]
l6_herd.py, part 1: the slow database and the naive reader
python
def get_single_flight(key):
while key notin cache:
with lock:
ev = inflight.get(key)
leader = ev isNoneif leader:
ev = inflight[key] = threading.Event()
if leader:
cache[key] = slow_database(key)
ev.set()
del inflight[key]
else:
ev.wait() # wait for the leader's answerreturn cache[key]
l6_herd.py, part 2: single-flight
python
def burst(getter):
global loads
loads = 0
cache.clear()
start = threading.Barrier(50)
def client():
start.wait() # all 50 arrive together
getter("home-page")
threads = [threading.Thread(target=client) for _ in range(50)]
t0 = time.perf_counter()
for t in threads: t.start()
for t in threads: t.join()
ms = (time.perf_counter() - t0) * 1000
print(f"{getter.__name__:<18} database loads {loads:>2} "
f"{ms:.0f} ms")
burst(get_naive)
burst(get_single_flight)
l6_herd.py, part 3: fifty threads arrive together
It was run with Python 3.12.10. The times vary a little from run to run, on this machine; the counts do not.
text
get_naive database loads 50208 ms
get_single_flight database loads 1207 ms
The naive reader called the database 50 times and the single-flight reader called it once. The elapsed time is the same, about 0.2 s, because the waiting readers still have to wait for the one load. What changed is the work done by the database: one fiftieth of it. In a real system the loads on a struggling database also take longer, so the saving is larger than the arithmetic shows.
The Facebook paper describes a leased variant of the same idea. Its servers hand out a token for a key at most once every 10 seconds by default, and other readers in that period are told to wait briefly and retry. The authors report that for a set of keys prone to thundering herds, the peak database query rate was 17,000 per second without leases and 1,300 per second with them.
The XFetch rule
Single-flight works inside one process. With many app servers, each one can still send a leader to the database at the same moment. Another approach is to refresh early. In the paper by Vattani and others on cache stampede prevention, the algorithm called XFetch makes each reader decide, randomly, whether to recompute a little before the entry expires. A reader recomputes if the current time minus delta times beta times the natural log of a random number between 0 and 1 is at or past the expiry. Here delta is how long the last recomputation took and beta is a tuning factor that defaults to 1. The log of a random number is negative, so the sum is the current time plus a random head start, which is longer for slow recomputations and for larger beta.
XFetch in a model
The program below simulates readers arriving at 100 per second around an expiry, with a recomputation that takes 0.2 s. It compares a plain TTL, where requests after the expiry each go to the database, with XFetch, where a reader may refresh early. Each setting is run over 200 seeds and averaged.
python
import math
import random
TTL, DELTA, RATE = 10.0, 0.2, 100# seconds, seconds, requests/sdef one_expiry(beta, seed):
r = random.Random(seed)
expiry, recomputes, slow = 10.0, [], 0
pending = None# (finish time, new expiry)
t = 9.0while t < 11.0:
if pending and t >= pending[0]:
expiry, pending = pending[1], None
gap = -DELTA * beta * math.log(1 - r.random())
if t >= expiry: # real miss: caller waits
slow += 1
recomputes.append(t)
pending = pending or (t + DELTA, t + DELTA + TTL)
elif beta and t + gap >= expiry:
recomputes.append(t) # early refresh
pending = pending or (t + DELTA, t + DELTA + TTL)
t += 1 / RATE
return len(recomputes), slow
for beta in (0, 1):
runs = [one_expiry(beta, s) for s in range(200)]
n = sum(a for a, _ in runs) / 200
s = sum(b for _, b in runs) / 200
label = "plain TTL"if beta == 0else"XFetch beta=1"
print(f"{label:<14} recomputes {n:5.2f} waited {s:5.2f}")
l6_xfetch.py: a model of requests around one expiry
This is a model in simulated time, not a measurement of a real cache. With a plain TTL, 21 requests find the entry expired and each recomputes it. With XFetch the average is 3.19 recomputations, and the number of callers that actually waited on a recomputation was close to zero. The early refreshes happen while the old value is still valid, so no caller waits for them.
Other defences, and a missing key
Two more habits reduce stampedes. Add a small random amount to each TTL, so that entries loaded together do not expire together. And after a cache restart, warm the cache or let traffic return gradually, so that the database is not asked to serve everything at once.
A related problem is a read for a key that does not exist, such as a deleted product or an id typed by hand. The database returns nothing, cache-aside stores nothing, and every such read misses and reaches the database, which a buggy client or an attacker can repeat endlessly. The usual fix is negative caching: store a short-lived "not found" marker for the key, with a TTL of seconds rather than minutes, so that a later insert of that key is not hidden for long.
Term
Meaning
Hit ratio
Hits divided by all reads
Cache-aside
The application loads on a miss and deletes on a write
Write-behind
Writes go to the cache first and reach the database later
LRU, LFU
Evict the least recently, or the least frequently, used entry
Hot key
A key that receives so many reads that its node becomes the limit
Stampede
Many readers miss at once and all query the database
Single-flight
Only one load per key runs, and the others wait for it
What does single-flight change in the run, and what does it leave unchanged?
It cut the database calls from 50 to 1.
The elapsed time stayed about 0.2 s, because the other 49 readers still wait for the one load.
Why does XFetch use the time the last recomputation took?
A slow recomputation needs a longer head start, so the random early window grows with delta.
A quick one needs little, so the cache does not refresh much earlier than necessary.
Thirty app servers each use single-flight in their own memory. A hot entry expires and all thirty receive requests for it in the same instant. How many database loads can happen, and what would reduce them?
Up to thirty, one leader per server, because single-flight only coalesces inside one process.
Early refresh such as XFetch, or a lease handed out by the cache itself, so that one load serves every server.