Video in progress

In cache-aside, even "update the DB first, then delete the cache entry" can leave a stale value. In what sequence does this happen, and what do you do?

A reader misses the cache and reads the old value from the DB. Meanwhile the writer updates the DB and deletes the cache entry, and then the reader writes the old value into the cache, where it stays until the TTL runs out. Mitigations: a short TTL, a delayed second delete, versioned writes, or CDC-based invalidation.

📖 Answer

The sequence (A is the reader, B is the writer):

  1. A: user:7 isn't in the cache, so it reads from the DB: name = Ali.
  2. B: sets name = Vali in the DB, commits.
  3. B: DEL user:7.
  4. A: writes Ali into the cache.

Now the cache serves the old value for 30 minutes. This is rare (A's DB read has to be slower than B's entire write), but under high load and with GC pauses it really does happen.

Why "delete the cache first, then the DB" is worse: the window between the delete and the commit is much larger, and the reader almost always manages to write the old value back.

The solutions used in practice:

  • Always have a TTL. This is the last line of defense: the mistake doesn't stay forever.
  • Delayed double delete: you delete after the commit and delete again after 0.5-1 seconds (through a scheduled task or a queue). It's simple and covers many cases.
  • A conditional write with a version: you write the DB version into the cache along with the value, and with a Lua script only a newer version can replace an older one.
local cur = redis.call('HGET', KEYS[1], 'v')
if (not cur) or tonumber(cur) < tonumber(ARGV[1]) then
  redis.call('HSET', KEYS[1], 'v', ARGV[1], 'data', ARGV[2])
  redis.call('PEXPIRE', KEYS[1], ARGV[3])
end
  • Invalidation from CDC: Debezium reads the change from the binlog/WAL and deletes the cache entry. The application code gets simpler and no write path gets forgotten.

An important nuance: do the delete after the transaction commits. In Spring, that's @TransactionalEventListener(phase = AFTER_COMMIT). Otherwise you delete the cache entry even when the transaction rolls back, or, worse, you delete it before the commit and pull the old value back in.