Course contents

06. Caching Lesson 7 of 8

Cache Invalidation

Keep cached data correct: the TTL staleness trade-off, delete-on-write, the read/delete race, versioned keys and CDC-driven invalidation.

16 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A cache is a copy; it does not see writes unless you tell it or it expires.
  • A TTL bounds staleness on every key, paid for with misses on keys that never changed.
  • Delete the key after commit; deleting avoids the ordering races of updating.
  • A read that started before a write can cache the old value after the delete; versioned keys, leases and the TTL handle it.
  • CDC invalidates from the commit log, so no writer can forget; its lag is a short stale window.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. The database changed, the cache did not

    Shoppers read prices at 600 requests per second through a cache-aside Catalog API. The cache has room for every product and no TTL, so about nine in ten reads are hits.

    The Pricing service raises product 42 from €20 to €25 in the database. Nobody tells the cache. The next shopper’s read is a hit and gets €20, and so will every read after it, forever: a cache without expiry or invalidation never notices a change.

    The write and the stale read are a scripted illustration; the background traffic is simulated.

    Scene: The Pricing service writes a new price to the database. A shopper then reads the same product through the Catalog API and gets the old price from the cache, which has no TTL. About nine in ten reads are cache hits.

    Key idea: A cache is a copy. Unless something removes or expires it, a copy stays wrong after the source changes.

  2. 2. A TTL bounds the damage

    We give every entry a 5-second TTL. A stale price now lives at most about 5 seconds after the write before the entry expires and the next read reloads it. The cache still knows nothing about writes; it just forgets on a timer.

    The price: every key expires, changed or not. The hit ratio drops from about 89% to roughly 77%, and the database gets more than twice the reads (about 15% → about 35% busy).

    Scene: Cache entries now expire after 5 seconds. About 77% of reads hit; the database handles noticeably more reads than before.

    Key idea: The TTL is the maximum staleness you accept, paid for with misses on every key.

  3. 3. Fresher by timer gets expensive

    Marketing wants price changes visible "immediately", so the TTL drops to 0.5 seconds. Staleness is now bounded by half a second, but only about half of reads hit and the database goes to roughly 75% busy, about twice the load of the 5-second TTL.

    And it is still not immediate. Most prices change once a week, yet every key is reloaded twice a second. A timer cannot know *which* keys changed; only the write path knows that.

    Scene: Entries expire after half a second. Only about half of reads hit and the database is around 75% busy.

    Key idea: Shrinking the TTL buys freshness linearly and costs load on every key, including the ones that never change.

  4. 4. Delete the key when you write

    Better: the writer tells the cache. After committing the new price, the Pricing service deletes price:42 from the cache. The next read misses, loads €25 from the database and caches it. The TTL goes back up to 60 seconds, now only a backstop for a delete that gets lost.

    Delete, don’t update: two writers that each SET their value can reach the cache in the opposite order to the database and leave the older value behind; a delete just forces a fresh read. With the long TTL the hit ratio is back near 85–90% and the database is quiet.

    The write and delete are a scripted illustration; reads are simulated.

    Scene: The Pricing service writes the new price, then deletes the cache key. The next read misses, loads the new price from the database and stores it. The TTL is 60 seconds; most reads hit the cache again.

    Key idea: Invalidate on write (delete after commit), and keep a TTL as a safety net for missed deletes.

  5. 5. A slow reader puts the old value back

    Delete-on-write still has a race. Follow the numbers:

    ① A read misses. ② It loads €20 from the database, then stalls (a GC pause, a slow network). ③ The Pricing service writes €25. ④ It deletes the key, which is not there yet. ⑤ The stalled reader finally SETs €20. Every read after that gets the old price until the 60-second TTL expires.

    The window is small, so it is rare per write, but with millions of writes it happens. This is a scripted illustration of the interleaving.

    Scene: An illustration of the race: a read misses and loads the old price, the Pricing service then writes the new price and deletes the key, and only afterwards the slow reader stores the old price in the cache, where later reads find it.

    Key idea: A read that started before a write can finish after its delete and cache the old value: the TTL is what finally fixes it.

  6. 6. Put the version in the key

    One fix is to make old values unreachable instead of deleting them. The product row carries a version that every write increments, and the cache key includes it: price:42:v7, then price:42:v8.

    Now the stalled reader’s late SET writes price:42:v7, a key nobody asks for any more. New reads ask for v8, miss once, load €25 and cache it. The orphaned v7 entry just ages out through LRU or its TTL. The cost: readers must know the current version (it comes with the row or a tiny version lookup), and orphans use memory until they are evicted.

    A related fix is a lease: on a miss the cache hands out a token, a delete invalidates it, and a SET with a stale token is refused. Both are scripted here.

    Scene: An illustration of versioned keys: the write bumps the product to version 8. A late store of the old price lands on the version 7 key, which nobody reads; new reads ask for version 8, miss once, load the new price and cache it.

    Key idea: Versioned keys turn a late stale write into a harmless orphan: nobody reads the old version again.

  7. 7. Invalidate from the database’s change log

    Deletes in application code only work if every writer remembers them. A bulk import, a migration or a hand-written SQL fix will not. Change data capture (CDC) moves invalidation out of the writers: a connector (Debezium, for example) reads the database’s commit log (the WAL or binlog), publishes each change to a topic, and an Invalidator deletes the affected keys.

    Every committed write, from any writer, now triggers a delete. The delay is the pipeline’s lag, usually milliseconds to seconds, so there is still a short stale window. Delivery is at-least-once, which is fine: deleting a key twice is harmless.

    The pipeline is a scripted illustration.

    Scene: A bulk import and the Pricing service both write to the database. A CDC connector reads each commit from the log and publishes it to the price-changes topic; an Invalidator consumes it and deletes the key from the cache.

    Key idea: CDC-driven invalidation covers every writer, because it reacts to commits instead of trusting application code.

  8. 8. Layers of invalidation

    No single mechanism is enough. A practical stack: delete on write (or CDC so no writer can forget), versioned keys or leases where a stale value is costly, and a TTL backstop sized to the staleness you can live with.

    Decide per data type: a product description can be minutes stale, a price shown at checkout should be re-read from the source. Measure staleness (compare a sample of cached values with the database) instead of assuming invalidation works.

    Scene: The full picture: shoppers read through the Catalog API and a cache with a 60-second TTL; writes reach the cache as deletes through the CDC pipeline. Most reads hit and nothing fails.

    Key idea: Invalidate on change, bound the leftovers with a TTL, and re-read the source where correctness matters.