Sub topic 6
Write-through caching
This chapter assumes you know basic Python, how an application talks to a database, and the cache-aside pattern from the earlier chapters. Here you will see how write-through keeps a cache and a database in step on every write. You will also see what it costs and where it breaks.
What write-through means
In write-through caching, every write goes through the cache layer to the database as one synchronous operation. The write is not finished until both the database and the cache hold the new value. The caller gets success only after the database has accepted the write.
Compare this with the cache-aside code you saw earlier. There, update_user saves to the database and then deletes the cached entry. The next read misses and reloads the value. Write-through skips the miss. It puts the new value in the cache at write time, so the next read is already a hit.
The goal is to make the cache an up-to-date copy of the data after every write, instead of an entry that gets thrown away.
The write path
The database is the source of truth, so it is written first. The cache is updated only if the database write succeeds.
If the database write fails, the cache is not touched. The caller sees the error, and the cache still holds the old value, which still matches the database.
A working implementation
This example uses an in-memory stand-in for the database so you can run it as shown.
import threading
class InMemoryDB:
def __init__(self):
self.rows = {}
def save_user(self, user_id, data):
self.rows[user_id] = data
def fetch_user(self, user_id):
return self.rows.get(user_id)
class WriteThroughUserStore:
def __init__(self, db):
self.db = db
self.cache = {}
self.write_lock = threading.Lock()
def update_user(self, user_id, data):
with self.write_lock:
self.db.save_user(user_id, data) # raises on failure, cache untouched
self.cache[f"user:{user_id}"] = data # only reached after the DB commit
def get_user(self, user_id):
key = f"user:{user_id}"
if key in self.cache:
return self.cache[key] # hit
value = self.db.fetch_user(user_id) # miss: fall back to the database
if value is not None:
self.cache[key] = value
return value
if __name__ == "__main__":
db = InMemoryDB()
store = WriteThroughUserStore(db)
store.update_user(7, {"name": "Ada"})
db.rows.clear() # prove the next read does not need the database
print(store.get_user(7)) # {'name': 'Ada'}Three details matter here:
- Ordering. The database write comes first. If you update the cache first and the database write then fails, readers see a value that was never saved.
- The read path still handles misses. After a restart, an eviction, or a TTL expiry, the cache lacks entries.
get_userfills them lazily, as in cache-aside. Write-through only changes the write side. - The lock.
write_lockmakes the database write and the cache update one unit within this process. The next section explains why that matters.
Where write-through goes wrong
Racing writers
Suppose two threads update the same key without a lock. Thread A writes v1 to the database. Thread B writes v2 to the database. Then B updates the cache, and A updates it last. The database holds v2 and the cache holds v1. Nothing corrects this until the entry expires or is evicted.
Ways to prevent it:
- Hold a lock around the database write and cache update, as the example does. A per-key lock allows more parallelism than one global lock.
- Attach a version number or timestamp to each value, and have the cache reject writes older than what it holds. This also works across processes.
- Set a TTL on every entry as a backstop, so any inconsistency that slips through is bounded in time.
A lock inside one process does nothing for several application servers sharing a cache. In that case you need versioning, or a single writer per key.
Partial failure
The database write can succeed and the cache update can then fail, for example when a remote cache is unreachable. The caller has an ambiguous result, and the cache is now stale. Common responses are:
- Treat the cache update as best-effort. Log the failure, delete the key, and let the next read reload it.
- Retry the cache update a few times.
- Fail the whole operation and rely on idempotent writes, so the client can retry safely.
Option 1 is the most common. It falls back to invalidation, which is why write-through and invalidation are covered as related topics.
Wasted work on data nobody reads
Write-through caches every write, whether or not anyone will read it. If your workload writes many records that are rarely read, the cache fills with entries that push out useful ones. Your eviction policy then has more work to do and your hit ratio can drop.
Write latency
Each write now pays for the database round trip plus the cache update. Write-through does not make writes faster. The cost of a write is at least that of a plain database write, and usually a little more. If write speed is your bottleneck, see write-back, which defers the database write.
Comparing the write patterns
| Pattern | Write goes to | Cache after a write | Read after a write | Main risk |
|---|---|---|---|---|
| Cache-aside with invalidation | Database, then delete the cache key | Entry removed | Miss, then reload | Race between a reload and a write can cache an old value |
| Write-through | Database and cache, synchronously | Entry holds the new value | Hit | Writer races, wasted cache space |
| Write-around | Database only | Entry unchanged or absent | Miss for new data | Stale entry if the key was already cached |
| Write-back | Cache first, database later | Entry holds the new value | Hit | Data loss if the cache fails before flushing |
Write-through gives you the strongest read-after-write behavior of the table's patterns that keep the database authoritative. A user who saves a profile and reloads the page sees the new data, and the reload is fast.
When to choose it
Write-through fits when:
- Data is read soon after it is written, such as user profiles, settings, or shopping carts.
- Reads far outnumber writes, so the extra write cost is small compared with the saved database reads.
- Stale reads are costly, and you want the cache to match the database immediately after every successful write.
- You can route all writes for a key through one component, which keeps ordering simple.
It fits poorly when:
- Most written data is never read again. Write-around avoids polluting the cache.
- Write throughput is the limit. Write-back or batching helps more.
- Several independent services write to the same table directly. A write that bypasses your cache layer leaves the cache stale, and write-through cannot help. You need invalidation or a short TTL for that data.
Checking your understanding
Exercise
A write-through store updates the cache first and then writes to the database. The database write fails with a timeout. What state is the system in, and how does the correct ordering prevent it?
Show answer
The cache holds a value that the database never saved, so readers see data that does not exist in the source of truth, and it may be lost on the next eviction or restart. The correct ordering writes the database first and updates the cache only after the commit succeeds. If the database write fails, the cache is never touched and still matches the database.
Exercise
Two application servers share one cache and both update user 7 at nearly the same time. A process-local lock is held on each server. Why can the cache still end up holding the older value, and name two ways to reduce the risk?
Show answer
Each lock protects only its own process, so the two servers can interleave their database writes and cache updates. The database may end with the newer value while the cache ends with the older one. Two mitigations are to store a version number or timestamp with each value and reject cache writes that are older than the stored one, and to set a TTL on entries so a wrong value is corrected after a bounded time. A shared distributed lock or routing all writes for a key to one writer also works.