How to Implement Cache Invalidation Strategies
Invalidate caches correctly: choose TTL versus event-driven eviction, invalidate dependent keys, and avoid the stale-read races that survive a delete.
On this page
Introduction
There is a famous line that the two hard problems in computer science are cache invalidation and naming things, and the joke lands because invalidation genuinely is hard. A cache must serve a value that is close enough to the truth, which means deciding how stale is acceptable and how a change reaches the cache. Get it wrong and you either serve old data for minutes or you defeat the cache by invalidating so aggressively it never helps.
This tutorial covers the two main strategies, TTL and event-driven eviction, how to invalidate dependent keys when one entity changes, and the subtle delete race that leaves a stale value even after a correct delete. The examples use generic cache operations and apply to an in-process cache, Redis, or a CDN.
Choose TTL or event-driven invalidation
A TTL expires a value after a fixed time, so staleness is bounded by that time and nothing has to know when the data changes. It is simple, robust, and the default for data where a short window of staleness is fine. The cost is that the cache may serve a value that is stale for up to the TTL, and that a read shortly after expiry pays the origin load. Scale the TTL to how much staleness the product tolerates.
An event-driven invalidation evicts a key when the underlying data changes, so the next read sees the new value promptly. It is needed when a write must be reflected quickly, such as a profile change the user expects to see immediately. The cost is that the writer must know which keys to evict, which is easy for the primary key and harder for derived keys. Use both: a TTL as a backstop for correctness and an event for promptness.
// TTL as the backstop, explicit eviction on write for promptness
async function updateProfile(userId, patch) {
await db.update(userId, patch);
await cache.del('profile:' + userId); // prompt: next read reloads
await cache.del('profile:list:page:1'); // dependent list page
await cache.del('profile:count:active'); // dependent aggregate
}
Invalidate dependent keys, not just the primary
The hard part is not evicting the key for the entity that changed, it is evicting the keys derived from it. A list that includes the entity, an aggregate that counts it, a search result that mentions it, and a page that renders it are all stale after the change. An invalidation strategy that only deletes the primary key leaves derived caches serving old data, and these are often the ones users see on a list or a dashboard.
Two approaches handle dependencies. One is to enumerate the derived keys at write time and delete each, which is precise but requires the writer to know every derivative; keep a mapping or a naming scheme so the set is discoverable. The other is to make derived keys depend on a version that changes on write, so all derived keys for an entity become unreachable at once. The version approach scales better as the number of derivatives grows.
// versioned keys: bump the version, and every derived key for the entity misses
async function bumpVersion(entity: string, id: number) {
const v = await versions.incr(entity + ':' + id); // e.g. 5 -> 6
return v;
}
function derivedKey(entity: string, id: number, v: number, suffix: string) {
return entity + ':' + id + ':v' + v + ':' + suffix; // old v keys are never read again
}
Avoid the delete race
Even a correct delete can be defeated by a race. A read that begins before a write and finishes after it can repopulate the cache with the value it read, which is now stale, just after the writer deleted the key. The write then appears not to have taken effect until the next TTL expiry. This is the tricky failure that makes invalidation feel unreliable.
Versioned keys close the race: because the key encodes a version that changed on write, the stale read writes to the old version’s key, which no reader uses anymore. An alternative is to delete after the write commits and to delay subsequent reads slightly, but versioning is cleaner and removes the timing dependence. Delete after the transaction commits, never before, so you do not evict a value the transaction failed to change.
async function updateWithVersion(entity, id, patch) {
const v = await db.transaction(async (tx) => {
await tx.update(entity, id, patch);
return tx.incrVersion(entity, id); // version bump committed with the write
});
// the old version's keys are no longer read; no delete race is possible
return v;
}
Use events for cross-instance invalidation
A write on one instance must invalidate caches on the others. Publishing an invalidation event on a channel every instance subscribes to lets each drop its local copy promptly, which is essential for an in-process layer that would otherwise hold a stale value for its whole TTL. The event carries the key or the entity and version, and each instance evicts accordingly.
Make the event idempotent and tolerate missed messages. If an instance is down during an event, it will recover its correctness when the TTL expires, so the event improves promptness while the TTL guarantees eventual correctness. This layering is why you always keep a TTL even with events: events make it fast, TTL makes it right when an event is lost.
await cache.publish('invalidate', JSON.stringify({ key: 'profile:' + userId }));
// every instance:
subscriber.subscribe('invalidate', (msg) => {
const { key } = JSON.parse(msg);
localCache.del(key);
});
Test the staleness bound
Test that a write is visible within the promised window: after a write with event invalidation, the next read returns the new value; after a write with only a TTL, the new value appears at the latest after the TTL. Test that a dependent key, such as a list or a count, is also updated, which catches an invalidation that forgot the derivatives. Test the race by starting a slow read, performing a write, letting the read finish, and asserting the cache does not serve the stale value.
# write, then read: new value must appear (event invalidation)
curl -s -X PUT -d '{"name":"new"}' http://localhost:3000/users/1 >/dev/null
curl -s http://localhost:3000/users/1 | grep -q '"name":"new"'
# a list that includes the user must also reflect the change
curl -s http://localhost:3000/users?page=1 | grep -q '"name":"new"'
Common pitfalls
Invalidating only the primary key and leaving derived keys stale, deleting before the write commits so the cache reloads the old value, relying only on a TTL when a write must be seen promptly, ignoring the read-after-write race, and no TTL at all so a lost event leaves a value stale forever are the recurring mistakes. Versioned keys or dependency enumeration, delete-after-commit, a TTL backstop, and events address them.
Conclusion
Cache invalidation is choosing how stale is acceptable and how a change reaches the cache. Use a TTL as the correctness backstop and an event for promptness, invalidate the dependent keys or version them so derivatives miss too, delete after the write commits, and use events across instances. Self-check by asserting a write is visible within the window and that a dependent list reflects it. Then invalidation is a bounded, testable property instead of a hopeful gesture.
Sources: MDN: HTTP caching and invalidation, Redis: Keyspace notifications, AWS: Caching best practices and cache invalidation.
FAQ
- Is TTL-based invalidation enough?
- For data where brief staleness is fine, yes, and it is the simplest and most robust approach. For data that must reflect a write promptly, add an explicit invalidation on write. Many systems use both: a TTL as a backstop and an event for promptness.
- Why does a delete not always fix staleness?
- A read that started before the write can finish after it and repopulate the cache with the old value. Deleting after the write and using versioned keys, where the key changes on each write, close that race because the stale read writes to an old key that is no longer read.
Report a problem with this articleOpens a pre-filled issue on GitHub.