Write-through, write-behind and write-around

Caching and Redis Mid-level Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

A page-view counter takes 20,000 increments a second and can lose a few seconds of counts on a crash. Best write strategy?

Options
Hint 1 of 1

Can you afford to lose a few seconds?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Write-behind: INCR in Redis, flush totals to the database every few seconds

Correct. Fast writes; the bounded loss is acceptable here.

When some loss is acceptable, counting in memory and writing totals in batches turns 20,000 row updates a second into one write every few seconds. The risk is only the counts since the last flush.

Why not the others?
  • B Write-through: update the database on every view. 20,000 row updates a second on one hot row.
  • C Write-around: only write the database. Same database load.
  • D No cache. The database becomes the bottleneck.

30-second answer

Write-through writes to the cache and the database in the same operation, so the cache is always warm for recently written data, at the cost of slower writes and caching data that may never be read. Write-behind writes to the cache and flushes to the database later, giving fast writes but risking data loss if the cache fails before flushing. Write-around writes only to the database and lets reads fill the cache, which avoids polluting it with write-once data.

Practise saying it · 35 s. No recording, just a timer

Compare cache write strategies.

Say your answer out loud, then check which of these points you covered:

  • Through: both now, warm, slower
  • Behind: cache now, DB later, loss risk
  • Around: DB only, reads fill
  • Pick per data

Deep dive

Write-behind suits counters and metrics where losing a few seconds is acceptable.

Write-through still needs invalidation if anything else writes the database.

Most web apps use cache-aside with write-around plus delete-on-write.

If you write-behind from Redis, enable AOF persistence and monitor the flush lag.

Common mistakes

  • Using write-behind for payments.
  • Assuming write-through makes the cache consistent when other services write the database directly.
  • Writing every row into the cache 'just in case'.

Senior take & follow-ups

One sentence per pattern with its trade-off, then which you'd pick for what.

Follow-up questions

Think of your answer first, then open the hint.

  1. Which one risks data loss?

    Show hint

    Write-behind: the cache holds the only copy until flushed.

  2. Which is best for write-heavy, read-rarely data?

    Show hint

    Write-around.

Suggest a fix if something here is wrong or out of date.