Node.js › Caching
What is cache stampede (thundering herd), and how do you prevent it in a high-traffic Node.js service?
AdvancedAnswer
Cache stampede occurs when a popular cached entry expires and many concurrent requests simultaneously discover the cache miss and all rush to recompute the same expensive underlying data at once, momentarily overwhelming the downstream database exactly as if the cache didn't exist. Common mitigations include using a lock or 'in-flight request' map so only the first request actually recomputes the value while others wait for that same result, and 'stale-while-revalidate' -- serving the slightly stale cached value immediately while refreshing it in the background.
const inFlight = new Map();
async function getWithStampedeProtection(key, fetchFn) {
if (inFlight.has(key)) return inFlight.get(key); // join the existing in-flight fetch
const promise = fetchFn().finally(() => inFlight.delete(key));
inFlight.set(key, promise);
return promise;
}Real-world example A news site's homepage data cache expiring during a traffic spike used to cause a brief but severe database overload; adding an in-flight deduplication map ensures only one regeneration happens per expiration, with all other concurrent requests simply awaiting that same result.