What it is
Cache invalidation is everything that keeps a cache from serving data the source of truth no longer holds. A cache entry is a copy taken at some moment; when the database changes, the copy is wrong until it expires (TTL), is removed (delete on write, CDC), or becomes unreachable (versioned keys). Phil Karlton’s quip that it is one of the two hard things in computer science is about the timing: deciding when a copy stops being valid, across processes that run concurrently.
Why it exists
Caches are fast because they do not consult the database. The same property means they cannot notice a change by themselves. Without invalidation a cache with no TTL serves the old value forever; with only a TTL it serves it for up to the TTL. Whether that matters depends on the data: a stale product description for a minute is fine, a stale price at checkout or a revoked permission is not.
How it works
TTL. Every entry expires after a fixed time. Worst-case staleness is roughly the TTL (plus any in-flight read). It needs no coordination, but it reloads every key on schedule, changed or not, so a short TTL lowers the hit ratio and raises database load. In the lesson’s model, TTLs of none / 5 s / 0.5 s gave hit ratios of about 89% / 77% / 50%.
Delete on write. After the database commit, the writer deletes the key; the next read misses and loads the fresh value. Delete rather than update: two writers that SET their values can reach the cache in the opposite order to their commits and leave the older value cached. Delete after commit, not before, or a concurrent read can reload the old row in between. Keep a TTL as a backstop for deletes that fail.
The read/delete race. ① A read misses. ② It loads the old value. ③ A writer commits the new value. ④ The writer deletes the key, which is not there yet. ⑤ The reader stores the old value. Now the cache is stale until the TTL expires. The window is short (a GC pause, a slow network), but at high write rates it happens.
Versioned keys. Include a version in the key (price:42:v8) that each write increments, for example a row version column. A late SET of the old value writes price:42:v7, which no reader requests; it ages out by LRU or TTL. Readers must learn the current version (it often comes with the row or a parent object), and orphaned versions use memory until evicted.
Leases. On a miss, the cache gives the reader a token; a delete invalidates outstanding tokens; a SET with an invalid token is refused. This is the approach described for Facebook’s memcache deployment (NSDI 2013); leases also limit stampedes by letting only one token holder refill a key.
Delayed double delete. Delete after commit, then delete again a little later (say a second) to catch a late stale SET. It narrows the window rather than closing it, and the delay is a guess.
CDC-driven invalidation. A change-data-capture connector (Debezium, AWS DMS, a database’s logical replication) reads the commit log (PostgreSQL WAL, MySQL binlog), publishes each change to a topic, and an invalidator deletes the affected keys. It covers every writer, including bulk imports, migrations and manual SQL. Delivery is usually at-least-once and ordered per key or partition; deletes are idempotent, so duplicates are harmless. The lag of the pipeline, typically milliseconds to seconds, is a stale window.
When to use it
- TTL only: data where bounded staleness is acceptable and writes are frequent or untracked (aggregates, recommendations).
- Delete on write + TTL: the default for entities owned by one service with a clear write path.
- Versioned keys or leases: hot keys with frequent writes where a stale value is costly.
- CDC: many writers, shared databases, or legacy writers you cannot change.
When not to
- Don’t cache data that must always be current (balances, inventory reservations, authorization decisions) unless you re-check the source on the critical path.
- Don’t rely on a very short TTL as your invalidation strategy for large key sets; it turns the cache into a load generator.
- Don’t add CDC for one service with one write path; delete-on-write is simpler.
Trade-offs
| Technique | Staleness | Cost | Weak spot |
|---|---|---|---|
| TTL | Up to the TTL | Misses on every key, changed or not | Short TTLs overload the database |
| Delete on write | Small window | Code on every write path | Forgotten writers; read/delete race |
| Update on write | Small window | Code on every write path | Concurrent writers reorder values |
| Versioned keys | None from late writes | Version lookup; orphaned entries | Readers must know the current version |
| Leases | None from late writes | Cache support needed | Not built into most managed caches |
| CDC | Pipeline lag | Connector, topic, consumer to operate | Lag spikes; schema-to-key mapping |
Alternatives
- Write-through: write the cache and the database in the same path, keeping the cache current for that writer (still racy with other writers).
- Read from the source where it matters: show cached prices on listing pages, re-read at checkout.
- Short-lived local caches with a longer shared cache behind them, each with its own TTL.
- Push-based invalidation: publish an explicit "product changed" event from the service (often via a transactional outbox) instead of reading the database log.
Failure modes
- Lost deletes: the delete call fails or the process crashes between commit and delete; the TTL is the only recovery. A transactional outbox or CDC makes the invalidation durable.
- Stale write-back after a delete: the read/delete race above.
- Invalidation storms: a bulk update deletes thousands of hot keys at once, and the following misses stampede the database.
- Replica lag: the invalidated reader reloads from a lagging read replica and caches the old value again. Reload from the primary after a write, or delay the delete by more than the lag.
- Key mapping drift: CDC knows rows, the cache stores views (a product page combines several tables); a missed mapping leaves some views stale.
In production
Choose staleness per data type and write it down. Delete after commit, keep a TTL with jitter on every key, and alert on failed deletes. Watch for read replicas in the reload path. For many writers, invalidate from CDC or an outbox. Measure staleness directly by sampling cached values and comparing them with the database; "we invalidate on write" is a claim, not a metric.
Common misconceptions
- "With delete-on-write, the cache is always consistent." A slow read can still store the old value after the delete.
- "A short TTL is a cheap way to be fresh." It reloads every key, changed or not, and is still stale for up to the TTL.
- "Updating the cache on write is as good as deleting." Concurrent writers can leave the older value behind.
- "CDC makes invalidation instant." It makes it complete; the pipeline lag is still a stale window.
Interview angle
Interviewers ask "how do you keep the cache consistent?" Strong answers name the staleness each data type can accept, then layer: delete after commit, TTL backstop, and either versioned keys or leases for the read/delete race. Expect follow-ups on multiple writers (CDC or an outbox), replica lag in the reload path, and bulk updates causing stampedes. Drawing the five-step race and explaining exactly where it breaks is a strong signal.
Model assumptions
The simulation is a simplified model, not a benchmark. Shoppers read 2,000 product prices with Zipf(1) popularity at 600 requests per second through a cache-aside Catalog API (64 workers). The cache has room for every key, so only the TTL limits hits; an expired key counts as a miss and is reloaded from the database. The database has 8 connections and a 20 ms mean read (lognormal), about 400 reads per second. The engine models only reads: it does not model writes changing values or deletes removing keys. The stale read, delete-on-write, the race, versioned keys and the CDC pipeline are scripted illustrations drawn on top of the simulated read traffic; their timings are for readability, not measurements. The hit-ratio tile counts all lookups since the simulation started; the numbers in the steps are measured after warm-up. Numbers show behaviour and orders of magnitude only.