What Is Cache Invalidation - and When You Actually Don't Need It

What is cache invalidation? It is the part of a caching system that decides when a cached copy of data is no longer trustworthy, and what to do about it. Cache invalidation exists because a cache is a second copy of the truth, and the moment the first copy changes, the second one is lying.

The lie is usually harmless. A product description that is thirty seconds out of date costs nothing. A permissions check that is thirty seconds out of date can be an incident. Invalidation is how you choose which of those you are living with.

Almost every caching bug in production is really an invalidation bug. The read path was easy; the hard part was noticing that something changed, in a system where the thing that changed and the thing holding the copy do not know about each other.

This page covers the mechanism, the standard cache invalidation strategies and what each one costs, and the fairly large set of cases where the honest answer is to use a short expiry and stop thinking about it. Close-up of tower servers in a data center with blue and red lighting.

ConceptCache invalidation
Where it sitsData access layer - sits between your application and its source of truth, wherever a copy of data is held
In one sentenceCache invalidation is the set of rules that decide when a cached value is treated as stale, so reads stop returning it.

The 60-Second Answer

What it does: marks or removes cached entries once the underlying data has changed, so readers stop getting an old value.

The one problem it solves: a cache makes reads fast by holding a copy, and a copy diverges from the source the instant the source is written. Invalidation bounds how long that divergence can be observed.

The one cost it adds: correctness now depends on every write path knowing which cache keys it affected. That coupling does not show up in a benchmark - it shows up six months later when a new write path is added and forgets to invalidate.

Default position: start with time-based expiry (TTL). Move to explicit invalidation only for the specific keys where a stale read is actually expensive.

How It Actually Works

1. A cache entry is a copy with no link back to its source

The structural reason this is hard

When you store a value in a cache, you store bytes under a key. The cache does not know the value came from a database row, and the database does not know a copy exists. There is no reference, no subscription, no callback.

That missing link is the whole problem. Every invalidation strategy is a way of reconstructing a relationship the storage layer never recorded, either by guessing with time or by telling the cache explicitly on write.

⚠️ In production — This is why 'just invalidate on write' breaks as a system grows. Nothing enforces the mapping from a write to the keys it affects, so the mapping lives in developers' heads and in code review. Writes that bypass your application - a migration, an admin console, a replication stream, somebody running an UPDATE by hand - invalidate nothing at all.


2. Time-based expiry (TTL): let the entry die of old age

No coordination, bounded staleness

You attach a lifetime to the entry. After it elapses, the next read misses and refetches. Nothing has to notify anything.

cache.set(f"product:{product_id}", payload, ttl=60)

The TTL is a direct statement of your staleness budget: with a 60-second TTL, a reader can see data up to 60 seconds old. You are not eliminating staleness, you are capping it and making the cap explicit.

⚠️ In production — A TTL is also a load-shaping decision, not just a correctness one. Entries written together tend to expire together, and the refetch arrives as a spike rather than a trickle. Spreading expiry with a small random offset per key - jitter - is usually the difference between a smooth refill and a periodic thundering herd on your database.


3. Write-through and write-around: decide what a write does to the cache

Update it, or just remove it

On a write you have two sane options. Write-through updates the cache with the new value as part of the write. Write-around (often called write-invalidate) deletes the key and lets the next reader repopulate it from the source.

Deleting is usually the better default. It is one operation, it is idempotent, and the value that eventually lands in the cache was read from the source of truth rather than assembled by the write path.

⚠️ In production — Write-through quietly requires the write path to be able to construct exactly the same shape the read path caches. If the cached value is a joined or derived object - a product with its current stock and its computed price - the write path now has to recompute that whole object, and any difference between the two code paths becomes a cache that is wrong in a way no refetch will fix.


4. Explicit invalidation on write: the ordering trap

Delete after the commit, not before

The sequence matters. Write to the source of truth, let it commit, then delete the cache key. If you delete first, a concurrent reader can miss, read the old value from the database, and write that old value back into the cache - where it now sits with a fresh lifetime.

db.update(product_id, fields)   # commit first
cache.delete(f"product:{product_id}")  # then invalidate

Even in the correct order there is a narrow window where a reader has already fetched the old value and has not yet stored it. Ordering shrinks the race; it does not remove it.

⚠️ In production — The delete is a second operation that can fail independently of the write, and failing it is silent. If the cache delete throws, or the process dies between the two lines, you now hold a stale entry with no expiry to save you - which is the strongest argument for always setting a TTL even on keys you invalidate explicitly. The TTL becomes your backstop for every invalidation you missed.


5. Keys, dependencies, and the fan-out problem

One write, many affected entries

A single write rarely maps to a single key. Changing a product's price affects the product entry, the category listing it appears in, the search results page, any bundle that prices off it, and the homepage block that featured it.

Two common ways out. Key versioning: embed a version or generation number in the key (product:42:v7), bump the version on write, and the old keys are orphaned and expire on their own - no deletes needed. Or group keys behind a shared prefix or tag so one logical invalidation covers a set.

