← Back to SQL, page 23

sql-0457 · Medium mid

How would you add a cache in front of the database for product pages, and keep it correct when products change?

Use cache-aside: read from the cache, and on a miss read the database and store the result with a time-to-live. On updates, write to the database first, then delete the cache key so the next read reloads it. Short TTLs bound staleness, and versioned keys or change events help when many keys depend on one row.

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