Sub topic 8
Write-back caching
This chapter assumes you know cache-aside and write-through, and that you understand why a database write costs far more than a memory write.
How it works
In write-back caching (also called write-behind), a write goes only to the cache. The cache marks the entry as dirty, meaning it is newer than the copy in the database. The write returns to the caller immediately. A later flush writes the dirty entries to the database. The flush runs on a timer, when the number of dirty entries passes a threshold, or when a dirty entry is about to be evicted.
Write-through waits for the database on every write. Write-back moves that wait off the request path.
Why use it
- Lower write latency. Callers see memory speed, not database speed.
- Coalescing. Two writes to the same key between flushes produce one database write. In the diagram, the value
1is never written. - Batching. One bulk write is usually cheaper than many single writes.
This suits write-heavy data where losing a few seconds of updates is tolerable, such as counters, view counts, and activity logs.
A minimal implementation
import threading
class FakeDB:
def __init__(self):
self.rows = {}
def load(self, key):
return self.rows.get(key)
def save_many(self, batch):
print(f"db write: {batch}")
self.rows.update(batch)
class WriteBackCache:
def __init__(self, db, max_dirty=3):
self.db = db
self.max_dirty = max_dirty
self.cache = {}
self.dirty = set()
self.lock = threading.Lock()
def get(self, key):
with self.lock:
if key in self.cache:
return self.cache[key]
return self.db.load(key)
def put(self, key, value):
with self.lock:
self.cache[key] = value
self.dirty.add(key)
should_flush = len(self.dirty) >= self.max_dirty
if should_flush:
self.flush()
def flush(self):
with self.lock:
batch = {k: self.cache[k] for k in self.dirty}
self.dirty.clear()
if not batch:
return
try:
self.db.save_many(batch)
except Exception:
with self.lock:
self.dirty.update(batch) # keep them dirty so a retry can happen
raise
db = FakeDB()
cache = WriteBackCache(db)
cache.put("views:1", 10)
cache.put("views:1", 11) # coalesced with the previous write
cache.put("views:2", 5)
cache.put("views:3", 8) # third dirty key triggers a flushThe run prints a single db write: line holding views:1 as 11, views:2 and views:3. The first value of views:1 never reaches the database.
Risks and common errors
- Data loss. If the cache process crashes before a flush, the dirty entries are gone, and the database never saw them. Write-back is only safe when the cache is durable (for example, backed by a write-ahead log) or the data is expendable.
- Stale reads from the database. Any other service that reads the database directly sees old values until the flush runs. Route all reads through the cache, or accept the lag.
- Failed flushes. The code above re-marks entries as dirty on failure. Without that step, a failed flush silently drops writes. Also decide how many retries to allow and what to do when the backlog grows.
- Ordering. Coalescing and batching can reorder writes across keys. If a database constraint depends on that order, write-back may violate it.
- Eviction of dirty entries. An eviction policy must flush a dirty entry before removing it. Otherwise eviction loses data.
Exercise
A service uses write-back caching with a 30-second flush interval. The cache node crashes 20 seconds after the last flush. What data is lost, and which property of write-back makes this possible?
Show answer
Every write acknowledged since the last flush and not yet saved to the database is lost, up to 20 seconds of updates. Write-back acknowledges writes after updating only the cache and defers the database write, so the cache holds the only copy of dirty entries until the flush.