Why you need it
A popular copy can be answering thousands of people a second. The instant it expires, all of them miss together and rush to the database for the same thing, which can knock the database over exactly when traffic is highest.
Think of it like this
One shop assistant telling a crowd the price of the sale item. When she goes on break, everyone runs to the manager's office at once to ask the same question. Better: one person asks, and everyone waits a moment for the answer.
Where you’ll find it
- Facebook: Gives one caller a "lease" to refill a missing copy while others wait, as described in its memcache paper.
- NGINX: Has
proxy_cache_lock: only one request fetches a missing copy, the rest wait for it. - Go: Ships singleflight, which merges identical requests in flight into one.
What to know first
Expiry. The moment a cached copy's TTL runs out and it is thrown away. See Invalidation and TTL.
Miss. Asking the cache and finding no copy, so the request goes to the database.
How it works
- What goes wrong. 1,000 requests a second share one copy. It expires. In the next 200 ms, while the database works on the first miss, 200 more requests also miss and also ask the database. This is the rush in the animation.
- Fix 1: only one refills. The first request to miss takes a short lock and fetches. Everyone else waits a moment for its result, or is given the old copy meanwhile. One database query instead of hundreds. This is the fix in the animation.
- Fix 2: refresh before expiry. Refresh popular copies a little before they expire, in the background, so they never go missing. A neat version picks the moment at random, more likely the closer the expiry is.
- Fix 3: spread expiry times. If many copies were filled together with the same TTL, they also expire together. Add a little randomness, say 10 minutes plus up to 1 extra, so they do not all expire at once.
An example
The sale page gets 5,000 requests a second. Building it from the database takes 0.5 seconds.
No protection: the copy expires, and in that half second about 2,500 requests hit the database for the same page. It slows down, which makes the window longer, and it spirals.
With one-refills: one query, 0.5 seconds, while the others are served the old copy or wait briefly. The database barely notices.
Further reading
- Cache stampede, Wikipedia. Short overview of the three common fixes. Start with this one.
- Optimal Probabilistic Cache Stampede Prevention, Andrea Vattani and others, VLDB 2015. The early-refresh trick, with the one-line formula behind it.
- singleflight, Go package docs. A tiny, real implementation of "only one refills".