Caching PatternsLesson 3.2
Write-through and write-behind caching: when to update Redis on writes
write-through pattern, write-behind pattern, consistency tradeoff, dual write, cache invalidation, write amplification
Keeping cache consistent on writes
Cache-aside handles reads. For writes you need a strategy to keep Redis and your database consistent.
Write-through
Write to Redis and the database in the same operation, synchronously. The cache is always up to date.
async function updateUser(userId, data) {
// Write to DB first
await db.query('UPDATE users SET name=$1 WHERE id=$2',
[data.name, userId]);
// Immediately update cache
const cacheKey = `user:${userId}`;
await client.setEx(cacheKey, 300, JSON.stringify(data));
}Write-through increases write latency (two round trips) but eliminates stale cache entries for that key.
Write-behind (write-back)
Write to Redis immediately and return success. A background worker asynchronously flushes changes to the database.
async function updateUserAsync(userId, data) {
await client.setEx(`user:${userId}`, 300, JSON.stringify(data));
await client.rPush('db:write:queue', JSON.stringify({ userId, data }));
// Worker drains queue and writes to DB
}Write-behind is faster but risks data loss if Redis crashes before the flush. Use it only when you can tolerate some data loss or have Redis persistence enabled.
