Sub topic 12
Consistency and Staleness Trade-offs
This chapter assumes you know the cache-aside pattern, TTL expiration, and invalidation from earlier chapters. You should also be comfortable with client-server requests and with basic database behavior. Here we look at what a cache costs you in correctness, and how to decide how much staleness is acceptable.
Why a cache is never perfectly consistent
A cache holds a copy of data that lives somewhere else. The source of truth, usually a database, can change at any moment. Between that change and the moment the cache learns about it, the cache returns stale data: a value that no longer matches the source.
This is not a bug in one particular pattern. It follows from having two copies and no way to update both atomically. A database write and a cache update are two separate operations on two separate systems. Either can fail, be delayed, or be reordered relative to other requests.
So the real question is not "can I avoid staleness?" but "how much staleness can this data tolerate, and for how long?"
Staleness as a budget
Think of staleness as a budget you spend to buy speed. Define it per kind of data:
| Data | Tolerable staleness | Reason |
|---|---|---|
| Product description | Minutes to hours | Rarely changes, low harm if old |
| Follower count | Seconds to minutes | Users do not notice small drift |
| Account balance shown before a payment | Near zero | Wrong value causes wrong decisions |
| Inventory at checkout | Zero (read the source) | Overselling has a real cost |
| Permissions and revocation | Near zero | Stale access is a security issue |
A useful habit is to write the budget as a number, such as "at most 30 seconds old". A TTL then becomes the upper bound of that budget when no other mechanism corrects the entry sooner.
Where staleness comes from
Different patterns create staleness in different ways.
- TTL only. The entry can be stale for up to the full TTL after the source changes. Staleness is bounded but always possible.
- Cache-aside with invalidation on write. Staleness is usually short, but race conditions can leave a stale value in place for a full TTL (see below).
- Write-through. The cache and database are updated together, so reads are fresh unless one of the two writes fails or another writer bypasses the cache.
- Write-back. The cache is ahead of the database. Readers of the cache see new data, but readers of the database see old data until the flush happens. Data can also be lost if the cache fails before flushing.
- Replicas. If the cache is filled from a read replica that lags the primary, the cache can store an old value even though it was loaded just now.
A race that leaves stale data behind
Cache-aside with delete-on-write is the common default, and it has a well-known race. Consider a reader and a writer working on the same key.
The reader's read happened before the write, but its cache fill happened after the delete. The delete had nothing to remove, so the old value is now cached. It stays there until the TTL expires or another invalidation arrives.
This race is rare because it needs a slow reader and a fast writer to overlap on the same key. It is real at scale, though. Three things reduce the damage:
- Keep a TTL on every entry, so a bad entry heals itself.
- Delete the key rather than writing the new value into the cache. Two concurrent writers updating the cache can leave the older write last, while a delete is order-insensitive.
- For high-value keys, use a version number or timestamp stored with the value, and refuse to overwrite a newer version with an older one.
Order matters: update the database first
The update function from the cache-aside chapter writes to the database and then deletes the cache entry. The reverse order is worse.
If you delete the cache entry first and then write the database, a reader can arrive in the gap. It misses the cache, reads the old row, and refills the cache with old data. The write then finishes, and nothing invalidates the entry. The stale window now lasts until the TTL.
Deleting after the write shrinks the window to the narrow race shown above. It does not remove the window.
Some systems close it further with a delayed double delete: delete the key after the write, wait a short interval longer than a typical read, and delete again. This catches a late refill. It adds complexity and a timing assumption, so use it only where a short stale window is not acceptable and a version check is not available.
Failure of the invalidation step
The database write can succeed while the cache delete fails, for example because of a network error. The cache then serves old data until the TTL expires. Options for handling this:
- Rely on the TTL. Simple, and the TTL is the staleness bound.
- Retry the delete. Put the failed delete in a queue and retry until it succeeds.
- Publish changes from the database. Drive invalidation from a change log, so every committed write produces an invalidation event, and the writer does not need to remember to call the cache.
The third option makes invalidation reliable at the cost of an extra component. Even then, delivery can lag, so the TTL stays as a backstop.
Consistency models you will meet
Caching systems are often described using terms from distributed systems. Here is what they mean for a cache.
| Model | What a reader sees | Typical cache setup |
|---|---|---|
| Strong consistency | Always the latest committed value | No cache, or write-through with a single writer path and no replicas |
| Read-your-writes | A user sees their own updates immediately, others may lag | Bypass or refresh the cache for the writing user |
| Eventual consistency | Old values for a while, converging to the latest | TTL-based cache-aside |
| Bounded staleness | Never older than a stated limit | TTL equal to the limit, plus invalidation |
Read-your-writes is worth singling out because users notice its absence. If someone edits their profile and then sees the old profile on the next page, they assume the save failed. A common fix is to delete the cache entry on write and make sure the next read by that user goes to the source, or to return the new value from the write response itself. Other users can continue to see the cached copy until it expires.
Serving stale data on purpose
Sometimes returning an old value is better than returning nothing. Two techniques use staleness deliberately:
- Stale-while-revalidate. When an entry has expired, return the old value immediately and refresh it in the background. The user sees fast responses, and the next request gets fresh data. HTTP supports this with the
stale-while-revalidatedirective. - Stale-if-error. If the source is down, keep serving the expired entry rather than failing. This trades correctness for availability during an outage.
Both need a limit. An entry that is hours old during an outage may be acceptable for a news page and unacceptable for a price.
Detecting staleness in practice
You cannot fix what you cannot see. Practical checks include:
- Sampling. For a small percentage of cache hits, also read the source and compare. Log the mismatch rate and the age of the cached entry.
- Age metadata. Store the load time with each value, and record the age of entries served. A rising age distribution suggests invalidation is failing.
- Targeted tests. Write a value, read it through the cache, and assert what a reader sees within your staleness budget. Run these against the real invalidation path, not just the cache library.
The following example stores a version with each value and refuses to overwrite a newer entry with an older one. This closes the race shown earlier for keys where each write increments a version.
import threading
import time
cache = {} # key -> (value, version, expires_at)
guard = threading.Lock()
TTL_SECONDS = 60
def put_if_newer(key, value, version):
"""Store the value only if it is newer than what the cache holds."""
with guard:
entry = cache.get(key)
now = time.monotonic()
if entry is not None and entry[2] > now and entry[1] >= version:
return False # the cache already holds an equal or newer version
cache[key] = (value, version, now + TTL_SECONDS)
return True
def get_user(user_id, db):
key = f"user:{user_id}"
entry = cache.get(key)
if entry is not None and entry[2] > time.monotonic():
return entry[0]
value, version = db.fetch_user_with_version(user_id)
put_if_newer(key, value, version)
return valueThe reader in the race above would call put_if_newer with the old version. If a writer has already placed the new version in the cache, the old fill is rejected. This works when writers also populate the cache with their version. If writers only delete, a deleted key has no version to compare against, so the guard cannot help in that case. In that setup, keep the TTL short and accept the narrow window.
Choosing a staleness level
Work through these questions for each kind of data:
- What is the harm of a user seeing a value that is N seconds old?
- How often does the data change compared with how often it is read? Data that is read often and changes rarely is the best fit for caching.
- Can writes reach the source through more than one path, such as batch jobs or admin tools? Each path needs to invalidate the cache.
- Is there a replica between the cache and the primary, and how far can it lag?
- Does a failure of invalidation need to be self-healing? If yes, always set a TTL.
The answers set the TTL, the invalidation mechanism, and whether the data should be cached at all. Strong consistency and high cache hit ratios pull against each other, and the staleness budget is where you decide the balance.
Exercise
A service updates a user's email in the database and then deletes the cached entry user:7. A support agent reports that after one update, the old email still appears for about a minute, though most updates show correctly. The TTL is 60 seconds. What is the most likely cause, and what two changes reduce the problem?
Show answer
Most likely cause: a reader missed the cache before the write, read the old row, and then refilled the cache with the old value after the writer's delete. The delete found nothing to remove, so the stale value stayed until the 60-second TTL expired. Changes that help: (1) store a version with each entry and reject fills older than the cached version, or use a delayed second delete to catch late refills; (2) shorten the TTL for this key type so any remaining stale entry heals sooner. Reading from the primary instead of a lagging replica when filling the cache is also worth checking.
Exercise
For each item, state whether you would use a long TTL, a short TTL with invalidation, or no cache: (a) a blog post body, (b) a user's permission list, (c) the stock count shown during checkout.
Show answer
(a) Long TTL, since the content changes rarely and staleness causes little harm. (b) Short TTL with active invalidation on every permission change, because stale access is a security risk. (c) No cache, reading from the source, since overselling has a direct cost; a short TTL is acceptable only on browse pages, not at the point of purchase.