⚠️ In production — Key versioning trades delete complexity for memory: the orphaned entries stay resident until they expire, so a hot object under frequent writes can hold many dead generations at once. Under memory pressure your cache then starts evicting whatever it wants, and the entries it drops are not the dead ones. Tag-based invalidation has the opposite failure - the tag set grows until a single invalidation is deleting thousands of keys in a blocking call.


6. Invalidation across many caches

Local caches do not hear your delete

A delete against a shared cache like Redis or Memcached reaches every reader of that cache at once. An in-process cache inside each application instance does not: deleting from one instance leaves every other instance holding its own copy.

At that point you need a broadcast - a pub/sub channel or a change stream that every instance subscribes to and acts on. Reading from the database's change log is the more robust version, because it catches writes that did not go through your application code.

⚠️ In production — Broadcast invalidation is best-effort by nature. An instance that was restarting, partitioned, or lagging on its subscription silently misses the message and keeps serving a stale value with no error anywhere. In-process caches therefore want deliberately short TTLs - seconds, not minutes - so a missed broadcast self-heals instead of persisting until the next deploy.


7. The stampede at the moment of invalidation

Invalidation concentrates load

The instant a hot key is invalidated, every concurrent request for it misses at once and goes to the source of truth together. You removed one cache entry and generated a burst of identical expensive queries.

The standard mitigations are to let one requester recompute while the others either wait on it or serve the previous value (a lock or single-flight on the key), and to refresh before expiry rather than at it - an early recompute triggered while the old value is still being served.

⚠️ In production — Serving the stale value during recompute is almost always the right call, and it is also the moment to notice you have changed your consistency story. Your staleness window is no longer the TTL - it is the TTL plus however long a recompute takes under load, which is longest exactly when the system is most stressed.


8. Choosing a strategy from the cost of being wrong

Staleness budget per key, not per system

The decision is not which strategy is best. It is, for each class of data, how much staleness is acceptable and what it costs to do better.

A country list can be cached for a day with no invalidation at all. A product price wants a short TTL plus an explicit delete on write. A permission or a feature flag that gates access wants invalidation you can trust - often meaning you do not cache the decision in-process, or you cache it for only a few seconds.

⚠️ In production — Teams tend to pick one strategy and apply it everywhere, which means either over-engineering the country list or under-engineering the permission check. Set the policy per key class and write the staleness budget down next to the cache call, because the next person cannot infer it from a TTL number alone.

A woman writes 'Use APIs' on a whiteboard, focusing on software planning and strategy. ## Where You Meet It
  • A product catalogue behind a read-heavy API. Product detail entries carry a short TTL and are explicitly deleted when the merchant saves an edit, so the merchant sees their own change immediately. The category listing pages are left on TTL alone - a listing being a minute stale is invisible to shoppers, and invalidating every listing a product appears in on every edit would be a large amount of machinery for no observable gain.
  • A session or permissions check in front of every request. Here the cost of a stale read is a user keeping access after a revoke, so the staleness budget is seconds, not minutes. Teams typically keep this in a shared cache with a very short TTL and an explicit delete on revoke, and deliberately avoid in-process caching of the decision because a missed broadcast would extend the window unpredictably.
  • A CDN in front of a marketing site. Published pages sit at the edge with a long TTL, and the publish pipeline issues an explicit purge for the paths it changed. The purge is the invalidation; the long TTL is what makes the cache worth having. When a purge is missed, the symptom is the classic one - the page looks correct to the author on a cache-busting URL and stale to everyone else.
  • A dashboard aggregating expensive analytical queries. Nobody invalidates these on write, because every write would invalidate everything. Instead the entries have a TTL matched to how often the numbers are actually looked at, with a refresh-before-expiry so the dashboard never pays the recompute cost in a user-facing request.
  • A multi-instance service with an in-process config cache. Each instance holds its own copy, so a config change is broadcast over pub/sub and each instance drops its entry. The TTL stays short anyway, because an instance that was rolling at the moment of the broadcast will never hear it.

When You Actually Need It

  • A specific cached value is read far more often than it is written, and a stale read of it has a named consequence - a user sees their own edit missing, a revoked permission still works, a price is wrong at checkout.
  • Your writers and readers are the same application, so the write path can realistically know which keys it affects. This is what makes explicit invalidation maintainable rather than aspirational.
  • Your source of truth cannot absorb the read volume that a short TTL would generate. If you need a long TTL for load reasons but short staleness for correctness reasons, explicit invalidation is the only way to have both.
  • Recomputing the value is expensive enough that you cannot simply shorten the TTL until the problem disappears - a heavy aggregation, a fan-out across services, an external API call.
  • Writes already flow through a change stream or event log you can subscribe to, which means invalidation can be driven from the data layer and will catch writes that bypass your application.
  • You have more than one cache tier - CDN, shared cache, in-process - and need a deliberate story for how a change propagates through all of them rather than three independent accidents.

