Caching interview question · Most asked
Why is cache invalidation hard, and what strategies help?
Summary
Invalidation is hard because data changes in many places, caches are distributed, and races between reads and writes can repopulate stale values. Strategies: TTLs as a safety net, delete-on-write, versioned keys, event-driven invalidation, and accepting bounded staleness where the business allows.
Longer Answer
A classic race: request A misses and reads the old value from the DB; request B updates the DB and deletes the key; request A then writes the stale value into the cache. Mitigations include short TTLs, delayed double delete, versioned keys (bump product:v{n}), or write-through with compare-and-set. Decide per data type how stale is acceptable.
Key Points
- TTL as safety net
- Delete on write
- Versioned keys
- Events for cross-service invalidation
- Define acceptable staleness
More most-asked Caching questions
- Explain the main caching patterns: cache-aside, read-through, write-through and write-behind.
- What is a cache stampede (thundering herd) and how do you prevent it?
- How does HTTP caching work (Cache-Control, ETag, CDNs)?
- Explain the difference between cache penetration, cache breakdown and cache avalanche.
- In cache-aside, why can a value be stale even though you delete the key on every write?
- How can a CDN leak one user's data to another, and how do you prevent it?
- Should you invalidate the cache before or after the database commit?
- How does stale-while-revalidate work, and when is it inappropriate?