Write-through and write-behind

Why you need it

When data is changed, both the database and the cache hold a version of it. If only one is updated, they disagree. Write strategies decide which gets the change first, and what the visitor waits for, trading speed against safety.

Think of it like this

Writing in a diary and on a sticky note. You can write in both before closing the bag (slower, both match). Or write on the sticky note now and copy it into the diary tonight (faster, but if you lose the note first, it is gone).

Where you’ll find it

What to know first

Write. Any change to data: a new price, a new post, a like.

Durable. Saved in a way that survives a crash, usually on disk in the database.

How it works

  1. The problem. You change a price. The database has the new one; the cache still has the old one. This is the first beat of the animation.
  2. Write-through: both, then "saved". Update the database and the cache, and only then tell the visitor it is saved. They always agree, and reads right after are fresh. The visitor waits for the slower one, the database.
  3. Write-behind: cache now, database later. Update the cache, say "saved" at once, and write to the database a moment later, often in batches. Very fast. But if the cache dies before it writes, those changes are lost.
  4. Write-around: database only. Write only to the database and delete the copy (see Invalidation and TTL). The next read fills the cache. This is the usual partner of Caching (cache-aside).
  5. Choosing. Money, orders, anything you cannot lose: write-through or write-around. View counts, likes, game scores, where losing a few is fine and speed matters: write-behind is tempting.

An example

The database takes 20 ms to save; the cache 1 ms.

Write-through: each save takes about 21 ms, and the copy is always right.

Write-behind: each save takes 1 ms. A view counter gets 10,000 updates a second, and they reach the database as one batch per second instead of 10,000 writes.

If the cache crashes, write-behind loses up to one second of views. For a view counter that is fine; for payments it is not.

Further reading

  • Caching strategies, AWS ElastiCache docs. Lazy loading against write-through, with the trade-offs of each. Start with this one.
  • Cache writing policies, Wikipedia. The same ideas as they appear in hardware, with a clear diagram.