Skip to content

Cache invalidation and stampedes

Deep diveConcept

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.

Where a stale read comes from
CauseHow long it lasts
No invalidation, TTL onlyUp to the TTL after every change
A delete that failed or was never sentUntil the TTL, or forever without one
Two writes or a read and a write racingUntil the next write or the TTL
A delete that ran before the write committedUntil 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.

Set on write: two writers finish in the wrong order
Step 1 of 5
Database
user:42→Ana
Cache (Redis)
user:42→Ana
Who is doing what
W1 · Ann
W2 · Anna
  • 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.

Delete on write: a slow reader puts old data back
Step 1 of 6
Database
user:42→Ana
Cache (Redis)
Empty
Who is doing what
Reader
Writer · Ann
  • 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:

Delete cache, then write DBWide windowAny reader during the write misses, reads the old row and refills the cache with it. The delete achieved nothing.
Write DB, then delete cacheNarrow windowOnly the slow-reader race above is left. Delete after the transaction commits, not inside it.
  • 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.

Ways to get invalidations to the cache
ApproachHow it worksWatch out for
Delete in the appAfter each commit, the code that wrote deletes the keys it changedWrites from anywhere else are never invalidated
Follow the database logA process tails the write-ahead log or binlog (for example with Debezium) and deletes keys for each changed rowA small delay, and one more system to run
Versioned keysReaders look up the current version (`user:42:v8`); a write bumps it, and old keys simply expireOne extra lookup per read, and memory held by dead versions until they expire
TTL onlyNo invalidation; accept data up to the TTL oldUsers 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.

A popular key expires: every miss goes to the database
Step 1 of 8
Requests for the home feed
r1
r2
r3
r4
r5
Cache
Empty
Database queries
Empty
  • 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.

0 DB queries

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.

The same expiry, with a rebuild lock
Step 1 of 7
Requests for the home feed
r1
r2
r3
r4
r5
Cache
Empty
Database queries
Empty
  • 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.

0 DB queries
feed.js
// redis is a node-redis client; db.loadFeed() runs the slow query.
async function getFeed() {
for (let tries = 0; tries < 20; tries++) {
const cached = await redis.get('feed:home');
if (cached) return JSON.parse(cached);
// NX: only set if absent, so exactly one caller wins. PX: the lock
// expires by itself after 5 s, even if the winner crashes.
const won = await redis.set('lock:feed:home', '1', { NX: true, PX: 5000 });
if (won) {
const feed = await db.loadFeed();
const ttl = 60 + Math.floor(Math.random() * 10); // jitter: 60–69 s
await redis.set('feed:home', JSON.stringify(feed), { EX: ttl });
await redis.del('lock:feed:home');
return feed;
}

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.

Text
$ node stampede.js
naive: 100 requests, database queries: 100
with lock: 100 requests, database queries: 1
Other ways to blunt a stampede
TechniqueIdeaGood for
Serve stale while refreshingKeep the old value past its soft expiry; one request refreshes it in the background while others get the old copyData where a few seconds old is fine; HTTP has it as `stale-while-revalidate`
Refresh early, at randomEach read may refresh slightly before expiry, more likely the closer it gets, so one request usually does it firstHot keys with costly rebuilds, without a lock
Jitter the TTLAdd a random few seconds to each TTLMany keys written together that would otherwise expire together
Coalesce in the processConcurrent misses in one server share one in-flight promiseCutting 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.

08 Check yourself

Question

Your write path updates the database, then calls redis.set(key, newValue). Two users edit the same record at the same moment. What can happen?

Question

Why is "delete the cache key, then write the database" worse than the other way round?

Question

A key is read 2,000 times a second and takes 500 ms to rebuild. It expires, and nothing protects it. About how many rebuilds start before the first one finishes?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?