What is the difference between write-through and write-back caching?
Write-through writes to the cache and the database together before replying, so data is safe but writes are slower. Write-back writes to the cache first and flushes to the database later, which is faster but can lose data on a crash.
Explain it simply
Think of a shopkeeper's ledger. Write-through: you note every sale in the pocket diary and the main register at the same moment. Slower, but both always match. Write-back: you note sales in the pocket diary all day and copy them to the register in the evening. Faster during the day, but if you lose the diary, those sales are gone.
Write-through:
- Cache and database stay consistent.
- Every write pays the database latency.
- Good when data loss is unacceptable.
Write-back (write-behind):
- Reply right after the cache write; batch the flushes to the database.
- Great for write-heavy loads like counters, since many updates to one key become one database write.
- Risk: if the cache node dies before flushing, recent writes are lost. Use replication or a durable log to reduce that risk.
A third option, write-around, writes only to the database and lets reads fill the cache.
Example
A view counter updated 1,000 times in a second.
Write-through: 1,000 database writes.
Write-back : 1,000 cache increments, one database write per
5 seconds with the total.If the cache crashes at second 4, write-back loses up to 4 seconds of counts. For a view counter that is fine; for a bank balance it is not.
What to say in the interview
"Write-through keeps cache and database in step at the cost of write latency. Write-back is faster and absorbs bursts, but unflushed data can be lost if the cache fails. I use write-through for important data and write-back for tolerant, write-heavy data like counters."