Cache invalidation and write patterns
Keep cached data fresh enough, and choose how writes reach the cache and the database.
15 min readDecide how stale is acceptable
Every cache serves data that may be out of date; the design question is by how much. A product description can be a few minutes old without anyone noticing. A price shown at checkout or an account balance should not be stale at all, so it may bypass the cache or be read from the source of truth at the moment it matters. Write the staleness budget down per type of data. It decides your TTLs, whether you need explicit invalidation, and which reads must skip the cache entirely.
Write patterns
Cache-aside handles reads; you also need a rule for what happens to the cache when data changes. The choice trades freshness, write latency and risk of loss against each other, and different data in the same system can use different patterns. Most designs start with invalidate on write plus a TTL and only move to the others for a specific reason.
- Invalidate on write: update the database, then delete the cache key; the next read repopulates it. Simple and the most common choice
- Write-through: write to the cache and the database together, so the cache is always warm for recently written data
- Write-behind: write to the cache and flush to the database later; fast writes but risk of loss if the cache fails
- TTL only: never invalidate, just let entries expire; fine when the staleness budget is generous
Races and why delete beats update
Updating a cached value on every write sounds fresher than deleting it, but concurrent writers can leave the cache holding an older value than the database: writer A reads version 1, writer B writes version 2 to both stores, then A writes its stale result into the cache. Deleting the key after the database commit avoids most of these races, because the next reader fetches the current row. Always keep a TTL as a safety net, so any inconsistency you missed heals itself within minutes rather than lingering forever.
Stampedes on popular keys
When a very popular key expires or is invalidated, hundreds of requests can miss at the same moment and all query the database for the same row. This is a cache stampede. Mitigations include request coalescing, where only one request recomputes the value and the rest wait for it, adding random jitter to TTLs so many keys do not expire together, and refreshing hot keys in the background shortly before they expire. In SystCode, the Feedback panel shows database load jumping when hit rate drops; these techniques keep that jump small.
Key takeaways
- Set a staleness budget per type of data before choosing TTLs
- Invalidate on write by deleting the key after the database commit
- Always keep a TTL as a safety net against missed invalidations
- Coalesce requests and jitter TTLs to prevent stampedes on hot keys
Sign in to track lessons and earn badges.