Caching interview question · Most asked
Should you invalidate the cache before or after the database commit?
Summary
After. Deleting before commit lets other readers re-cache the old row (they still see it until the commit). Use on-commit hooks or transactional events.
Longer Answer
Django transaction.on_commit, Laravel DB::afterCommit, Spring @TransactionalEventListener(AFTER_COMMIT) or a transaction-aware cache manager. Also avoid filling the cache from a lagging replica right after a write.
Key Points
- Invalidate after commit
- Before-commit deletes get undone
- Don't fill from lagging replicas
Deep dive: Database Caching at Scale
More most-asked Caching questions
- Explain the main caching patterns: cache-aside, read-through, write-through and write-behind.
- Why is cache invalidation hard, and what strategies help?
- 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?
- How does stale-while-revalidate work, and when is it inappropriate?