Sub topic 2
Write-Through, Write-Around, and Write-Back Caching
Assume you know basic Python, client-server requests, databases, latency, and throughput. This chapter compares write strategies and then covers expiration, eviction, and invalidation.
Write-through caching
With write-through caching, an application writes to the cache and the database as one logical operation. A successful write updates both locations before the application reports success.
class Store:
def __init__(self):
self.database = {}
self.cache = {}
def write_through(self, key, value):
self.database[key] = value
self.cache[key] = value
def read(self, key):
if key not in self.cache:
self.cache[key] = self.database.get(key)
return self.cache[key]This keeps frequently read data warm, but every write pays for both destinations. The database remains the durable source of truth.
Write-around caching
Write-around sends writes directly to the database and does not update the cache. The next read loads the new value into the cache.
This avoids caching data that is written once and rarely read. However, the first read after a write is a cache miss. If an old entry remains, the application must invalidate it.
Write-back caching
Write-back, also called write-behind, writes to the cache first and sends the database update later. It reduces write latency and can combine multiple updates.
The trade-off is data loss if the cache fails before it flushes. It also requires retry handling, ordering rules, and a durable queue or equivalent mechanism.
Expiring entries with TTL
A time to live (TTL) limits how long an entry remains usable. Short TTLs reduce staleness but increase database reads. Long TTLs improve hit ratio but serve older data longer.
Eviction policies
When a cache reaches capacity, it evicts entries according to a policy.
| Policy | Evicts | Useful when |
|---|---|---|
| LRU | Least recently used | Recent access predicts reuse |
| LFU | Least frequently used | Popular items stay popular |
| FIFO | Oldest inserted item | Simple ordering is enough |
Invalidating cached data
Invalidation removes or refreshes an entry after its source changes. A common rule is: update the database, then delete the related cache key. Include tenant, version, and parameter values in keys to avoid collisions.
Exercise
Which strategy is safest when every successful write must be immediately visible on later reads?
Show answer
Write-through, combined with invalidation or an atomic update design that prevents stale replicas.