← Back to Node.js, page 8

nodejs-0145 · Hard senior

How do you implement cache-aside with Redis in a Node.js service, including TTL jitter, stampede protection with a lock, negative caching and invalidation?

Cache-aside means the application reads the cache first, loads from the database on a miss, and writes the result to the cache with a TTL. To stop a stampede (many requests loading the same missing key), let one request take a short lock with SET key NX PX and load, while others wait briefly and read the cache. Add TTL jitter, cache 'not found' for a short time, and delete the key when data changes.

Full answer

Cache-aside steps

  1. GET the key from Redis. If found, return it.
  2. On a miss, load from the database.
  3. SET the key with a TTL, then return the value.
  4. On a write, update the database first and then DELETE the cache key (not update it, which avoids race conditions between writers).

Problems and fixes

  • Stampede: when a hot key expires, hundreds of requests miss at once and hit the database. Use a lock: SET lock:key token NX PX 5000. Only the winner loads. The others sleep a few milliseconds and read the cache again, or fall back to loading after a timeout. In one process, share the promise instead.
  • Safe release: delete the lock only if the stored token is yours (a short Lua script compares and deletes). The lock expiry protects against a crashed owner.
  • Synchronised expiry: many keys with the same TTL expire together. Add random jitter (for example plus or minus 10 percent).
  • Negative caching: store a marker such as null for a short TTL (30 seconds), so lookups for missing ids do not reach the database repeatedly.
  • Stale data: choose a TTL by how wrong the data may be. Stale-while-revalidate returns the old value and refreshes in the background.
  • Serialisation: JSON for plain data, and a version in the key (user:v2:42) so a deploy that changes the shape does not read old entries.
  • Failure of Redis: treat the cache as optional. On a Redis error log and go to the database, with a timeout so Redis problems do not slow requests.
  • Avoid caching per-user data under shared keys, and never cache secrets.

Metrics: hit rate, loader calls, lock waits and latency.

javascript
const Redis = require('ioredis');
const { setTimeout: sleep } = require('node:timers/promises');

const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const prefix = `cache-demo:${process.pid}:`;
let loaderCalls = 0;
const database = new Map([['1', { id: 1, name: 'Asha' }]]);

async function loadFromDatabase(id) {
  loaderCalls++;
  await sleep(50);                                       // a slow query
  return database.get(id) ?? null;
}

const jitter = (seconds) => Math.round(seconds * 1000 * (0.9 + Math.random() * 0.2)); // plus or minus 10 percent

async function getStudent(id) {
  const key = prefix + 'student:' + id;
  for (let attempt = 0; attempt < 20; attempt++) {
    const cached = await redis.get(key);
    if (cached !== null) return JSON.parse(cached);       // a stored null means "known to be missing"

    const token = Math.random().toString(36).slice(2);
    if (await redis.set(key + ':lock', token, 'PX', 2000, 'NX')) {   // winner loads
      try {
        const value = await loadFromDatabase(id);
        const ttlMs = value === null ? 1000 : jitter(60);            // short TTL for missing data
        await redis.set(key, JSON.stringify(value), 'PX', ttlMs);
        return value;
      } finally {
        await redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0", 1, key + ':lock', token);
      }
    }
    await sleep(10);                                       // someone else is loading, check the cache again
  }
  return loadFromDatabase(id);                             // give up waiting
}

async function main() {
  // 20 requests arrive together for the same missing cache key.
  const results = await Promise.all(Array.from({ length: 20 }, () => getStudent('1')));
  console.log('20 parallel requests ->', results.every((r) => r && r.name === 'Asha'), '| database calls:', loaderCalls);

  await getStudent('1');
  console.log('a later request hits the cache, database calls:', loaderCalls);
  const ttl = await redis.pttl(prefix + 'student:1');
  console.log('TTL with jitter is within 54 to 66 seconds:', ttl > 53000 && ttl <= 66000);

  // Invalidate on write: update the database, then delete the key.
  database.set('1', { id: 1, name: 'Asha Rao' });
  await redis.del(prefix + 'student:1');
  console.log('after invalidation:', (await getStudent('1')).name, '| database calls:', loaderCalls);

  // Negative caching: a missing id is loaded once, then remembered briefly.
  await getStudent('99'); await getStudent('99'); await getStudent('99');
  console.log('three lookups of a missing id -> database calls:', loaderCalls);

  const keys = await redis.keys(prefix + '*');
  if (keys.length) await redis.del(...keys);
  await redis.quit();
}
main();

Twenty parallel requests for the same key cause one database call because of the lock. The script needs a running Redis server. Install first with npm install ioredis (run here with ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 20 parallel requests -> true | database calls: 1 a later request hits the cache, database calls: 1 TTL with jitter is within 54 to 66 seconds: true after invalidation: Asha Rao | database calls: 2 three lookups of a missing id -> database calls: 3

Key points

  • Read cache, load on miss, set with TTL, delete on write.
  • A NX lock lets one request load while others wait.
  • Add TTL jitter and short negative caching.
  • Delete the key on write instead of updating it.
  • Treat the cache as optional when Redis fails.

Common mistakes

  • Letting every request reload a hot key after it expires.
  • Deleting a lock that belongs to another owner.
  • Updating the cache and the database in different orders from different writers.
  • Using the same TTL for every key.
  • Failing requests because Redis is down.

Follow-ups

  • Why delete the key on write instead of setting the new value?
  • How does stale-while-revalidate work?
  • What are the weaknesses of a single-instance Redis lock?

Tips

  • Say the four steps first.
  • Explain the stampede with numbers: one load, many waiters.
  • Mention token-checked release.