Sub topic 6
Write-through caching
This chapter assumes you know cache-aside, TTL, and basic database reads and writes. Write-through is a write pattern. Every write goes to the cache and to the database as part of the same operation, so the cache always holds the latest value for any key that was written.
How it works
The application sends the write to the cache layer. That layer writes to the database first, then updates its own entry, and only then reports success. A later read finds the new value in the cache.
A minimal implementation
import threading
class DictDB:
"""Stand-in for a real database."""
def __init__(self):
self.rows = {}
def save(self, key, value):
self.rows[key] = value
def fetch(self, key):
return self.rows.get(key)
class WriteThroughCache:
def __init__(self, db):
self.db = db
self.cache = {}
self.lock = threading.Lock()
def put(self, key, value):
with self.lock:
self.db.save(key, value) # if this raises, the cache is untouched
self.cache[key] = value # update the cache only after the DB succeeds
def get(self, key):
with self.lock:
if key in self.cache:
return self.cache[key]
value = self.db.fetch(key) # key was never written through
if value is not None:
with self.lock:
self.cache.setdefault(key, value)
return value
store = WriteThroughCache(DictDB())
store.put("user:1", {"name": "Ada"})
print(store.get("user:1"))The database write comes first on purpose. If it fails, the exception propagates and the cache never holds a value the database lacks.
Trade-offs
| Property | Effect |
|---|---|
| Read freshness | Reads of written keys never see stale data |
| Write latency | Each write pays for both the database and the cache |
| Cache contents | Fills with keys that may never be read |
| Durability | Same as the database, since it is written synchronously |
Common errors
- Concurrent writers. Two threads writing the same key can finish the database write in one order and the cache write in the other, leaving the cache different from the database. The lock above prevents this inside one process. Across processes you need a version number, a compare-and-set, or a single writer per key.
- Partial failure. If the database write succeeds and the cache write fails, the cache is stale. Delete the entry on failure, or rely on a TTL as a backstop.
- Cache pollution. Write-heavy data that is rarely read wastes memory and evicts useful entries. Write-around suits that data better.
- Bypassed writes. Any job that writes to the database directly leaves the cache stale. Route every write through the cache layer.
Exercise
A write-through cache saves to the database, and then the cache update throws an error. What should the code do, and why?
Show answer
Remove the key from the cache (or let it expire) and report the error or retry the cache update. The database holds the new value, so keeping the old cached value would serve stale reads. Deleting forces the next read to reload the correct value from the database.