Sub topic 11
Invalidating Cached Data
This chapter assumes you know cache-aside, TTL expiration, and the basic read and write paths from earlier chapters. Invalidation is the work of removing or replacing a cached entry once its source data has changed. TTL alone bounds staleness. Invalidation shrinks it.
Three ways to invalidate
| Approach | How it works | Staleness window | Main risk |
|---|---|---|---|
| Time-based | The entry expires after its TTL | Up to the full TTL | Stale reads until expiry |
| Delete on write | The writer removes the key after updating the source | Short, usually milliseconds | Races, missed keys |
| Update on write | The writer overwrites the cached value | Short | Concurrent writers can store an older value |
Delete on write is the usual default. A delete is idempotent. Repeating it does no harm. The next read rebuilds the entry from the source.
Delete after the write, not before
Order matters in cache-aside. The safe order is to update the database first, then delete the key. The update_user function from the cache-aside chapter does this.
If you delete first, a concurrent reader can refill the cache with the old row before your write commits. That stale value then stays until its TTL runs out.
A race that remains
Deleting after the write is not fully safe. A reader can miss, read the old row, and then be delayed. If the writer commits and deletes during that delay, the reader still stores the old value afterward. This is rare because the read must be slower than the write. A TTL on every entry caps the damage, so keep a TTL even when you invalidate explicitly.
Invalidating related keys
One change can affect many keys. Updating a product may change its detail page, a category list, and search results. Two techniques help:
- Keep a record of which keys depend on which source row, and delete them all on write.
- Put a version number in the key, such as
catalog:v7:category:3. Bumping the version makes every old key unreachable. Eviction and TTL clean up the orphans later.
Versioned keys depend on the key design you chose earlier. They avoid scanning for keys to delete.
Invalidation by event
When writers are spread across services, publish a change event and let a consumer delete the affected keys. This keeps cache logic out of every writer. It adds delay and a new failure point. If the consumer falls behind, stale data lasts longer, so monitor its lag.
def on_user_changed(event, cache):
# event is a dict such as {"user_id": 42}
cache.pop(f"user:{event['user_id']}", None)
cache.pop(f"user:{event['user_id']}:profile_page", None)
cache = {"user:42": "old", "user:42:profile_page": "old"}
on_user_changed({"user_id": 42}, cache)
print(cache) # {}Exercise
A service deletes the cache key first, then updates the database. Why can this leave stale data in the cache, and what change fixes most of the problem?
Show answer
Between the delete and the database write, a reader can miss, load the old row, and put it back in the cache. That entry then stays until its TTL ends. Updating the database first and deleting the key afterward fixes most cases. Keeping a TTL on the entry covers the remaining rare race.
Exercise
Why might you use versioned keys instead of deleting every key related to a changed category?
Show answer
Versioned keys need no list of dependent keys and no scan. You bump one version number and the old keys are never read again. They expire or are evicted later.