← Back to Backend, page 1

backend-0018 · Hard senior

What is a cache stampede (thundering herd), and how do you prevent it with locks, request coalescing and TTL jitter?

A stampede happens when a hot cache key expires and many requests miss at once, so they all hit the database to rebuild the same value and may overload it. Prevent it by letting only one request rebuild: coalesce concurrent callers in a process (single-flight), use a short distributed lock (SET NX PX) across processes while the others wait or serve stale data, add random jitter to TTLs so keys do not expire together, and refresh popular keys before they expire.

Full answer

The problem

  • A key with 5,000 requests per second expires. During the 100 ms that the database query takes, 500 requests miss and send the same query. The database slows down, rebuilds take longer, more requests pile up, and the system can collapse.

Defences

  1. Single-flight (request coalescing) inside one process: keep a map of key to the in-flight promise. The first miss starts the load, the others await the same promise.
  2. Distributed lock for many processes: SET lock:key token NX PX 2000. The winner loads and fills the cache, and releases the lock only if it still owns it (compare the token in a Lua script). The losers wait briefly and re-read the cache, or return stale data.
  3. TTL jitter: add 10 to 20 percent random time to each TTL so keys created together do not expire together.
  4. Early refresh or stale-while-revalidate: store a soft expiry. After it, serve the old value and refresh in the background. Probabilistic early expiration (refresh a bit before expiry with growing probability) also spreads the load.
  5. Warm important keys on deploy, and protect the database with timeouts, a concurrency limit and a circuit breaker.

Always give the lock a TTL (a crashed winner must not block forever) and a waiting limit, and fall back to loading the value yourself when the wait ends.

javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

let dbCalls = 0;
const slowQuery = async () => { dbCalls++; await sleep(50); return 'expensive result'; };

async function naive(key) {
  const hit = await redis.get(key);
  if (hit) return hit;
  const value = await slowQuery();
  await redis.set(key, value, 'EX', 30);
  return value;
}

const RELEASE_LOCK = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
async function withLock(key) {
  for (let attempt = 0; attempt < 50; attempt++) {
    const hit = await redis.get(key);
    if (hit) return hit;
    const token = Math.random().toString(36).slice(2);
    if (await redis.set(`lock:${key}`, token, 'PX', 2000, 'NX')) {         // only one caller gets the lock
      try {
        const value = await slowQuery();
        await redis.set(key, value, 'EX', 30 + Math.floor(Math.random() * 6));    // TTL with jitter
        return value;
      } finally { await redis.eval(RELEASE_LOCK, 1, `lock:${key}`, token); }
    }
    await sleep(10);                                                        // others wait and look again
  }
  return slowQuery();                                                       // give up waiting, load it ourselves
}

(async () => {
  await redis.del('bk18:a', 'bk18:b', 'lock:bk18:b');
  await Promise.all(Array.from({ length: 20 }, () => naive('bk18:a')));
  console.log('20 concurrent misses, no protection :', dbCalls, 'database calls');

  dbCalls = 0;
  const results = await Promise.all(Array.from({ length: 20 }, () => withLock('bk18:b')));
  console.log('20 concurrent misses, with a lock   :', dbCalls, 'database call | all got the value:', results.every((r) => r === 'expensive result'));
  const ttl = await redis.ttl('bk18:b');
  console.log('TTL is inside the jitter range      :', ttl >= 29 && ttl <= 35);
  console.log('lock released after the load        :', (await redis.exists('lock:bk18:b')) === 0);
  await redis.del('bk18:a', 'bk18:b');
  redis.disconnect();
})();

Runs against the local Redis server with a 50 ms fake query. Twenty requests start together, and the database call count is the measurement. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 20 concurrent misses, no protection : 20 database calls 20 concurrent misses, with a lock : 1 database call | all got the value: true TTL is inside the jitter range : true lock released after the load : true

Key points

  • Many concurrent misses on one key overload the database.
  • Single-flight lets one caller rebuild and others share the result.
  • A lock with a TTL and an owner token works across processes.
  • Jitter and early refresh avoid synchronised expiry.
  • Add timeouts and fallbacks to every wait.

Common mistakes

  • A lock with no expiry that blocks everyone after a crash.
  • Releasing a lock with DEL without checking the owner.
  • Everyone waiting forever instead of falling back.
  • Setting the same TTL for all keys.
  • Protecting the cache but not the database behind it.

Follow-ups

  • How does probabilistic early expiration work?
  • When would you serve stale data instead of waiting?
  • How is single-flight different from a distributed lock?

Tips

  • Explain the failure chain first.
  • List four defences.
  • Mention token-checked release.