Sub topic 11
Invalidating Cached Data
This chapter assumes you know what cache-aside is, how TTL expiration works, and how to read basic Python. Invalidation is the act of removing or replacing a cached entry because the source data changed. It is the hardest part of caching to get right, because the cache and the database are two separate stores with no shared transaction.
Why invalidation is hard
A cache holds a copy. When the original changes, the copy is wrong until something fixes it. Three things make this difficult:
- The writer must know which cache keys depend on the changed data.
- The database write and the cache change are two operations. One can succeed while the other fails.
- Other readers run at the same time and can put old data back.
TTL alone bounds how long a stale entry can live, but it does not remove staleness. Explicit invalidation shortens the stale window, and TTL stays in place as a safety net for when invalidation fails.
The main approaches
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Delete on write | Update the database, then remove the key | Simple, next read refills | Brief race windows |
| Update on write | Update the database, then write the new value to the cache | No miss after a write | Race windows are worse, and every writer must build the cached shape |
| Event-driven | Publish a change event, and subscribers delete keys | Decouples writers from caches | Delivery delay, lost events |
| Versioned keys | Put a version in the key, so a change creates a new key | No delete needed | Old keys wait for TTL or eviction |
| TTL only | Do nothing and wait for expiry | No code | Stale for the full TTL |
Most teams start with delete on write and add the others only where needed.
Delete on write
The cache-aside example from earlier in this tutorial uses this pattern. The write goes to the database first, then the key is removed.
import time
cache = {} # key -> (value, expires_at)
TTL_SECONDS = 60
def update_user(user_id, data, db):
db.save_user(user_id, data) # 1. source of truth first
cache.pop(f"user:{user_id}", None) # 2. then invalidateDeleting is usually safer than updating the cache in place. If you write the new value into the cache, two concurrent writers can finish their database writes in one order and their cache writes in the other. The cache then keeps the older value. A delete has no such ordering problem, because the next read loads whatever the database holds.
Why the order matters
If you delete the key before the database write, a reader can slip in between the two steps. It misses, reads the old row, and caches it. The write then finishes, and the cache holds old data until TTL expires.
sequenceDiagramThe diagram below shows that wrong ordering.
Writing to the database first and deleting second narrows the window but does not close it.
Race conditions that remain
Even with the correct order, one race survives. A reader misses and reads the old row from the database. Before it stores that row, the writer saves the new row and deletes the key. The reader then stores the old row. The entry is stale until TTL expires.
This window is small, because the reader must be slow between its read and its cache write. It still happens under load. You have three common ways to deal with it:
- Keep a short TTL on entries that matter, so any stale entry ages out quickly.
- Delete the key a second time after a short delay (a delayed double delete). This catches the late reader's write.
- Store a version or timestamp with the value, and have the cache reject a write whose version is older than the stored one.
The third option needs a cache that supports conditional writes, such as a compare-and-set or a script. It is the only one of the three that closes the window instead of narrowing it.
When the delete fails
The database write can succeed and the cache delete can fail, for example if the cache node is unreachable. The caller sees an error or, worse, no error, and the cache keeps old data until TTL.
Handle this deliberately:
- Retry the delete a limited number of times.
- If retries fail, push the key onto a queue so a background worker keeps retrying.
- Log the failure and count it as a metric, so you can see how often it happens.
- Keep TTL set on every entry. TTL is the final backstop.
Never make the database write depend on the cache delete succeeding. A cache outage should not stop users from saving data.
Event-driven invalidation
When many services cache the same data, the writer cannot reach every cache directly. A common design is to publish a message such as user.updated with the user's id. Each service listens and deletes its own keys.
import json
def on_message(raw, cache):
event = json.loads(raw)
if event["type"] == "user.updated":
user_id = event["id"]
cache.pop(f"user:{user_id}", None)
cache.pop(f"user_profile:{user_id}", None)Two failure modes apply. Messages can arrive late, so the stale window equals the delivery delay. Messages can also be lost. Brokers differ in delivery guarantees, so check what yours promises, and keep TTL as the fallback. Make handlers idempotent, meaning that running one twice has the same effect as running it once. Deleting a key is naturally idempotent.
Invalidating derived and grouped data
A single change often affects several keys. Changing a product's price may stale the product page, a category listing, and search results that include it. Three techniques help:
- Explicit key lists. The write path deletes every known dependent key. This is simple but breaks when someone adds a new cached view and forgets to update the list.
- Tags or groups. Store a set of keys under a tag such as
category:12, and delete everything in the set. This needs extra bookkeeping in the cache. - Versioned namespaces. Keep a counter for the group and include it in every key. Incrementing the counter makes all old keys unreachable at once.
import time
cache = {}
TTL_SECONDS = 300
def namespace_version(group):
return cache.get(f"ns:{group}", 1)
def list_key(category_id, page):
v = namespace_version(f"category:{category_id}")
return f"products:cat{category_id}:v{v}:page{page}"
def invalidate_category(category_id):
group = f"ns:category:{category_id}"
cache[group] = cache.get(group, 1) + 1 # old keys are now unreachable
print(list_key(12, 1))
invalidate_category(12)
print(list_key(12, 1))Running this prints products:cat12:v1:page1 and then products:cat12:v2:page1. The old entries are never read again, and TTL or eviction removes them later. The cost is wasted memory until that happens, in exchange for a single cheap operation that invalidates any number of keys.
Choosing a TTL alongside invalidation
If your invalidation is reliable, a long TTL is acceptable, because TTL only covers missed events. If invalidation is best effort, use a TTL equal to the staleness you can tolerate. Data that users notice immediately, such as a changed password or a cart, needs reliable invalidation or no caching at all.
Common mistakes
- Invalidating only the key you remember, not the derived keys.
- Deleting the cache before writing the database.
- Updating the cache in place from several writers.
- Failing the user's request because the cache delete failed.
- Removing TTL because "we invalidate on every write".
- Never testing the invalidation path, so bugs show up as rare, hard-to-reproduce stale data.
Exercise
A service writes to the database and then deletes the cache key. A user still sees old data for up to a minute, but only occasionally under heavy load. The TTL is 60 seconds. Describe the race that likely causes this and one fix that closes it.
Show answer
A slow reader missed the cache and read the old row from the database. The writer then saved the new row and deleted the key. The reader finished afterward and stored the old row in the cache, which stays until the 60 second TTL expires. A fix that closes the window is to store a version with each value and use a conditional write that rejects older versions. A delayed second delete or a shorter TTL only narrows the window.
Exercise
Why is deleting a cache key on write usually safer than writing the new value into the cache?
Show answer
With in-place updates, two concurrent writers can commit to the database in one order and update the cache in the other, leaving the older value cached. A delete has no ordering problem because the next read loads the current database value.