Picture a Saturday, a few minutes past ten. The sale banner has gone up at ten exactly, the push notification had gone out at the same moment, and the homepage was doing more traffic than it had done all month.
Then the database graph stood up.
Not a ramp. A wall. Connections pinned, CPU pinned, p99 on the homepage from 180 milliseconds to four seconds in the space of a single scrape interval. Then, about a second later, it fell back down as if nothing had happened. Ten minutes later it did it again. And ten minutes after that.
I looked for the cron. Everyone looks for the cron. There was no cron.
There was a Redis key called listings:popular, holding the ten most-viewed listings for the homepage, with a 600-second TTL. At ten o'clock it was hot. At ten past, it expired. That was the whole incident: a cache stampede, which is the thing this post is about, and which most of us read about and nod at until it has our weekend.
One key, a thousand misses
The mechanics are not complicated, which is why they get missed in review.
A key holds the homepage listings, or the top-ten query, or the rendered navigation. Traffic reads it a few hundred times a second. At second 600 the TTL hits zero and Redis deletes it. The next request misses, and starts the rebuild. The rebuild is a query with two joins and an ORDER BY over a views table, and it takes 300 milliseconds. During those 300 milliseconds the key is still missing, so the next hundred requests also miss, and also start the rebuild.
A hundred copies of the same query land on the database within a third of a second. They all return the same rows. They all write the same value to the same key. Ninety-nine of them were waste, and the database paid for all hundred, and so did every other query that was queued behind them.
The part that makes this painful is when it happens. At 3am the same key expires, one request misses, it rebuilds, nobody notices. At peak the same expiry is hit by a crowd. The problem scales with concurrency, so it is invisible in staging, invisible overnight, and arrives at exactly the moment the database has the least to spare. If you have a sale starting on Saturday morning, this is the Saturday morning incident, and it will be the first thing your database does to mark the occasion.
I covered the Laravel version of the fix in Laravel caching with Redis. This post is about the three approaches underneath, in plain Redis and Node, and which one I would reach for now that I have been on the wrong end of it.
Lock and let one request rebuild
The obvious fix, and the one you end up shipping from your phone at twenty past ten. The first request to miss takes a lock. It rebuilds. Everyone else waits for it.
const LOCK_TTL_MS = 10_000;
async function getPopular(): Promise<Listing[]> {
const cached = await redis.get("listings:popular");
if (cached) return JSON.parse(cached);
const token = randomUUID();
const locked = await redis.set("listings:popular:lock", token, "PX", LOCK_TTL_MS, "NX");
if (locked === "OK") {
try {
const value = await computePopular(); // the 300 ms query
await redis.set("listings:popular", JSON.stringify(value), "EX", 600);
return value;
} finally {
await releaseLock("listings:popular:lock", token); // Lua: only if token matches
}
}
// Someone else holds the lock. Poll briefly for their result.
for (let i = 0; i < 20; i++) {
await sleep(50);
const now = await redis.get("listings:popular");
if (now) return JSON.parse(now);
}
return computePopular(); // gave up waiting; compute ourselves rather than error
}The NX and PX flags on Redis SET do the whole job in one round trip: set only if absent, and expire in so many milliseconds. Two details carry the rest.
The lock has a TTL. If the rebuilding process dies holding it (deploy, OOM, a query that hangs), the lock must expire on its own or every subsequent request waits forever for a rebuild that is not coming. Ten seconds is generous for a 300-millisecond query and short enough that a crash is a ten-second blip rather than an outage. Set it to the worst case of your rebuild, times three.
And the release checks the token. Without that, a slow rebuild that outlives its own lock TTL releases the lock the next holder just acquired. This is a well-known mistake and I have still made it, in a first version of exactly this function.
The weakness is the wait. Those twenty polls are up to a second of latency on a hundred requests, and if the rebuild is slow they time out and fall through to computing anyway, which is the stampede with extra steps. A lock turns a herd into a queue. The queue still has to stand somewhere. The spikes go away, but the ten-minute p99 bump does not, and that is usually what sends people reading.
Recompute before it expires?
A different idea: do not wait for the key to expire. Have one request refresh it slightly early, and choose that request at random with a probability that rises as expiry gets closer.
This is probabilistic early expiration, from a 2015 VLDB paper by Vattani, Chierichetti and Lowenstein, Optimal Probabilistic Cache Stampede Prevention, usually called XFetch. The maths is two lines. On every read, with delta being how long the recompute takes and expiry the moment the key would expire:
recompute if: now - delta * beta * ln(random()) >= expiryrandom() is uniform in (0, 1], so ln(random()) is between negative infinity and zero and -delta * beta * ln(random()) is a positive number that is usually small and occasionally large. Far from expiry it almost never crosses. Near expiry it almost always does. beta is a knob; 1.0 is the paper's default, higher means earlier.
interface Wrapped<T> { value: T; delta: number; expiry: number } // delta, expiry in ms
async function getPopular(beta = 1.0): Promise<Listing[]> {
const raw = await redis.get("listings:popular");
const now = Date.now();
if (raw) {
const w: Wrapped<Listing[]> = JSON.parse(raw);
const early = now - w.delta * beta * Math.log(Math.random()) >= w.expiry;
if (!early) return w.value;
}
const start = Date.now();
const value = await computePopular();
const delta = Date.now() - start;
const w: Wrapped<Listing[]> = { value, delta, expiry: now + 600_000 };
await redis.set("listings:popular", JSON.stringify(w), "EX", 660); // hard TTL a bit past soft
return value;
}No lock, no coordination, no waiting. One request, chosen by the dice, eats the 300 milliseconds and refreshes the key before anyone else needs to. The herd never forms because the key never expires under load.
It also adapts. A recompute that gets slower pushes delta up, which pushes the refresh earlier, automatically. I like that property a lot, because the 300 milliseconds in this story was 300 milliseconds on a quiet database and considerably more on a busy one.
The weakness: it is probabilistic, so on a key read a few times a minute rather than a few hundred times a second there may be no read in the window where early refresh would trigger, and the key expires like any other. That is fine; a key with low traffic cannot stampede. The real cost is that one request per refresh still pays the full recompute latency inline. Under a 300-millisecond query, a user somewhere gets a 300-millisecond-slower page every ten minutes. For a homepage that is acceptable. For a checkout it is not.
Serve stale, refresh behind
The third approach gives up on the idea that the reader should ever wait, and it is the one that should end up in the code the following week.
Store the value with its own soft expiry inside it. Set the Redis key's hard TTL well past that. On a read, if the soft expiry has passed, return the stale value immediately and kick off a refresh in the background, guarded by a lock so only one refresh runs.
interface Wrapped<T> { value: T; softExpiry: number }
async function getPopular(): Promise<Listing[]> {
const raw = await redis.get("listings:popular");
if (raw) {
const w: Wrapped<Listing[]> = JSON.parse(raw);
if (Date.now() > w.softExpiry) void refreshInBackground(); // not awaited
return w.value; // stale is fine
}
return refreshNow(); // cold start, the only time a reader waits
}
async function refreshInBackground() {
const locked = await redis.set("listings:popular:refresh", "1", "PX", 10_000, "NX");
if (locked !== "OK") return; // someone else is on it
try {
await refreshNow();
} finally {
await redis.del("listings:popular:refresh");
}
}
async function refreshNow(): Promise<Listing[]> {
const value = await computePopular();
const w: Wrapped<Listing[]> = { value, softExpiry: Date.now() + 600_000 };
await redis.set("listings:popular", JSON.stringify(w), "EX", 3600); // hard TTL: one hour
return value;
}Nobody blocks except on a cold cache. The value is at most one refresh old. The database sees exactly one query per soft TTL, regardless of concurrency. If the database is down the stale value keeps serving for up to an hour, which is a feature, and which has saved more than one homepage.
The costs are honest ones. The hard TTL means memory is held longer, and for large values that matters; I wrote about what large values do to a Redis instance in the cache compression post, and the same arithmetic applies here. The background refresh needs somewhere to run (in Node it is a dangling promise in the request process, which is fine until the process is recycled mid-refresh, which is why the lock has a TTL). And "at most one refresh old" is a promise you have to be able to make to the product team, because a user who just changed something and sees the old version will not care that the architecture is elegant.
The one I'd pick
Stale-while-revalidate, every time, for anything that can be stale at all.
The lock approach makes readers queue, and queues under load are what you were trying to avoid. XFetch is clever and I would use it where I cannot store a wrapper around the value, but it still charges one reader the full rebuild. Stale-while-revalidate charges nobody after the first request, degrades gracefully when the backend is slow or down, and the code is the easiest of the three to read at 2am. Or at twenty past ten on a Saturday.
What would change my mind is a value that must not be stale. Then stale-while-revalidate is a correctness bug, and I would go to the lock, with the TTL set carefully and the token check in the release, and accept the queue. Or I would ask why that value is in a cache in the first place, which is the question that gets skipped most often. And I would read the query plan for the rebuild, because a 300-millisecond query that becomes a 30-millisecond query shrinks every one of these windows by ten.
The mistake I made, for longer than I like, was treating this as a problem to solve per key when I noticed a spike. It is a property of the cache wrapper. The right place for the soft TTL and the background refresh is the one function every cached read goes through, so that the next hot key is protected before anyone has to find it on a graph on a Saturday morning, with a sale on.