Sub topic 8
Write-back caching
This chapter assumes you know the cache-aside and write-through patterns from earlier chapters, and that you are comfortable reading Python with threads. Write-back caching (also called write-behind) trades durability for write speed. You will see how it works, how to build a small version, and where it loses data.
How write-back differs from write-through
In write-through caching, every write goes to the cache and the database before the caller gets a reply. The database is always current, but each write pays the database's latency.
In write-back caching, a write updates only the cache and marks the entry as dirty. A dirty entry holds a value the database has not seen yet. The cache writes dirty entries to the database later, in the background. The caller gets a reply at cache speed.
| Property | Write-through | Write-back |
|---|---|---|
| Write latency | Cache plus database | Cache only |
| Database load | One write per update | Fewer writes, often batched |
| Durability on cache crash | No data loss | Unflushed writes are lost |
| Database freshness | Always current | Behind by up to one flush interval |
| Complexity | Low | High |
The write path
The diagram shows one update and the later flush.
Notice that v2 never reaches the database. The two writes to user:1 were coalesced into one. This is the main performance gain. If a hot key is updated 1,000 times between flushes, the database sees one write.
A working implementation
The class below keeps a dirty set, flushes when the set gets large or when a timer fires, and flushes once more on shutdown. It does not load missing keys from the database. To keep the example short, it assumes every key was written through the cache.
import threading
class WriteBackCache:
def __init__(self, store, flush_interval=5.0, max_dirty=100):
self.store = store # must provide save_many(dict)
self.flush_interval = flush_interval
self.max_dirty = max_dirty
self.data = {}
self.dirty = set()
self.lock = threading.Lock()
self.stop = threading.Event()
self.thread = threading.Thread(target=self._loop, daemon=True)
self.thread.start()
def get(self, key, default=None):
with self.lock:
return self.data.get(key, default)
def put(self, key, value):
with self.lock:
self.data[key] = value
self.dirty.add(key)
too_many = len(self.dirty) >= self.max_dirty
if too_many:
self.flush() # size-triggered flush
def flush(self):
with self.lock:
batch = {k: self.data[k] for k in self.dirty}
self.dirty.clear()
if not batch:
return
try:
self.store.save_many(batch)
except Exception:
with self.lock:
self.dirty.update(batch) # keep them dirty so we retry
raise
def _loop(self):
while not self.stop.wait(self.flush_interval):
try:
self.flush()
except Exception:
pass # a real system would log and alert here
def close(self):
self.stop.set()
self.thread.join()
self.flush() # final flush on clean shutdown
class FakeStore:
def __init__(self):
self.rows = {}
self.write_calls = 0
def save_many(self, batch):
self.write_calls += 1
self.rows.update(batch)
store = FakeStore()
cache = WriteBackCache(store, flush_interval=60, max_dirty=100)
for i in range(1000):
cache.put("counter", i) # 1000 writes to the same key
print(store.write_calls) # 0: nothing flushed yet
cache.close()
print(store.write_calls, store.rows) # 1 {'counter': 999}The 1,000 writes cause one database write. Three details matter:
- The flush copies the batch and clears the dirty set while holding the lock, then calls the database outside the lock. Slow database calls do not block
put. - If the database call fails, the keys go back into the dirty set. The cache holds the newest value for each key, so a retry never writes stale data.
closeperforms a last flush. Without it, a normal restart would lose writes.
Flush triggers
Production caches combine several triggers:
- Time. Flush every N seconds. This bounds how stale the database can get.
- Dirty count or size. Flush when too many entries are dirty. This bounds how much data a crash can lose.
- Eviction. When the cache must evict a dirty entry, it must write that entry first. Evicting a dirty entry without a flush silently discards the write. With LRU, the least recently used key may still be dirty if it was written once and never read.
- Shutdown. Flush on graceful stop, as
closedoes above.
Failure modes
Write-back has failure modes that write-through does not.
Data loss on crash. If the process or cache node dies between a write and its flush, the acknowledged write is gone. The caller was told it succeeded. With an in-process dictionary, any crash loses every unflushed write. A remote cache such as Redis improves this only if it persists to disk, and even then persistence is usually asynchronous.
Stale reads from the database. Anything that reads the database directly, such as reports, other services, or a cache-miss path on another node, sees old data until the flush. Every reader that needs fresh data must go through the cache.
Write reordering and conflicts. If two cache nodes hold the same key, each flushes its own value, and the last flush wins. This may not match the order of the original writes. Write-back works best when one cache owns each key.
Database constraint failures. The caller has already been told the write succeeded. If the flush later fails on a unique constraint or a validation rule, nobody can tell the caller. Validate data before it enters the cache.
Backpressure. If the database is down or slow, the dirty set grows without limit. Set a maximum dirty size. When it is reached, block writers or reject writes, so the cache degrades into write-through behavior instead of exhausting memory.
When write-back fits
Good fits have three traits. Writes are frequent, losing a few seconds of them is tolerable, and the same keys are often updated repeatedly.
- Counters and metrics such as page views, likes, and rate-limit tallies.
- Session activity, such as "last seen" timestamps.
- Telemetry or log events that are batched anyway.
- Hardware or CPU caches, where write-back is the standard design for the same reason.
Poor fits include financial records, inventory that must not oversell, and anything audited.
Choosing between write-through and write-back
Start with write-through, or with cache-aside plus invalidation. Move to write-back only when you have measured that database write latency or write volume is the bottleneck, and when the product owner has accepted the loss window in writing. Then make the window explicit: state the flush interval and the dirty cap, and expose the current dirty count as a metric.
Exercise
A cache flushes dirty entries every 10 seconds and holds at most 500 dirty entries. A key is updated 200 times in one 10-second window, and the process crashes 4 seconds after the last flush. How many database writes did that key cause in the window, and what is lost?
Show answer
Until the crash, the key caused zero database writes in that window, because its updates are only flushed at the interval, and the last flush happened before the window's updates (assuming they began after it). The updates made in the 4 seconds before the crash are lost, along with any other dirty entries. The key's database value is whatever the previous flush wrote. If the process had survived, the 200 updates would have been coalesced into one database write at the next flush.
Exercise
Why must a write-back cache flush a dirty entry before evicting it?
Show answer
The cache holds the only copy of the newest value. Evicting the entry without writing it to the database discards an acknowledged write.