CACHE STAMPEDE
When a popular key expires, everyone races to recompute
user:42 expires at 1000 ms. Ten readers arrive evenly between 700 and 1300 ms. A DB load takes 150 ms, plus 50 ms for each load already running. No protection. How many DB loads does this one expiry cost?
A cached key expires at one instant. Every request that arrives before someone reloads it misses. In plain cache-aside each miss runs its own DB load. Those loads compete, so each one is slower, so the window stays open longer and more requests fall into it.
Three fixes keep the same expiry. Singleflight lets the first miss load and makes the rest wait for that load. Stale-while-revalidate keeps serving the old value while one background refresh runs. Early refresh lets a reader refresh before expiry, with a probability that rises as expiry approaches.
function get(key) {
const v = cache.get(key);
if (v !== undefined) return v;
const fresh = await db.load(key); // every concurrent miss runs this
cache.set(key, fresh, TTL);
return fresh;
}const inflight = new Map(); // key -> Promise
function get(key) {
const v = cache.get(key);
if (v !== undefined) return v;
if (!inflight.has(key)) {
inflight.set(key, db.load(key).then((fresh) => {
cache.set(key, fresh, TTL);
return fresh;
}).finally(() => inflight.delete(key)));
}
return inflight.get(key); // everyone shares one load
}
// Stale-while-revalidate: keep the old value past its soft TTL,
// return it immediately and refresh once in the background.
// Early refresh (XFetch): refresh when
// now - LOAD_MS * beta * ln(random()) >= expiresAt Watch the DATABASE box and the invariant strip. NO PROTECTION turns both invariants red after expiry. SINGLEFLIGHT and STALE-WHILE-REVALIDATE face the same traffic and the same expiry and keep loads for the v1 expiry at 1 at every REQUESTS value; stale-while-revalidate also keeps the longest wait at 0 ms. EARLY REFRESH (PROBABILISTIC) holds at the default but not at every count: move the slider and watch it let two loads through.
No protection. The DB absorbs 3 loads for one expiry without falling behind. Raise REQUESTS until one expiry costs more than that, and note the count where it first happens.
GOAL: one expiry costs more than 3 DB loads
Add singleflight. Concurrent misses for the same key must share one loader call, and the next expiry must be able to load again. loader(key) returns a Task, not a Promise: call .then(fn) on it to get a new Task. Return the value on a hit and a Task on a miss. No async/await.
Hot keys in Redis or memcached: homepage queries, config blobs, a celebrity's profile. Go's singleflight package, stale-while-revalidate in HTTP Cache-Control, memcached leases, and the XFetch paper (“Optimal Probabilistic Cache Stampede Prevention”, VLDB 2015). Symptom: periodic DB spikes lined up with a TTL.
“A popular key expires and the DB falls over. What happened and how do you fix it?” Explain the miss window and the feedback loop, then compare singleflight (bounded load, waiters), stale-while-revalidate (no waiting, stale reads) and early refresh (probabilistic). In a fleet, say that singleflight is per process, so N servers can still send N loads unless you add a distributed lock or lease.
USED IN
Chapters that build on this lesson.
- Caching in front of the databaseDatabases