Module 4 · Caching and performanceLesson 36 of 886 minIntermediate

Write-through vs write-back

Write-through saves to the cache and the database together. Write-back saves to the cache now and the database later, which is faster but riskier.

Try it

Compare how long the app waits in each tab, then play "Write-back + crash" and see what happens to unsaved data.

Cache-aside keeps the cache out of the write path. Two other patterns put it right in the middle.

Write-through

Every write goes to the cache, and the cache writes it to the database before confirming.

  • The cache is always up to date: reads right after a write get the new value.
  • No data loss from the cache, because the database already has it.
  • Writes are as slow as the database (a little slower, in fact).
  • You may cache data nobody reads.

Good for data that's written and then read soon after, like user profiles or settings.

Write-back (write-behind)

Writes go to the cache, which confirms immediately. The cache saves to the database later, often in batches.

  • Very fast writes: memory speed.
  • Fewer database writes: ten updates to the same counter become one.
  • Risk: if the cache dies before flushing, those writes are lost, even though the user was told "saved".
  • Harder to reason about: the database is behind the cache for a while.

Good for high-volume, loss-tolerant data: view counts, analytics, likes, game state that's checkpointed.

Where you'll meet these

  • CPU caches and disks use write-back all the time, with batteries or flush commands for safety.
  • Databases themselves are write-back internally, made safe by the write-ahead log.
  • In application design, write-through or cache-aside are the safe defaults. Reach for write-back when write volume forces you to, and make the loss window explicit.

Quick check

Which pattern suits counting video views, where losing a few seconds of counts is fine but the write volume is huge?