When You Don't

  • The data tolerates being a minute old. Use a TTL and nothing else. The overwhelming majority of cached data in the overwhelming majority of systems falls here, and explicit invalidation buys you coupling in exchange for staleness nobody would have noticed.
  • You have one application instance and a database that is comfortably handling its load. You do not need invalidation because you probably do not need the cache. Add an index, fix the N+1 query, or let the database's own buffer cache do its job - a cache you did not add cannot serve a stale value.
  • Write volume is close to read volume. Invalidation on every write means the entry is almost never warm when it is read, so you are paying cache round-trips, invalidation complexity, and the occasional stale read for a hit rate near zero. Cache something further down the stack, or do not cache.
  • The value is derived from many inputs and you cannot enumerate what a given write affects. Trying to build a complete dependency graph here produces a system where nobody can safely add a write path. Use a short TTL and accept bounded staleness, or restructure so the cached thing has a single clear owner.
  • The cheap fix is available and you have not tried it. If a 5-second TTL makes both the load problem and the staleness problem go away, take it. A short TTL is a real cache invalidation strategy, not a placeholder for one, and it has the property that it keeps working when someone adds a write path without reading your code.
  • Writes come from outside your application - batch jobs, replication, an admin tool, operators running SQL. Application-level invalidation will miss all of these and you will have a cache that is correct in testing and wrong in production. Either move invalidation to the data layer via a change stream, or rely on TTL so the system self-heals. Detailed view of blue ethernet cables connected to a network switch in a data center.

What People Get Wrong

"If we invalidate on every write, the cache is always consistent with the database."

There is a window between the database commit and the cache delete, and another between a reader's miss and its write-back. Both are small and both are real, which is why the honest framing is a bounded staleness window rather than consistency. Invalidation makes the window short; it does not close it.

"A TTL is a lazy substitute for proper invalidation."

A TTL is an explicit, self-healing staleness contract that requires no coordination and cannot be forgotten by a future write path. Explicit invalidation is the thing that needs the backstop - which is why mature systems set a TTL on keys they also invalidate, not instead of invalidating them.

"Deleting the key is enough - we delete it, so the next read is correct."

Only if the delete reaches every copy. In-process caches in other instances, a CDN tier, a client-side cache, and a read replica that your repopulating read might hit are all places the old value can survive or be re-sourced. 'Delete the key' is a statement about one cache, not about the system.

"Invalidation is a correctness concern, so it has no performance implications."

Invalidating a hot key sends every concurrent reader to the source of truth at the same moment. Invalidation is one of the main ways a caching layer generates load spikes, which is why single-flight locks and serve-stale-while-revalidating exist at all.

Why It Was Built This Way

The design constraint is that caches were deliberately built to know nothing about your data. A cache is a key-value store that is fast because it does almost nothing: no schema, no relationships, no transactions spanning it and your database, no idea that product:42 has anything to do with a row somewhere. That ignorance is the source of the speed. The moment a cache understood your data model well enough to invalidate itself, it would need to participate in your writes, and it would start to look like a database with all the costs that implies.

So the invalidation decision was pushed out to the application, and what got traded away is any guarantee that it is done correctly. There is no mechanism that can tell you a write path forgot to invalidate. No type system catches it, no test naturally covers it, and the failure is silent and intermittent - a user reports seeing old data, you cannot reproduce it, the entry expires, and the ticket gets closed. This is the real reason cache invalidation has its reputation for difficulty. The mechanics of deleting a key are trivial. The hard part is that correctness depends on a complete, informal, human-maintained map from writes to keys, in a system where both sides keep changing.

That is what makes the TTL more respectable than it first appears. A TTL is not a weaker form of invalidation - it is a different bargain. You give up freshness within a known bound, and you get back a property nothing else offers: the system is eventually correct no matter what anybody forgets. Explicit invalidation buys freshness by taking on an obligation that grows with every new write path. The right design is usually both, with the TTL as the floor you can reason about and explicit invalidation layered on only for the keys where the stale read has a cost you can name.

Related Briefs

What to Read Next

  • cache stampede and thundering herd prevention
  • cache-aside vs write-through caching
  • eventual consistency in distributed systems

Treat invalidation as a staleness budget set per class of data, not as a single policy for your whole cache. Start with a TTL, because it is self-healing and cannot be forgotten, and add explicit invalidation only where you can name what a stale read costs. Keep the TTL in place on those keys too - it is the backstop for every invalidation that silently did not happen. And when invalidation is becoming the most complex part of your data access layer, the question to ask is whether the cache is earning its keep at all.

댓글

이 블로그의 인기 게시물

What Is a Message Queue - and When You Actually Don't Need One

What Is a Bloom Filter - and When You Actually Don't Need One

When to Use GraphQL Over REST API - and When REST Is Still the Right Call