Module 4 · Caching and performanceLesson 37 of 887 minIntermediate
Cache invalidation
When data changes, cached copies become wrong. Invalidation is how you get rid of them, and it's famously hard.
Start with "Do nothing" and watch stale answers pile up. Try "Expire (TTL)" with different TTLs, then "Delete on write".
"There are only two hard things in computer science: cache invalidation and naming things." (Phil Karlton)
Every cached value is a copy. When the original changes, the copy is wrong until something removes or refreshes it.
Strategies
1. Time to live (TTL): every entry expires after a set time.
- Simple and self-healing: even bugs fix themselves after the TTL.
- Data can be stale for up to the TTL.
2. Delete (or update) on write: whenever the app changes data, it deletes the cached key.
- Fresh almost immediately.
- Every code path that writes must remember to invalidate. Miss one, and that data stays wrong.
- Harder when one change affects many cached things (a renamed category appears in thousands of cached pages).
3. Event-driven invalidation: the database publishes changes (change data capture, like Debezium reading the database log), and a consumer deletes affected keys. Nothing gets forgotten, but there's more infrastructure.
4. Versioned keys: include a version in the key (product:42:v7). A change bumps the version, so old entries are simply never read again and expire on their own.
Combining them
The common real-world recipe: delete on write, plus a TTL as a safety net. Writes keep things fresh; the TTL cleans up anything a bug or race missed.
Ask the product question
The right answer depends on how much staleness users can tolerate:
- A bank balance: seconds may matter.
- A product description: minutes are fine.
- A list of countries: days are fine.
Make the staleness budget explicit, then pick the simplest strategy that meets it.