Backend Case Studies

Topic B5

Cache invalidation, TTL and stampedes

TTLs, deleting cache entries when data changes, and stopping thousands of requests refilling at once.

10 min · advanced

Watch: when the copy expires, six users arrive at once. Without protection all six ask the database; with protection, just one does.

u1u2u3u4u5u6cacheusersDBprice · TTL 3s
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 6

A popular product's price is cached with a TTL (time to live) of 3 seconds. While it's valid, every request is served from the cache.

The problem isn't the TTL itself, but every request noticing the empty cache in the same second.

TTL: expiring on its own

A TTL is the use-by date on a milk carton. Simple and safe: at worst, data is stale for as long as the TTL. Choosing one is a trade-off. A short TTL means fresh data but more database queries. A long TTL means a calmer database but users may see old prices. For prices or stock, seconds. For a category list, hours.

Invalidation: delete on change

When an admin changes a price, delete its cache key at the same time. The next request misses and fetches the new price. It sounds easy, but you need to know every key that holds that data: the product page, the category list, search results, recommendations. Missing one means stale data that only goes away when its TTL runs out. That's why invalidation is almost always paired with a TTL as a safety net.

Code, for programmersUpdate the database first, then delete the cache
async function updatePrice(id, price) {
  await db.product.update({ where: { id }, data: { price } });
  await redis.del(`product:${id}`);   // delete, don't overwrite:
}                                         // the next read refills it from the source

Cache stampedes

Choose "no protection" in the figure. A popular key expires, and every request arriving in that second sees an empty cache and goes to the database. Three common ways to prevent it:

  • Single-flight / lock: the first request takes a lock and refills; the others wait for its result.
  • Stale-while-revalidate: keep serving the old value briefly while one process refills in the background.
  • TTL with jitter: add a few random seconds to each TTL so thousands of keys don't expire together.
Code, for programmersSingle-flight within one process
const inFlight = new Map();   // key -> promise of the value being fetched

async function getOnce(key, load) {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);
  if (inFlight.has(key)) return inFlight.get(key);   // someone is already loading it

  const p = load()
    .then(async (v) => { await redis.set(key, JSON.stringify(v), "EX", 60 + Math.random() * 10); return v; })
    .finally(() => inFlight.delete(key));
  inFlight.set(key, p);
  return p;
}
// across many servers, use a short Redis lock (SET key NX EX 5) instead

Quiz

  1. What is a cache stampede?

  2. A price changes. What is safer after updating the database?

  3. Why add random jitter to TTLs?

0 of 3 answered.