Applicability
When to Use
✓When consistency between cache and database is critical
✓When read-after-write consistency is required
✓When you can tolerate slightly higher write latency
Overview
How It Works
Write-Through ensures cache and database are always in sync by writing to both on every update. The agent writes to PostgreSQL and Redis simultaneously, so the cache always reflects the latest data. This eliminates the stale-data problem of Cache-Aside at the cost of higher write latency.
This pattern is ideal when applications frequently read data they just wrote, and when consistency is more important than write performance. Both writes can be done in parallel to minimize latency.
Implementation
Code Example
typescript
async function writeThrough(key, data) {
await Promise.all([
postgres.query("INSERT INTO cache_data (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value=$2", [key, JSON.stringify(data)]),
redis.set(key, JSON.stringify(data))
]);
}
async function read(key) {
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
// Fallback for cache failures
const result = await postgres.query("SELECT value FROM cache_data WHERE key=$1", [key]);
return result.rows[0] ? JSON.parse(result.rows[0].value) : null;
}Quick Info
Categorycaching
ComplexityEasy