How it works
A cache stampede happens when many readers miss the same entry together and all rebuild it. For example, a key is read 5,000 times per second and takes 200 ms to rebuild. When it expires, about 1,000 readers miss before the first rebuild finishes (5,000 times 0.2), and all query the database. If those queries slow the database, rebuilds take longer, more readers miss, and the spike feeds itself. Scale to a Million Users warns of the same burst when a cache node restarts, and News Feed’s hot timeline and post entries carry the same risk.
Single-flight lets one caller rebuild a key while the others wait for that result. Go’s singleflight package does this within a process, so 50 servers means at most 50 queries, not 1,000. For one rebuild across the fleet, take a short-lived lock in Redis using SET with NX and an expiry. The expiry matters: if the holder crashes, the lock frees itself.
Jittered expiry adds randomness to each entry’s TTL, such as 300 seconds plus or minus 10 percent, so keys loaded together do not expire together. It helps many keys but not one hot key, which still has a single expiry moment.
Serving stale handles the hot key. Give each entry a soft expiry and a longer hard expiry. After the soft expiry, readers get the old value at once while one background worker refreshes it, the idea behind HTTP’s stale-while-revalidate. The cost is a bounded period of old data, which is fine for a product description but not for a permission check.
A leaderboard key is read by 300 app servers and takes a 3-second query to rebuild. It expires every 60 seconds, and the database spikes each minute. A teammate proposes adding 10 percent jitter to the TTL. What do you do?
Jitter only moves one key’s expiry, so the spike still comes about once a minute. In-process single-flight caps it at 300 queries, which is still large. A leaderboard tolerates being a little old, so serve stale after a soft expiry and let one worker, holding a short-lived Redis lock, refresh it. Readers do not wait, and the database sees one query per refresh.
Use this as a guide for self review; written answers are not graded.Keep in mind
- One expiring hot key can send every concurrent reader to the database.
- Single-flight limits rebuilds, jitter spreads many keys, and stale serving shields readers from the rebuild.
- Serve stale data only where a bounded period of old values is acceptable.