← Back to System Design, page 1

system-design-0008 · Hard senior

Why is cache invalidation hard? How do you prevent stale data and cache stampedes in a high-traffic system?

Invalidation is hard because the cache and the database are separate systems updated at different moments, so races and failed deletes leave stale entries. Use TTLs as a backstop, delete keys after the database commit, drive invalidation from the change log for reliability, and prevent stampedes with request coalescing, locks, jittered TTLs and early refresh.

Full answer

Where stale data comes from

  1. Race between a reader and a writer. Reader misses, reads old row from the database, pauses. Writer updates the row and deletes the key. Reader resumes and writes the old row into the cache. Now the cache holds old data until the TTL expires.
  2. Failed invalidation. The database commit succeeds but the delete call to the cache times out.
  3. Many copies. The same data sits in a local in-process cache, Redis and a CDN. Invalidating one layer does not touch the others.
  4. Derived keys. A student's marks appear in student:42, class:10B:toppers and school:report. Forgetting one derived key is easy.

Techniques for freshness

  • TTL on every key. It bounds how long wrong data can live. Choose by tolerance: 5 seconds for a price, 1 hour for a course description.
  • Delete after commit, not before. Optionally delete again after a short delay ("delayed double delete") to cover the reader race.
  • Versioned values. Store a version number with the cached value and only overwrite if the new version is higher (Redis Lua script or compare-and-set).
  • Change data capture (CDC). Tail the database's replication log (for example with Debezium into Kafka) and invalidate keys from those events. It retries until the delete succeeds and catches writes from every service, not just the one that remembered to delete.
  • Versioned keys for immutable content. report:v17. Bumping the version makes old keys unreachable; they expire by themselves. CDN assets use content hashes in file names for the same reason.

Stampedes (thundering herd)

When a hot key expires, thousands of requests miss at once and all hit the database. Suppose a key is read 20,000 times per second and the database query takes 50 ms. In that 50 ms window, about 20,000 x 0.05 = 1,000 requests miss and run the same query.

Defences:

  • Request coalescing / single flight: only one request per key per server rebuilds the value; others wait for its result.
  • Distributed lock on rebuild: SET lock:key token NX PX 2000; the winner rebuilds, others serve the stale value or wait briefly.
  • Stale-while-revalidate: keep serving the old value past its soft expiry while one worker refreshes it.
  • Jittered TTLs: ttl = 300 + random(0, 60) so keys created together do not expire together.
  • Probabilistic early refresh: refresh slightly before expiry with a probability that grows near the deadline.

Trade-off

Every technique buys freshness or protection with complexity. Decide per data type how stale it may be, and set TTLs and invalidation effort to match.

By level

Fresher: Explain that a cache copy can go out of date and that TTLs and deleting keys on update are the basic fixes. Describe what happens when a popular key expires. Naming TTL as a safety net is the key point at this level.

Mid: Walk through the reader-writer race, explain delete-after-commit, versioned values and request coalescing, and estimate the stampede size from traffic and query time. The arithmetic of a stampede should be done out loud.

Senior: Design CDC-driven invalidation across services and cache layers, handle multi-region caches, define per-entity staleness budgets, and plan database headroom for cold-cache recovery. Expect a reliable, event-driven invalidation path rather than delete calls scattered in code.

Key points

  • Races between readers and writers can write stale data back into the cache
  • TTLs bound staleness and must exist on every key
  • CDC-based invalidation is more reliable than delete calls scattered in code
  • Stampedes happen when a hot key expires; coalescing, locks and stale-while-revalidate prevent them
  • Jitter TTLs so keys do not expire together

Common mistakes

  • Deleting the cache key before the database commit
  • Relying only on application code to invalidate every derived key
  • Using the same fixed TTL for millions of keys created at the same time
  • Forgetting local in-process caches and CDN layers

Follow-ups

  • Walk through the reader-writer race and show where delayed double delete helps
  • How would you invalidate a value cached in 500 app servers' local memory?
  • How do you pick a TTL for product prices?

Tips

  • Narrate one concrete race with timestamps
  • Do the stampede arithmetic out loud
  • Separate freshness techniques from stampede techniques

Evaluation rubric

  • Identifies at least two real causes of staleness
  • Proposes concrete invalidation mechanisms including TTL and an event-driven option
  • Explains stampede with numbers and two or more defences
  • Discusses trade-offs and per-data tolerance