Video in progress
When data changes, do you update the DB first and then delete the cache entry, or the other way around? Why?
Usually you write to the DB first, then delete the cache entry (not update it). In the opposite order, another request can put the old value back into the cache between the delete and the DB write, and it stays until the TTL runs out.
📖 Answer
The race in the "delete the cache first" variant:
1. Writer: DEL product:5
2. Reader: GET -> miss, reads the old price from the DB
3. Writer: UPDATE price (DB)
4. Reader: SET product:5 <old price> // the old value stays for 10 minutes
"DB first, then DEL" has a race too, but it's much rarer: the reader would have to get a miss, read the old value from the DB, and then do its SET after the writer's UPDATE + DEL. A DB read is usually faster than a write, so the window is narrow.
Why delete and not update? Two parallel writers can SET the cache in the opposite order, leaving value B in the DB and value A in the cache. With a delete, that can't happen.
Extra protection:
- run the
DELafter the commit; - always set a TTL, which caps any inconsistency;
- in critical places, a delayed second
DEL(delayed double delete), or listening to DB changes through CDC (Debezium) and clearing the cache from that.
If the DEL fails with a Redis error, you need a retry or a queue, otherwise the stale value lives until the TTL runs out.
Sign up to mark studied questions and save your progress.