Cache invalidation and stampedes
You update a row, and users keep seeing the old value; or a popular key expires and the database falls over. Both come from the moment a cached copy stops being right. Here are the races behind stale reads, why you delete rather than update, and how to stop a thousand misses arriving at once.
01 Two copies, one truth
A cache holds a copy of data whose real home is the database. The moment the database changes, the copy is wrong, and it stays wrong until something removes or replaces it. That is all invalidation means: making sure a wrong copy does not live for long.
There are only two tools. A TTL throws the copy away after a fixed time, whatever happened. An explicit invalidation removes it when the data changes. A TTL alone means every change is invisible for up to the TTL; explicit invalidation alone means any missed or mistimed delete leaves a wrong value forever. Real systems use both, and the trouble is in the timing.
| Cause | How long it lasts |
|---|---|
| No invalidation, TTL only | Up to the TTL after every change |
| A delete that failed or was never sent | Until the TTL, or forever without one |
| Two writes or a read and a write racing | Until the next write or the TTL |
| A delete that ran before the write committed | Until the TTL |
02 Why setting the cache on a write goes wrong
The tempting way to keep the cache fresh is to write the new value into it right after the database. It works with one writer. With two writers on the same key, nothing makes their cache writes happen in the same order as their database writes.
- not started
- acting now
- paused
- just written
- unchanged
User 42 is called Ana in the database and in the cache. Two requests are about to rename her at nearly the same moment: W1 to Ann, W2 to Anna.
The database ordered the writes correctly; the cache did not, because two separate steps are not one atomic step. Deleting the key instead removes the order problem for writers: two deletes in either order leave the same empty key, and the next read loads whatever the database holds.
03 Delete on write, and the race that remains
Deleting fixes racing writers, but a reader still fills the cache on a miss, and a reader can be slow too.
- not started
- acting now
- paused
- just written
- read
The writers now delete the key instead of setting it. The cache is empty for user 42 (it expired a moment ago); the database says Ana.
This needs a miss, a read that starts before the write and a cache fill that lands after the delete, all on one key. It is rarer than the set race, because a database read is usually far quicker than a write plus a delete. On a busy key it still happens. The order of the two write steps matters more:
- Always set a TTL. It is the backstop that ends every stale value, whatever caused it. Short for data that changes, longer for data that rarely does.
- Leases. In the design described in the paper Scaling Memcache at Facebook (NSDI 2013), a miss returns a lease token, and a delete cancels outstanding tokens. A fill that arrives with a cancelled token is refused, which closes exactly the race above.
- Versions. Store a version number with the value, and fill or update only when yours is newer, checked atomically in a Lua script. An old read can no longer overwrite a newer value.
- A second, delayed delete. Delete again a moment later, say a second. Cheap and common, but it narrows the window rather than closing it.
04 Who sends the invalidation
So far the code that writes the database also deletes the key. That is the simplest setup, and it misses every write that does not go through that code: a migration, a script, another service sharing the table.
| Approach | How it works | Watch out for |
|---|---|---|
| Delete in the app | After each commit, the code that wrote deletes the keys it changed | Writes from anywhere else are never invalidated |
| Follow the database log | A process tails the write-ahead log or binlog (for example with Debezium) and deletes keys for each changed row | A small delay, and one more system to run |
| Versioned keys | Readers look up the current version (`user:42:v8`); a write bumps it, and old keys simply expire | One extra lookup per read, and memory held by dead versions until they expire |
| TTL only | No invalidation; accept data up to the TTL old | Users see their own changes late |
Following the log is what large deployments tend to do: every committed change is in the log, whoever made it, and in commit order. The Facebook paper above describes daemons that read MySQL's commit log and broadcast the deletes to every cache region.
A value cached in many places needs the delete in every one. An in-process cache on each of 20 app servers is 20 copies; deleting the Redis key fixes none of them. Broadcast invalidations (for example with Redis pub/sub) or keep local TTLs to a few seconds.
05 A thousand misses at once
Invalidation has a second cost. Removing a key, by a delete or a TTL, turns the next read into a miss. For a quiet key that is one database query. For the hottest key on the site, every request that arrives while the first rebuild is running misses too. This is a cache stampede, also called a thundering herd or dog-piling.
- not arrived yet
- missed, querying
- just added
- served
feed:home has just expired. It is the most-read key on the site, and five requests arrive within a few milliseconds of each other. A database query for the feed takes about 200 ms.
The database gets a sudden burst of identical, often expensive queries at exactly the moment the cache stopped protecting it. If that slows the queries down, the rebuild takes longer, more requests pile in, and the load can feed on itself.
06 Let one request rebuild the key
The fix is to make sure only one caller rebuilds a key while the rest wait for its result. In Redis, SET key value NX PX ms sets a key only if it does not exist and gives it an expiry, which makes a small lock.
- not arrived yet
- loading
- waiting
- just added
- deleted
- served
The same five requests, the same expired key. This time a miss first tries to take a lock: SET lock:feed:home 1 NX PX 5000.
A real run against a local Redis 8, with a fake query that sleeps 200 ms: 100 calls at once to plain cache-aside, then 100 to getFeed(). The small harness that fires them is not shown.
| Technique | Idea | Good for |
|---|---|---|
| Serve stale while refreshing | Keep the old value past its soft expiry; one request refreshes it in the background while others get the old copy | Data where a few seconds old is fine; HTTP has it as `stale-while-revalidate` |
| Refresh early, at random | Each read may refresh slightly before expiry, more likely the closer it gets, so one request usually does it first | Hot keys with costly rebuilds, without a lock |
| Jitter the TTL | Add a random few seconds to each TTL | Many keys written together that would otherwise expire together |
| Coalesce in the process | Concurrent misses in one server share one in-flight promise | Cutting the herd to one query per server, with no Redis round trip |
07 When invalidation bites
DEL inside BEGIN … COMMITDeleting before the commitA reader between the delete and the commit misses, reads the old row and caches it. Delete after the transaction commits.try { await redis.del(k) } catch {}Swallowing a failed deleteThe database moved on and the cache did not, until the TTL. Retry the delete, or let a log follower do it.feed:home, count:posts, user:42Derived keys nobody deletesOne row can feed many keys: a list, a count, a page. Deleting user:42 leaves the others stale. Keep a map from each row to the keys built from it, or give derived keys short TTLs.SET user:99 "null" EX 600Cached "not found"Caching misses protects the database from lookups of missing keys, but when user 99 is created, that cached "null" must be deleted too.EX 3600 on 1M keys at deployEverything expires at onceKeys warmed together with one TTL go cold together, a stampede across the whole cache. Add jitter.