← Back to Node.js, page 3

nodejs-0046 · Hard senior

What is a cache stampede, and how do you prevent it by caching promises?

A cache stampede happens when many requests ask for the same missing or expired item at once, and each one calls the slow backend. Store the in-flight promise in the cache, so the first caller starts the work and all other callers await the same promise. Remove failed promises and use a TTL.

Full answer

Suppose a dashboard value is cached for 60 seconds and takes 2 seconds to compute. At the moment it expires, 500 requests arrive. Each sees an empty cache and starts its own 2-second computation. The backend gets 500 heavy calls at once, slows down, and the response time grows, which invites more calls.

The fix in Node is simple because of the single thread. Cache the promise, not only the value:

  1. On a request, look up the key.
  2. If a promise exists (finished or still running), return it.
  3. If not, call the loader function, store the returned promise immediately (before any await), and return it.
  4. If the promise rejects, delete the key so the next call can retry. Otherwise the failure is cached.
  5. Add an expiry (TTL). A common refinement is stale-while-revalidate: serve the old value while one background refresh runs.

This works inside one process. With several processes or servers you still get one call per process. For a stronger guarantee use a shared cache with a lock or a short-lived "refresh in progress" key (for example in Redis), and add random jitter to expiry times so all keys do not expire together.

Limit the cache size too, or the cache itself becomes a memory leak.

javascript
function createCache(loader, ttlMs) {
  const entries = new Map(); // key -> { promise, expires }
  return function get(key) {
    const entry = entries.get(key);
    if (entry && entry.expires > Date.now()) return entry.promise;

    const promise = loader(key); // start the work and store the promise at once
    entries.set(key, { promise, expires: Date.now() + ttlMs });
    promise.catch(() => {
      if (entries.get(key)?.promise === promise) entries.delete(key); // do not cache failures
    });
    return promise;
  };
}

async function main() {
  let backendCalls = 0;
  const slowBackend = (id) =>
    new Promise((resolve) => setTimeout(() => { backendCalls++; resolve({ id, average: 74.5 }); }, 50));

  const get = createCache(slowBackend, 1000);

  const requests = Array.from({ length: 100 }, () => get('class-10A'));
  const answers = await Promise.all(requests);
  console.log('requests:', requests.length, '| backend calls:', backendCalls);
  console.log('all callers got the same object:', answers.every((a) => a === answers[0]));

  // A failing loader is not cached.
  let attempts = 0;
  const flaky = createCache(async () => {
    attempts++;
    if (attempts === 1) throw new Error('backend busy');
    return 'ok on attempt ' + attempts;
  }, 1000);
  await flaky('x').catch((e) => console.log('first call failed:', e.message));
  await new Promise((r) => setImmediate(r)); // let the clean-up run
  console.log('second call:', await flaky('x'));
}

main();

One hundred simultaneous callers cause a single backend call. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): requests: 100 | backend calls: 1 all callers got the same object: true first call failed: backend busy second call: ok on attempt 2

Key points

  • Many callers for the same missing key overload the backend.
  • Store the promise at once so later callers share it.
  • Delete rejected promises.
  • Use TTL, jitter and stale-while-revalidate.
  • Per-process only. Use a shared lock across servers.

Common mistakes

  • Caching the resolved value only, so the work starts again for every parallel request.
  • Caching a rejected promise for the full TTL.
  • Letting all keys expire at the same second.
  • Growing the cache without a size limit.

Follow-ups

  • How would you share the lock across several servers?
  • How does stale-while-revalidate change user latency?
  • How would you add a maximum size to this cache?

Tips

  • Start with the 500-requests picture.
  • Explain why storing the promise before any await is the key step.
  • Mention jitter to show you know the multi-server case.