Sub topic 12
Consistency and Staleness Trade-offs
This chapter assumes you know cache-aside, TTL expiration, and invalidation from earlier chapters. It covers what a cache costs you in correctness and how to decide how much staleness you can accept.
Why a cache can be wrong
A cache holds a copy of data that lives somewhere else. Once the source changes, the copy is out of date until something removes or refreshes it. The time between the change and the refresh is the staleness window.
You cannot remove this window. You can only choose how long it is and who sees it.
Two sources of staleness
- Missed invalidation. A write changes the database, but nothing tells the cache. The entry stays wrong until its TTL runs out.
- Races. Invalidation runs, but a concurrent reader puts an old value back.
The race is the one that surprises people. Look at this sequence with cache-aside:
The cache now holds the old value until the TTL expires. A short TTL bounds the damage, which is why TTL is still worth setting even when you invalidate on write.
Choosing a consistency level
Different data tolerates different staleness. Ask what the worst outcome is if a user sees an old value.
| Data | Acceptable staleness | Typical approach |
|---|---|---|
| Product page view counts | Minutes | Long TTL, no invalidation |
| User profile | Seconds | Cache-aside, delete on write, short TTL |
| Account balance, stock for checkout | None | Skip the cache, or read from the source |
Write patterns also differ. Write-through keeps the cache and database in step on every write. Write-back can leave the database behind the cache, so a cache failure can lose writes. Cache-aside with TTL is eventually consistent: the copy converges to the source, but not instantly.
Reducing the window
- Delete the entry after the database write, as in the cache-aside example, rather than before it. Deleting first lets a reader refill the old value while the write is still in progress.
- Always set a TTL as a backstop for missed invalidations and races.
- For critical reads, bypass the cache and query the source.
- Where a user must see their own change, route that user's next reads to the source for a short time, or update the cache with the new value after the write.
Stating the trade-off
For each cached item, write down a staleness budget, such as "profile data may be 30 seconds old". Then pick the TTL and write pattern that fit it. A budget makes the decision testable and gives your team something to review.
Exercise
A reader misses the cache and reads user 7 from the database. Before the reader writes to the cache, a writer updates user 7 and deletes the cache entry. What does the cache hold afterward, and what limits how long it stays wrong?
Show answer
The reader then stores the old value, so the cache holds stale data even though invalidation ran. The entry's TTL limits the damage, because it expires and the next read loads the new value from the database.