Caching

Cache invalidation

Why keeping a cache in step with the database is hard, which write-path choices cause stale data, and what TTLs, deletes, versioned keys and change data capture can each guarantee.

Lesson14 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A user changes their display name and saves. The page reloads and shows the old name. They save again. Ten minutes later the new name appears, and by then they have filed a bug.

The team traces it to a profile cache with a ten-minute TTL and no invalidation. They shorten the TTL to ten seconds, which cuts the hit ratio and still shows the old name on the reload. They change the save handler to overwrite the cache entry, and a month later find profiles that are stuck on an old value. They switch to deleting the entry, and it happens less often, but it still happens.

A line widely attributed to Phil Karlton says there are only two hard things in computer science: cache invalidation and naming things. The difficulty is real, and it has specific causes. This lesson covers those causes and the usual tools for dealing with them.

Why it is hard

  1. Two systems, no shared transaction. The database write and the cache operation cannot commit atomically. Either can fail, and the process can crash between them.
  2. Concurrency. Requests interleave. A sequence that is correct for one request at a time can go wrong when a reader and a writer overlap.
  3. Fan-out. One row feeds many cached values. A display name appears in the profile, in every comment list and in search results. Knowing which keys to invalidate is its own problem.

TTLs: the safety net

Give every entry a TTL. A TTL is the only mechanism that needs no cooperation: whatever went wrong, the wrong value has a maximum lifetime.

Choose it from two questions. How long may a reader see old data before it matters? How expensive is a miss? A product description can live for an hour. A price that is shown but re-checked at checkout might live for a minute. Add jitter so that keys do not expire together, as covered in Cache stampede and thundering herd.

A TTL alone is enough when staleness of that length is acceptable. It is not enough when users edit data and expect to see their edit.

Delete or update on write

Updating the cache entry in the write path looks attractive, because the next read is a hit. From application code it is unsafe. Writer 1 commits x = 1, writer 2 commits x = 2, writer 2 sets the cache to 2, and then writer 1’s delayed call sets it to 1. The database says 2 and the cache says 1. Cached values are also often derived, such as a join or a rendered fragment, so “the new value” is extra work that may never be read.

Deleting the key is safer. Deletes give the same result in any order and can be retried freely. The cost is one miss after each write.

Order matters too. Write the database, then delete. If you delete first, any reader that arrives before the commit misses, reads the old row and re-caches it, and nothing removes it afterwards. That interleaving is ordinary traffic, not bad luck.

The race that remains

Even “write, then delete” has a gap.

The stale write race in cache-aside4 components: Request A, Cache, Database, Request B. Connections: Request A to Cache (GET, then SET); Request A to Database (read on a miss); Request B to Database (1. write); Request B to Cache (2. delete).Request Areads user 42Cacheuser:42 is absentDatabaseuser:42 is v1Request Bupdates user 42GET, then SETread on a miss1. write2. delete

Step 1 of 8

The cache uses cache-aside with delete on write. The database holds version 1 of user 42, and the cached copy has just expired. Two requests arrive close together. Request A reads the user and request B updates it.

Read the steps as text
  1. The cache uses cache-aside with delete on write. The database holds version 1 of user 42, and the cached copy has just expired. Two requests arrive close together. Request A reads the user and request B updates it.
  2. Request A asks the cache for user 42 and gets a miss.
  3. Request A reads the database and gets version 1. Before it can store that value in the cache, A is delayed. A garbage collection pause, a slow network hop or a busy thread is enough.
  4. Meanwhile request B writes version 2 to the database and commits.
  5. Request B then deletes the cache key, as the pattern says it should. The key is not there, so the delete does nothing. B has done everything right.
  6. Request A wakes up and finishes its job. It stores what it read earlier, which is version 1.
  7. The database says version 2 and the cache says version 1. Nothing will correct it, because no write is pending and no delete is coming. Every reader gets the old value until the time to live runs out.
  8. The race needs a miss, a concurrent write and an unlucky pause, so it is rare, but a busy system will hit it. A time to live limits how long the damage lasts. A lease or a version check makes the cache reject the stale SET.
The stale write race in cache-aside

With a single database this needs a miss, a concurrent write and a reader slow enough to straddle both the commit and the delete. It is rare, though a busy system will see it.

A second variant is much more common. If misses are filled from a read replica, a reader can fetch the old row from a replica that has not yet applied the write, and cache it. The window is the whole replication lag.

A third failure is simpler still: the write commits and the delete never happens, because the call timed out or the process died.

The usual defences:

  • A TTL limits how long any of these last.
  • Delayed double delete. Delete, then delete again after a delay longer than the replication lag, often about a second. It is simple and a heuristic.
  • Leases or version checks. Facebook’s memcache gives a reader a lease token on a miss, and a delete invalidates the token, so the late SET is rejected. Without leases, store a version with the value and only accept a SET that carries a newer one.
  • Fill from the primary for a short time after a write to that key.

Versioned keys

Another approach avoids invalidation entirely: never change a cached value. Put a version in the key, such as user:42:v17, or a hash of the content. A change produces a new key. Nothing is deleted, and old keys are simply never asked for again and age out through their TTL or eviction.

Because old and new values live under different keys, a late writer cannot overwrite new data with old.

The catch is that a reader must know the current version before it can build the key. That pointer usually comes from the database row itself, such as an updated_at column, which is the “key-based expiration” approach popularised by Rails. Or it is a small counter in the cache, bumped with an atomic increment. A version in a key prefix, such as catalog:v8:product:7, invalidates a whole group at once when the prefix is bumped. That also empties the whole group at once, so plan for the reload.

