How to Prevent a Cache Stampede with Single-Flight
Stop the thundering herd on a cache miss: coalesce concurrent loads, refresh ahead of expiry, and jitter TTLs so keys do not expire together.
On this page
Introduction
A cache exists to keep load off the origin. The failure mode that defeats it is the stampede: a hot value expires, every concurrent request misses at the same moment, and they all call the origin together. Because the value was cached precisely because it is expensive, the burst hits the origin hardest exactly when the origin can least afford it. A single slow origin call multiplied by hundreds of concurrent callers can take a service down.
This tutorial prevents the stampede with two techniques: single-flight, which coalesces concurrent loads of the same key into one, and a proactive refresh that reloads a hot key before it expires. It also covers TTL jitter so a group of keys does not expire together. The examples are runtime-agnostic, with code for a Node.js service.
Coalesce concurrent loads with single-flight
Single-flight keeps a map of in-progress loads keyed by the cache key. When a caller needs a key that is already being loaded, it awaits the same promise instead of starting its own. The origin sees one load per key per instance, no matter how many callers ask. When the load resolves, all waiters get the result, and the map entry is removed so the next miss can start fresh.
Implement it so the in-flight entry is removed when the load settles, whether it resolves or rejects, or a rejected load would poison every future caller until the process restarts. If the load rejects, the waiters all receive the rejection, which is usually correct, but consider whether a single failure should fail every waiter or whether a retry is warranted. Keep the guard small and per key, and clean up on settlement.
const inflight = new Map<string, Promise<unknown>>();
function singleFlight<T>(key: string, load: () => Promise<T>): Promise<T> {
const existing = inflight.get(key) as Promise<T> | undefined;
if (existing) return existing; // join the in-progress load
const p = load().finally(() => inflight.delete(key)); // clean up on settle
inflight.set(key, p);
return p;
}
async function cachedGet(key: string, load: () => Promise<string>): Promise<string> {
const hit = await store.get(key);
if (hit !== null) return hit;
return singleFlight(key, async () => {
const value = await load();
await store.set(key, value, { EX: 300 });
return value;
});
}
Refresh ahead of expiry
Single-flight absorbs a miss, but the hottest keys should ideally never miss. A proactive refresh reloads a value shortly before it expires, so the cache holds a fresh value continuously and callers never see the miss. Read the value with its remaining TTL, and if the remaining time is below a threshold, trigger a background refresh while still returning the current value.
The background refresh must be coalesced too, or many readers seeing a low TTL will each kick off a refresh and recreate the stampede. Use the same single-flight guard for the refresh path. Return the current value immediately and refresh asynchronously, so the request latency does not include the refresh, and the value stays available throughout.
async function getWithRefresh(key: string, load: () => Promise<string>): Promise<string> {
const value = await store.get(key);
const ttl = await store.ttl(key);
if (value !== null && ttl > 0 && ttl < 30) {
// still return the current value; refresh in the background (coalesced)
singleFlight('refresh:' + key, async () => store.set(key, await load(), { EX: 300 })).catch(() => {});
}
return value ?? singleFlight(key, async () => store.set(key, await load(), { EX: 300 }).then(() => load()));
}
Jitter the TTLs to spread expirations
A batch of keys written together, such as a warm-up that loads a thousand entries at once, all expire at the same moment if they share a TTL, producing a stampede across every key at once. Adding random jitter to each TTL spreads the expirations over a window so the origin sees a steady trickle of refreshes instead of a wall.
Choose jitter proportional to the TTL, a few seconds on a five-minute TTL or a minute on an hour TTL. Apply it wherever you set a TTL from a fixed value, including the negative cache. The jitter is cheap and removes a failure mode that is otherwise invisible until a scheduled warm-up coincides with peak traffic.
function ttlWithJitter(baseSeconds, jitterSeconds = 30) {
return baseSeconds + Math.floor(Math.random() * jitterSeconds);
}
// a thousand keys warmed together now expire across a 30-second window, not at once
await store.set(key, value, { EX: ttlWithJitter(300) });
Handle the load failure
Coalescing bounds the origin load, but it also means one failure is shared by every waiter. Decide whether that is acceptable. For a transient origin error, the waiters all see the error, and a later retry succeeds. Where you want resilience, add a small timeout so a hung load does not block every waiter indefinitely, and fall back to a stale value or a default rather than failing everyone.
Do not let a failed load leave a lock held. The single-flight entry must be removed on rejection, or every subsequent caller joins a promise that will never resolve usefully. Test the rejection path specifically, because the happy path hides a leaked entry that only shows up when the origin has a bad minute.
function singleFlightWithTimeout(key, load, ms) {
const existing = inflight.get(key);
if (existing) return existing;
const p = Promise.race([
load(),
new Promise((_, rej) => setTimeout(() => rej(new Error('load timeout')), ms)),
]).finally(() => inflight.delete(key)); // release even on timeout/reject
inflight.set(key, p);
return p;
}
Test the burst and the refresh
Fire many concurrent requests for one cold key and assert the origin loader was called exactly once, which proves single-flight. Fire concurrent requests near expiry and assert the background refresh also coalesced to one call. Warm a batch with jittered TTLs and assert their expirations are spread, not simultaneous. Test that a rejected load releases the in-flight entry so a later request can retry.
# 200 concurrent cold requests for one key -> origin called once
seq 1 200 | xargs -P 200 -I{} curl -s -o /dev/null http://localhost:3000/hot/1
grep -c 'origin load' server.log # expect 1
Common pitfalls
No coalescing so a miss fans out to the origin, an in-flight entry not removed on failure so retries join a dead promise, proactive refresh without coalescing so the refresh itself stampedes, a fixed TTL so a batch expires together, and no timeout so a hung load blocks all waiters are the recurring mistakes. Single-flight on the load and the refresh, cleanup on settle, TTL jitter, and a timeout address them.
Conclusion
A cache stampede defeats the cache by hitting the origin hardest when it is least able. Coalesce concurrent loads with single-flight, refresh hot keys before they expire with the same coalescing, jitter the TTLs so keys do not expire together, and time out a hung load so waiters are not stuck. Self-check by firing many concurrent requests at a cold key and asserting one origin call. Then a popular key expiring is invisible to the origin.
Sources: Groupcache: singleflight package, Redis: Cache stampede mitigation, Coalescing and thundering herd (Wikipedia).
FAQ
- What is a cache stampede?
- It is when a popular cached value expires and every concurrent request misses at once, so they all hit the origin together. The origin sees a burst many times its steady load, which can overload it. The value being cached made the origin slow or expensive, so the burst is worst exactly where it hurts.
- Single-flight or background refresh?
- Single-flight coalesces the loads once a miss happens, so the origin sees one load. Background refresh avoids the miss entirely by refreshing a hot key before it expires. Use both: refresh ahead for the hottest keys, and single-flight as the backstop for any key that does expire.
Report a problem with this articleOpens a pre-filled issue on GitHub.