Full answer
Read path: GET product:42 → miss → SELECT ... FROM products WHERE id = 42 → SET product:42 <json> EX 300.
Write path: UPDATE products ... ; COMMIT; then DEL product:42.
Pitfalls:
- Delete after commit, not before: deleting first lets a concurrent reader repopulate the cache with the old value before the commit.
- Even after commit, a slow reader that fetched the old row just before the update can write it to the cache after the delete. A short TTL limits how long that stale value lives; a delayed second delete narrows the window further.
- Derived pages (category lists containing the product) need their own invalidation, often through events from an outbox or change data capture.
- Stampedes: when a hot key expires, many requests hit the database at once; use a lock or early refresh.
Cache what is read often and changes rarely. For prices and stock, keep TTLs short or read from the database directly.
Key points
- Cache-aside with TTL
- Write the database, then delete the key
- Races can still leave stale entries briefly
- Invalidate derived keys via events
- Guard against stampedes
Common mistakes
- Updating the cache and database in the wrong order
- Caching volatile values like stock with long TTLs
Follow-ups
- What is write-through caching?
- How would you warm the cache after a deploy?
Tips
- Explain the order of operations on write