~learn.
0:00 / 1:27
W04 · Caching

Two price updates. The database is right. The cache is wrong.

transcript

Two price updates hit at once. The database ends up right. The cache ends up wrong. And it stays wrong.

On a write, you update the database. Then you update the cache. Sounds smart. The next read is a hit. Now watch two requests.

Both read 100 dollars. A writes 90 to the database. Then B writes 80. B was last, so the database correctly says 80. B updates the cache first. 80. Still fine. Then slow A updates the cache. 90. Wrong.

The database commits landed in order. The cache writes didn't. So the fix sounds backwards. Don't update the cache at all.

With write-update, a late write overwrites the right one. Instead, both requests just delete the key. A's late delete? Harmless. Deleting twice is the same as once. The next read misses, and loads 80 from the database.

One race remains. A reader loads the old row just before the update. Then it sets that old row after the delete. The TTL bounds that window. Leases, like Facebook's, close it.

Update only with one writer per key, or atomic ops like INCR. Everything else: on a write, delete the cache entry. Don't update it.

Full breakdown in the lecture.