Choose versioned keys when values are expensive, shared and change rarely. They fit less well when a reader would need an extra lookup just to learn the version. Fingerprinted assets on a CDN are the same idea.

Event-driven invalidation with CDC

Deleting from application code only covers writes that go through that code and whose delete succeeds. Admin scripts, migrations, other services and crashed requests are all missed.

Change data capture (CDC) invalidates from the database’s own commit log. A connector such as Debezium tails the PostgreSQL write-ahead log or the MySQL binlog and publishes each change to a stream. A consumer maps the changed row to cache keys and deletes them.

Invalidating the cache from the database's change log6 components: App servers, Cache, Database, Invalidator, CDC connector, Change stream. Connections: App servers to Cache (read, fill on a miss); App servers to Database (1. write); Database to CDC connector (2. committed changes); CDC connector to Change stream (3. change events); Change stream to Invalidator (4. consume); Invalidator to Cache (5. delete keys).App serversCacheDatabasesource of truthInvalidatormaps rows to cache keysCDC connectortails the WAL or binlogChange streamfor example Kafkaread, fill on a miss1. write2. committed changes3. change events4. consume5. delete keys
Invalidating the cache from the database's change log

Every committed change is seen, whoever made it. Delivery is at least once, which is safe because deletes are idempotent. The costs are a delay, usually milliseconds to seconds, between the commit and the delete, plus a pipeline to operate and a mapping from rows to keys to maintain. The Facebook paper describes this shape too: a daemon reads the MySQL commit log and sends the deletes.

Choose CDC when several services write the same data or a missed delete is costly. Do not choose it when one service owns every write and a TTL-length mistake is tolerable, because the pipeline is one more system to run. Many teams do both: delete inline for speed, with CDC as the backstop.

What you can and cannot promise

Approach Staleness in the worst case Choose it when
TTL only The TTL Old data is harmless for that long
Write, then delete, plus TTL Usually milliseconds, the TTL if a race or failure hits Users see their own edits. The default
Versioned keys As fresh as the version pointer Expensive, shared, rarely changing values
CDC plus TTL Pipeline lag, the TTL if the pipeline stalls Many writers, or missed deletes are not acceptable

A cache built this way offers eventual consistency with bounded staleness. With extra work it can offer read-your-writes for the author, for example by reading the primary for a few seconds after their own write. Consistency models defines these terms.

It cannot offer linearizability. That would need the cache and the database to commit together, and a cache that takes part in every commit is no longer a cache. So do not make correctness decisions from cached data. Check stock, balances and revoked permissions against the source of truth, or make the write conditional in the database.

In the interview

When you add a cache, expect “how do you keep it consistent?” as the next question. Answer in layers: a TTL on everything, database write followed by a delete, then name the race that remains and one way to close it. Offer CDC when there are several writers or the interviewer pushes on missed deletes.

Then state the guarantee plainly. “Readers may see data up to a few hundred milliseconds old, and up to the TTL in a failure. Checkout does not read the cache.” Candidates who claim the cache is always consistent lose more credit than those who say exactly how stale it can be.

Key takeaways

  • A cache and a database cannot be updated atomically, so some window of staleness always exists. The design question is how long and how it ends.
  • Put a TTL on every entry. It is the only mechanism that still works when every other one has failed.
  • Write the database first, then delete the cache key. Deleting first, or setting the new value from application code, both create common races.
  • Delete-on-write still has a rare race in which a slow reader re-inserts an old value. Leases, version checks or a delayed second delete close most of it.
  • Versioned keys avoid invalidation by never changing a cached value. A change produces a new key and the old one ages out.
  • Change data capture invalidates from the database's own log, so it sees every committed write, including ones the application missed.
  • Promise bounded staleness, not strong consistency. Decisions that must be correct read the source of truth.

Check yourself

1. Two requests update the same row. Each writes the database and then SETs the new value in the cache. Which outcome is possible?
2. Why is "delete the cache key, then write the database" worse than the reverse order?
3. An application writes to the primary and deletes the cache key. Reads that miss are served from a replica that lags by 200 ms. What can go wrong?
4. A team uses key-based versioning, with keys such as user:42:v17. What do readers need for this to work?
5. What does invalidation driven by change data capture give you that deleting from application code does not?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

In cache-aside, what order should a write use, and why?

Write the database first, then delete the cache key. Deleting first lets a concurrent reader re-cache the old value, which then survives the write.

Why delete the key on write instead of setting the new value?

Concurrent writers can set the cache in a different order from their database commits, leaving the older value. A delete gives the same result in any order, and avoids computing values nobody reads.

Describe the stale-set race that remains with delete-on-write.

A reader misses and reads the old row. A writer commits and deletes the key. The reader then stores the old value. It stays until the TTL unless a lease or version check rejects the set.

What is a versioned (key-based) cache key?

A key that includes a version or content hash, such as user:42:v17. Values are never updated. A change creates a new key and the old one is left to expire.

How does CDC-based invalidation work?

A connector tails the database's commit log (WAL or binlog) and publishes change events. A consumer maps each changed row to cache keys and deletes them, with retries.

What consistency can a cache-aside design promise?

Eventual consistency with staleness bounded by the TTL in the worst case and usually milliseconds. Not linearizability. Read-your-writes needs extra work such as reading the primary after your own write.

Review the deck