Algorithms · Huge scale
Cache stampedes and leases
How Facebook stops a stampede on its cache. A popular item expires and a thousand servers rush the database at once. A tiny “I’ve got it” token calms the herd.
The problem
Picture one hugely popular piece of data, like a post everyone is reading and commenting on. Facebook keeps a copy in a fast cache (memcached) so its web servers rarely bother the database.
Then someone writes to it, and the cached copy is thrown out. Now hundreds of web servers ask for the key in the same instant, and every one of them misses. The 2013 paper Scaling Memcache at Facebook calls this a thundering herd.
The obvious way
The simple rule is: if the cache misses, ask the database yourself, then put the answer in the cache. That is fine for one server. But if 500 servers miss in the same instant, all 500 ask the database the same question, and all 500 compute the same answer. The database is hit hardest at the exact moment the cache was supposed to protect it.
The clever idea
Think of a coat-check ticket. When the cache misses, memcached hands the first asker a lease, a token that says "you're the one who goes to the database." Everyone else is told "someone's already fetching it, wait a moment and ask again."
Per the paper, by default each memcached server hands out a token only once every 10 seconds per key. The waiting clients retry shortly after, and by then the lease holder has usually filled the cache within a few milliseconds. The same lease token also fixes a second problem the paper names, stale sets.
How the code does it
Both runs use the same function. The only difference is the lease check. With use_leases=False every server walks into that branch, adds one to load[0], and queries the database. You get 500 queries, all in millisecond 0, which is the spike in the first timeline.
With leases, only the first server enters that branch. The other 499 skip to the sleep and retry, jump forward 5 ms, and find the cache already filled when the loop condition is checked again. So the charts show one query instead of 500, and the price is a small average wait.
Trade-offs
Leases trade a little latency for a lot of safety: clients that are told to wait pay a short delay, and they must be written to retry. Skip them for keys that are rarely read, because a stampede needs a crowd. And the simulation's 3 ms and 5 ms are made up for illustration, not Facebook's measurements.
Where else you'll see it
The same idea of letting one caller do the work while the others wait for its result shows up under names like request coalescing or "single-flight" in many caches and web servers.
With leases, 500 servers miss at the same instant. How many database queries does the simulation run?
- 1
- 499
- 500
Show the answer
1. Only the first server gets the token and queries the database. The other 499 wait, retry, and find the cache filled.
- Change SERVERS to 2000
- Set DB_MS to 8 and compare waits
- Set RETRY_MS to 1
The code
Python, with what each line means beside it. It compares the clever way with every server that misses the cache asks the database itself.
SERVERS = 500 # web servers all asking for the same key at ms 0Say 500 servers ask at onceDB_MS = 3 # made-up: ms for the database to answer and fill the cacheThe database takes 3 ms to answerRETRY_MS = 5 # made-up: how long a told-to-wait server sleepsWaiting servers sleep 5 ms, then retry def stampede(use_leases):Simulate the stampede, with or without leases filled_at = None # moment the cache gets the value backNo value is back in the cache yet token_given = FalseNobody holds the lease token yet load = [0] * 10 # database queries started in each msCount database queries per millisecond waited = 0Total waiting time starts at zero for server in range(SERVERS):Go through each web server t = 0 # every server arrives at ms 0Everyone arrives at millisecond zero while filled_at is None or t < filled_at:Keep trying while the cache is empty if not use_leases or not token_given:Query only if no leases or token free token_given = TrueMark the token as handed out load[t] += 1 # this server asks the databaseRecord one database query now if filled_at is None:If this is the first query filled_at = t + DB_MSCache will be filled 3 ms later breakDone: stop trying t += RETRY_MS # told to wait: sleep, then retryOtherwise sleep, then try again later waited += RETRY_MSAdd that sleeping time to the total return sum(load), load, waited / SERVERSReturn queries, per-ms load, average wait plain = stampede(False)Run the obvious wayleased = stampede(True)Run the lease wayshow([plain[0], leased[0]], "DB queries: no leases vs leases")Chart total database queriesshow(plain[1], "Without leases: DB load per ms")Chart the load per millisecond, no leasesshow(leased[1], "With leases: DB load per ms")Chart the load per millisecond, with leasesprint("avg extra wait (ms):", plain[2], "vs", round(leased[2], 2))Print the average extra waiting- still a miss line 12While the cache is empty, a server can't be served. Once t reaches filled_at, the loop ends and it reads from the cache.
- the lease check lines 13–18Without leases every server passes this test. With leases only the first does, because token_given flips to True.
- wait and retry lines 19–20Servers refused a token don't touch the database. They sleep and ask the cache again, and that sleep is the cost.
Read more
- usenix.org: Cache stampedes and leases
- Ask Bento: What happens if the lease holder crashes?
- Ask Bento: How do stale sets happen?
- Ask Bento: What is a cache stampede in other systems?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.