Headline: A cache stampede happens when a popular cache key expires and every concurrent request misses at the same moment and recomputes the same value against the database. In Node.js I prevent it in layers: coalesce identical in-flight loads inside each process, take a short Redis
SET NX PXlock so only one instance recomputes, and keep a soft expiry so readers get the stale value while a single worker refreshes it in the background.
The cache-aside code I used to write looked correct and passed every test: read from Redis, query Postgres on a miss, write the result back with a TTL. It only failed under real concurrency, when an expensive key — a homepage feed, a pricing table, a dashboard aggregate — expired while many requests were reading it. These are my notes on the layers that actually stop that failure mode in Node.js and NestJS services, and what each layer costs.
Key takeaways
- A cache stampede (also called a thundering herd or dog-piling) is a burst of identical cache misses that all recompute the same value at once, usually right after a hot key expires.
- In-process request coalescing — sharing one in-flight
Promiseper cache key — removes duplicate loads inside a single Node.js process in about ten lines of code. - A Redis lock taken with
SET key token NX PX ttllimits recomputation to one instance across the fleet. It is an efficiency lock, not a correctness guarantee. - A soft expiry stored inside the value, plus a longer hard TTL on the Redis key, lets readers keep getting the stale value while one worker refreshes it, so expiry never blocks a request.
- TTL jitter and probabilistic early expiration spread refreshes over time, so keys written together do not expire together.
Why does the cache-aside pattern cause cache stampedes?
Cache-aside causes stampedes because every reader that sees a miss is responsible for refilling the cache, and nothing tells the other readers that someone is already doing it. Cache-aside, also called lazy loading, is the pattern where the application checks the cache first and, on a miss, loads from the database and writes the result back.
// Naive cache-aside: correct, and a stampede waiting to happen async function getFeed(id: string) { const cached = await redis.get(`feed:${id}`); if (cached) return JSON.parse(cached); const feed = await buildFeedFromPostgres(id); // slow, expensive query await redis.set(`feed:${id}`, JSON.stringify(feed), 'EX', 60); return feed; } When feed:home expires, every request that arrives during the recompute window — the time buildFeedFromPostgres() takes — misses and runs the same query. The extra queries slow the database down, a slower query widens the recompute window, and a wider window lets more requests miss. That feedback loop is how a routine cache expiry turns into a database incident while the cache is technically working.
How do I coalesce duplicate cache loads inside one Node.js process?
Request coalescing means concurrent callers asking for the same key share one in-flight Promise instead of each starting their own load. Go's singleflight package popularized the pattern; in Node.js it is a Map from cache key to Promise.
const inflight = new Map<string, Promise<unknown>>(); export function coalesce<T>(key: string, fn: () => Promise<T>): Promise<T> { const existing = inflight.get(key); if (existing) return existing as Promise<T>; const promise = fn().finally(() => inflight.delete(key)); inflight.set(key, promise); return promise; } Three details mattered for me. First, removing the entry in finally() keeps a rejected promise from being reused forever: every waiter receives the same error once, and the next caller starts a fresh load. Second, the coalescing key must include everything that changes the result — tenant ID, locale, permission scope — or one user's data gets handed to another user's request. Third, one caller's AbortSignal must never cancel the shared load, because other callers are still waiting on it.
React's cache() function is not a substitute. React cache() and Next.js request memoization deduplicate calls within a single server render, while a stampede is many separate requests arriving at once.
How do I stop several Node.js instances from recomputing the same key?
A short-lived Redis lock limits recomputation to one instance, because Redis SET with the NX option only succeeds for the first caller while the lock key exists. In-process coalescing works per process, so ten replicas behind a load balancer still run ten recomputes without a shared lock.
import { randomUUID } from 'node:crypto'; // Delete the lock only if this caller still owns it const RELEASE = `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0`; export async function withRecomputeLock<T>(key: string, ttlMs: number, fn: () => Promise<T>) { const lockKey = `lock:${key}`; const token = randomUUID(); const acquired = await redis.set(lockKey, token, 'PX', ttlMs, 'NX'); // ioredis if (acquired !== 'OK') return null; // another instance is recomputing try { return await fn(); } finally { await redis.eval(RELEASE, 1, lockKey, token); } } The random token and the Lua compare-and-delete script stop an instance from deleting a lock that already expired and was taken by someone else. I set the lock TTL comfortably above the slowest recompute I expect; if a recompute outlives the lock, the worst case is one extra recompute, which is acceptable for a cache. I treat this strictly as an efficiency lock. A single-node Redis lock without fencing tokens cannot guarantee mutual exclusion through a failover or a long garbage-collection pause, so I never use it to protect payments or inventory.
The lock leaves one open question: what do the losing instances return? Polling until the value appears adds latency and Redis load, which is why I pair the lock with stale values.
How do I keep cache expiry from ever blocking a request?
Storing a soft expiry inside the cached value, with a longer hard TTL on the Redis key, lets every reader keep serving the old value while one worker refreshes it. It is the HTTP stale-while-revalidate idea applied to an application cache.
type Entry<T> = { value: T; freshUntil: number; computeMs: number }; export async function getOrRefresh<T>(key: string, freshMs: number, load: () => Promise<T>): Promise<T> { const raw = await redis.get(key); const entry = raw ? (JSON.parse(raw) as Entry<T>) : null; const recompute = async () => { const started = Date.now(); const value = await load(); const next: Entry<T> = { value, freshUntil: Date.now() + jitter(freshMs), computeMs: Date.now() - started }; await redis.set(key, JSON.stringify(next), 'PX', freshMs * 10); // hard TTL return value; }; if (!entry) { // Cold miss: nothing stale to serve. Lock losers load directly, still once per process. return coalesce(`cold:${key}`, async () => (await withRecomputeLock(key, 10_000, recompute)) ?? load()); } if (Date.now() >= entry.freshUntil || shouldRefreshEarly(entry)) { void coalesce(key, () => withRecomputeLock(key, 10_000, recompute)) .catch((err) => logger.warn({ err, key }, 'cache refresh failed')); } return entry.value; // fresh or stale, never blocked } The cold-miss branch is the only place a reader still waits, and it only runs after a cache flush or for a brand-new key. Every other read returns immediately, and at most one instance runs load() per refresh. I started with a hard TTL of ten times the soft TTL and shortened it for keys where very old data would mislead users.
On a long-running NestJS process, the fire-and-forget refresh simply finishes on its own. On Vercel Functions or any serverless runtime, the instance can be suspended once the response is sent, so I pass the refresh promise to waitUntil() from @vercel/functions, or schedule it with after() in Next.js, to keep it alive past the response.
How do I spread cache refreshes out over time?
Probabilistic early expiration and TTL jitter spread refreshes over time, so neither one hot key nor thousands of keys written together refresh at the same instant. Probabilistic early expiration makes each reader decide, with a probability that rises as expiry approaches, to refresh before the value actually expires. The technique comes from the 2015 paper Optimal Probabilistic Cache Stampede Prevention by Vattani, Chierichetti, and Lowenstein, and is usually called XFetch.
// XFetch: beta = 1 is the paper's default; beta > 1 favors earlier refreshes function shouldRefreshEarly(e: { freshUntil: number; computeMs: number }, beta = 1) { return Date.now() - e.computeMs * beta * Math.log(Math.random()) >= e.freshUntil; } // TTL jitter: ±10% around the base TTL const jitter = (ms: number) => Math.round(ms * (0.9 + Math.random() * 0.2)); Because Math.log(Math.random()) is always negative, XFetch moves the current time forward by a random amount scaled by how long the last recompute took. Slow keys start refreshing earlier, and cheap keys refresh close to their expiry. XFetch needs no coordination, which makes it useful on a cache without an atomic set-if-absent; alongside a lock, I use it to start the background refresh slightly before the soft expiry instead of after it.
TTL jitter solves a different problem. A cache warm-up script, a deploy that flushes the cache, or a bulk import writes thousands of keys within seconds, and with an identical TTL they all expire within the same second later. Random jitter of about ten percent spreads those expiries out. Jitter does nothing for a single hot key, which is why it complements coalescing and locks instead of replacing them.
How should I cache missing rows and failed loads?
Caching a short-lived not-found marker, called negative caching, stops repeated lookups for nonexistent keys from reaching the database every time. Without it, a crawler or a script requesting random IDs bypasses the cache completely, a failure mode usually called cache penetration. I keep negative entries to a few seconds so newly created rows show up quickly.
Failed loads get the opposite treatment: I never cache the error. When load() throws during a background refresh, the stale entry stays in Redis until its hard TTL, so readers keep getting the last good value while the database recovers — the application-cache equivalent of the HTTP stale-if-error directive.
Which cache stampede protection should I use?
I use these techniques in layers, because each one covers a different scope. The table summarizes what each layer prevents and what it costs.
| Technique | Scope | Prevents | Cost |
|---|---|---|---|
| Request coalescing | One process | Duplicate concurrent loads in that process | A Map and careful key design |
Redis SET NX PX lock | All instances | Parallel recomputes across replicas | Two extra Redis round trips per refresh |
| Soft TTL + stale serving | All readers | Requests blocking on expiry | Readers may see data up to one refresh old |
| Probabilistic early expiration (XFetch) | All readers | A synchronized refresh at the exact expiry moment | Some refreshes happen early |
| TTL jitter | Many keys | Mass expiry of keys written together | Less predictable expiry times |
| Negative caching | Missing keys | Repeated misses for nonexistent rows | A brief delay before new rows appear |
Before building this by hand, I check what the cache library already does. Bentocache for Node.js documents stampede protection and grace periods for stale values, and wrap()-style helpers in other libraries differ on whether they coalesce concurrent calls. I verify the behavior with a concurrency test instead of trusting a README:
import { test } from 'node:test'; import assert from 'node:assert/strict'; test('an expired key loads once under concurrency', async () => { let calls = 0; const load = async () => { calls++; await new Promise((resolve) => setTimeout(resolve, 50)); return 'feed'; }; await redis.del('feed:home'); await Promise.all(Array.from({ length: 300 }, () => getOrRefresh('feed:home', 60_000, load))); assert.equal(calls, 1); }); FAQ
Q: What is the difference between a cache stampede and cache penetration?
A: A cache stampede is many concurrent misses for a key that exists in the database and has just expired from the cache. Cache penetration is repeated misses for keys that do not exist in the database at all, so the cache never fills; negative caching fixes penetration.
Q: Is a Redis SET NX lock safe enough for cache recomputation?
A: Yes, for caching. A duplicate recompute only wastes some database work, so an occasional failure of a single-node Redis lock is harmless. Anything where two concurrent writers would corrupt data needs a database transaction or fencing tokens instead.
Q: Do React cache() or Next.js request memoization prevent cache stampedes?
A: No. React cache() and Next.js request memoization deduplicate calls within one render of one request. A stampede is many separate requests, which needs process-level coalescing plus a lock or stale serving across instances.
Q: How long should the hard TTL be compared with the soft TTL?
A: The hard TTL should cover the longest data-source outage you want to ride out with stale data. I started with ten times the soft TTL and shortened it for keys where very old data would mislead users.
Q: Do I still need application-level stampede protection behind a CDN with stale-while-revalidate?
A: Usually yes. CDN stale-while-revalidate protects cacheable HTTP responses at the edge, but personalized responses, service-to-service API calls, and expensive queries inside a request still go through the application cache, where the same stampede happens.
Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.

