Write-back
medium 22 minWith write-back, also called write-behind, a save is answered as soon as it is in the cache, and a worker writes it to the database later in batches.
See it run
Answer from memory now, write to the database in batches later, and know exactly what a crash would cost.
Operations
Write now, flush later
Ten steps: `user:123` gets a new email, the caller is answered, and a worker brings the database up to date.
Step 1 of 10
1. A write request
Writes
0
Flushes
0
The app is asked to change the email of user:123.
Step 1: 1. A write request
def write(key, value): cache.set(key, value) cache.sadd("dirty", key) return "saved" # no database waitdef flush(): # every 5 s keys = cache.take("dirty") db.write_many({k: cache.get(k) for k in keys}) mark_clean(keys)- Caller waits
- 1 ms
- Database writes
- 1 batch
- Write-through
- 11 ms (assumed)
Saved here means saved in memory. Say that sentence before the interviewer asks.
In the real world
The same write-back doing real jobs. Pick one and step through it.
1,000 updates a second on 200 videos, flushed every 5 seconds.
Step 1 of 3
In five seconds
Writes
5000
Flushes
0
5,000 updates land in memory, on 200 keys.
Step 1: In five seconds
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Using it for money
criticalA payment that was confirmed and then lost cannot be explained. It also breaks audit rules.
Wrongwrite_back.set("balance:42", new_balance)Rightwith db.transaction(): ledger.add(account=42, amount=-20)Clearing the buffer before the database confirms
criticalIf the flush fails after the buffer is cleared, the batch is gone.
Wrongbatch = list(dirty.items())dirty.clear()db.write_many(batch)Rightbatch = dict(dirty)db.upsert_many(batch)clear_if_unchanged(dirty, batch)Keeping the buffer only in the app's memory
majorEvery deploy and every crash of one app server loses its part. Other servers do not even know what is dirty.
Wrongself.buffer.append((key, value))Rightredis.set(key, value)redis.sadd("dirty", key) # shared, can be recoveredFlushing the value for a counter from two servers
majorEach server writes its own total and the last one wins. Send the difference, or keep one shared counter.
Wrongdb.set("views", my_local_total)Rightdb.execute("UPDATE posts SET views = views + %s", [delta])
Interview tips
How to explain it
- A write is answered from memory.
- Changed entries are dirty until a worker writes them in batches.
- A crash in between loses saves people already saw.
Memory trick: DEFER
- Direct write to the cache.
- Eventual database sync.
- Flush in the background.
- Extreme speed.
- Risk of data loss.
Reach for it when
- Counters, scores, sensor readings, activity.
- The same keys change many times.
- The loss is small and you can name it.
Move on when
- Payments, orders, anything audited.
- Others read the database and need it fresh.
- Nobody can operate the recovery.