patternjavascriptTip
Write-Through Cache
Viewed 0 times
write throughcache consistencysynchronous cache updateno stale reads
Problem
After a write to the database, the cache holds stale data until TTL expires, causing reads to return outdated values.
Solution
On every write to the database, also write the same data to the cache synchronously before returning to the caller. Cache and DB are updated in the same operation.
Why
Write-through keeps the cache consistent with the DB at all times without requiring explicit invalidation. Reads after writes always see fresh data.
Gotchas
- Increased write latency: every write must hit both DB and cache before completing.
- Cache bloat: data that is never read still occupies cache space. Pair with TTLs to evict cold entries.
- Two-phase failure: if the DB write succeeds but the cache write fails, the cache becomes stale. Always write DB first, then cache.
Code Snippets
Write-through update
async function updateUser(id, data) {
const user = await db.users.update(id, data); // write DB first
await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);
return user;
}Revisions (0)
No revisions yet.