Sub topic 7
Write-around caching
Write-around caching sends writes straight to the database and skips the cache. Reads still go through the cache, which fills on a miss. This chapter assumes you know cache-aside (read path with a miss and fill), what a hit ratio is, and what TTL means.
The idea
In write-through, every write updates both the database and the cache. In write-around, a write touches only the database. The cache learns about the new value later, when a reader asks for it and misses.
The write path is simple:
- The application writes to the database.
- The application does nothing to the cache, or removes any entry for that key.
- A later read misses, loads the fresh row, and stores it.
The read path is the same as cache-aside. Write-around is not a separate read mechanism. It is a rule about what writes do, and it is often combined with cache-aside reads.
Why skip the cache on writes
Write-around pays off when written data is rarely read soon after. Three common cases:
- Write-heavy, read-light data. Audit logs, event records, and import jobs write far more than they read. Caching each write fills the cache with entries nobody asks for.
- Large bulk loads. Loading a million rows through a write-through cache evicts the hot entries your readers depend on. This is cache pollution.
- Data read once, if ever. Uploaded files and order history often fit this pattern. Only the items that readers actually request earn a cache slot.
Because the cache only contains data that was read, it reflects real demand. Hit ratio per byte of cache tends to be higher than when every write is admitted.
The cost: the first read after a write misses
The main downside is a guaranteed miss on the first read of newly written data. If you write a record and read it back right away, that read goes to the database. For data that is written and then read soon, such as a user editing a profile and seeing it again, write-around adds latency that write-through would avoid.
A second cost appears when the data was already cached. Skipping the cache on write leaves the old value in place, so readers can see stale data. This is the most important edge case in the chapter.
Handling the stale entry
Write-around does not by itself say what happens to an existing cache entry. You have three options.
| Option | Behavior | Result |
|---|---|---|
| Do nothing | Old entry stays until TTL expiry or eviction | Stale reads for up to the TTL |
| Invalidate on write | Delete the key after the database write | Next read misses and loads fresh data |
| Short TTL only | Rely on expiry for all freshness | Bounded staleness, extra misses |
Most systems invalidate on write. The second code example in the spine's cache-aside pattern does exactly this: it saves to the database and then pops the key. That combination is what people usually mean by write-around with cache-aside reads.
Doing nothing is acceptable only if the staleness window equals the TTL and the business tolerates it. Product descriptions that change a few times a month may qualify. Account balances do not.
A working example
The code below stores users in a database and caches reads. Writes go to the database and delete the cached key. A counter records misses so you can see the first-read miss.
import time
TTL_SECONDS = 60
class FakeDB:
def __init__(self):
self.rows = {}
self.reads = 0
def save_user(self, user_id, data):
self.rows[user_id] = data
def fetch_user(self, user_id):
self.reads += 1
return self.rows.get(user_id)
cache = {} # key -> (value, expires_at)
def get_user(user_id, db):
key = f"user:{user_id}"
entry = cache.get(key)
if entry is not None and entry[1] > time.monotonic():
return entry[0]
value = db.fetch_user(user_id)
if value is not None:
cache[key] = (value, time.monotonic() + TTL_SECONDS)
return value
def write_user(user_id, data, db):
db.save_user(user_id, data) # write goes to the database only
cache.pop(f"user:{user_id}", None) # drop any stale copy
db = FakeDB()
write_user(1, {"name": "Ada"}, db)
print(get_user(1, db), "db reads:", db.reads) # miss, loads from db
print(get_user(1, db), "db reads:", db.reads) # hit, no new db read
write_user(1, {"name": "Ada L."}, db)
print(get_user(1, db), "db reads:", db.reads) # miss again after writeRunning it prints three lines. The database read count goes from 1 to 1 to 2. The first and third reads are misses caused by the write-around rule. The second read is a hit.
Notice that write_user never calls cache[key] = .... That single missing line is the whole difference from write-through.
Race conditions with invalidate-on-write
Deleting the key after the database write has a known race. Consider two threads:
- Reader A misses and reads the old value from the database.
- Writer B updates the database and deletes the key.
- Reader A stores the old value into the cache.
The cache now holds stale data, and nothing will remove it until the TTL expires. The window is small, because it needs a slow read overlapping a write, but it exists under load.
Ways to reduce it:
- Keep a TTL on every entry so any stale value is bounded.
- Delete the key both before and after the database write. This narrows the window but does not close it.
- Use versioned values or compare-and-set, so a fill with an older version is rejected.
The TTL is the safety net. Do not remove it just because you invalidate on write.
Comparison with other write policies
| Policy | Write goes to | Cache after write | Best for |
|---|---|---|---|
| Write-around | Database only | Entry deleted or untouched | Write-heavy data, rarely re-read |
| Write-through | Cache and database | Fresh entry | Data re-read soon after write |
| Write-back | Cache first, database later | Fresh entry | Very high write rates, tolerates data loss risk |
Write-around has the weakest consistency risk of the three when combined with invalidation, because the database is the only place a write lands. It also has no data loss risk. Write-back can lose acknowledged writes if the cache fails before it flushes.
Choosing write-around
Use it when most of these hold:
- Writes outnumber reads for the same keys, or reads are spread over a large key space.
- Newly written data is not usually read immediately.
- Bulk writes would evict hot entries.
- A single extra miss after a write is acceptable.
Avoid it when users read their own changes right away and the miss latency is visible, or when the database is the bottleneck on a hot key that is rewritten often. In that second case, each write forces a miss, and many concurrent readers can hit the database together. Pair write-around with stampede protection, such as the per-key lock covered in the stampede chapter, for such keys.
Common mistakes
- Forgetting to invalidate. Skipping the cache write is not enough. Without a delete or a TTL, old values persist.
- Invalidating before the write only. A reader can refill the cache with the old value between the delete and the database commit.
- Measuring the wrong hit ratio. After a write-heavy period, hit ratio dips because of forced misses. That is expected behavior, not a bug.
- Using it for read-your-writes requirements. If a user must see their update at once, the next read still works, because it misses and loads fresh data. The problem is only latency. The real failure comes from skipping invalidation.
Exercise
A service stores sensor readings. It writes 5,000 readings per second, and dashboards read only the latest value for a few hundred sensors. Would you pick write-around or write-through, and what do you do about the cached latest value when a new reading arrives?
Show answer
Pick write-around. Most readings are never read, so caching every write through would fill the cache with unused entries and evict the few hot ones. On each write, store to the database and delete the cached key for that sensor, or let a short TTL bound staleness if dashboards tolerate a few seconds of delay. The next dashboard read misses and loads the latest value, then serves hits until the following write or expiry.
Exercise
In the example code, which single change would turn the write path from write-around into write-through?
Show answer
In writeuser, replace the cache.pop call with an assignment that stores the new data and an expiry time in the cache, for example cache[f"user:{userid}"] = (data, time.monotonic() + TTL_SECONDS). The write then updates both the database and the cache.