Skip to content
Caching

Lesson 6 of 14 · 24 min

x
6/14

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Cache Invalidation Strategies

Phil Karlton's famous quote still holds: cache invalidation is one of the two hardest problems in computer science. When the underlying data changes, stale cache entries must be removed or updated — otherwise users see outdated information.

TTL (time-to-live) is the simplest strategy: every cached entry expires after a fixed duration. Set product cache to 5 minutes and stale data self-corrects. Event-based invalidation is more precise: when a product is updated, publish an event that tells every cache node to delete product:42. Versioned keys add a version number to cache keys (product:42:v3) — when data changes, bump the version and old entries become unreachable without explicit deletion. Stale-while-revalidate serves the stale value immediately while refreshing the cache in the background — users never wait, but may briefly see old data.

Before
TTL only — stale for up to 5 minutes
1await redis.setex('product:42', 300, JSON.stringify(product));2// Product updated in DB at t=60s3// Cache serves stale data until t=300s
After
Event-based invalidation — immediate consistency
1// On product update2async function updateProduct(id, data) {3  await db.products.update(id, data);4  await redis.del(`product:${id}`);5  await eventBus.publish('product.updated', { id });6}7 8// Other app instances also listen9eventBus.on('product.updated', ({ id }) => {10  localCache.delete(`product:${id}`);11});

Check your understanding

  • TTL-only invalidation trade-off?Show answer

    Answer

    Simple, but readers can see stale data until expiry.
  • What does event-based invalidation require?Show answer

    Answer

    Publishers that emit updates and subscribers that delete/update keys — including other app instances.
  • What problem do versioned keys solve?Show answer

    Answer

    Old entries become unreachable when the version bumps without needing an immediate delete everywhere.
Previous

Progress is saved in this browser.

Next Lesson