Write-Through Cache Pattern
Synchronously write to both cache and backing store so the cache always has the latest data without TTL-based invalidation.
Overview
In a write-through cache, every write operation goes to both the cache and the backing store synchronously. The application asks the cache to write, the cache writes to the database, and both succeed before the operation returns. The result: the cache always reflects the latest committed data, so you don’t need explicit invalidation logic on the write path.
The trade-off is write latency. Each write pays for two round trips — one to the database and one to the cache — so writes are slower than with write-behind or cache-aside. Reads stay fast because the cache is always fresh. This pattern suits read-heavy workloads where serving a stale value is a correctness bug, not a performance quirk: balances, inventory counts, feature flags, permissions.
Write-through only covers the write path. It says nothing about how data gets into the cache in the first place, which is why it’s almost always paired with read-through or cache-aside for the read side. On its own, a cold write-through cache still misses reads the same way any empty cache does.
When to Use
- Read-heavy workloads where reads far outnumber writes and read latency is the metric that matters.
- Strong consistency between cache and database is a correctness requirement — financial systems, inventory, quota counters.
- You’ve been bitten by forgotten
cache.delete(key)calls on write paths and want invalidation to be structural, not a developer obligation. - Teams that want one obvious write path instead of scattered invalidation calls across services.
Avoid it when:
- Writes dominate the workload — the double round trip compounds under write pressure; write-behind batches database writes instead.
- The data is write-once, read-rarely — caching it wastes memory on every update; write-around is cheaper.
- You can’t afford synchronous writes at all — event sourcing or queue-based sync may fit better.
Solution
Python with Redis
import redis
import json
from typing import Any, Callable
class WriteThroughCache:
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
def write(self, key: str, value: Any, db_writer: Callable, ttl: int = 3600) -> Any:
serialized = json.dumps(value)
# Write to database first (source of truth)
db_writer(value)
# Then write to cache
self.redis.setex(key, ttl, serialized)
return value
def write_transaction(self, key: str, value: Any, db_writer: Callable, ttl: int = 3600) -> Any:
pipe = self.redis.pipeline()
try:
# Write to database
db_writer(value)
# Queue cache write
pipe.setex(key, ttl, json.dumps(value))
pipe.execute()
return value
except Exception:
# If DB write succeeds but cache write fails, invalidate cache
# to prevent stale data on next read
self.redis.delete(key)
raise
cache = WriteThroughCache(redis.Redis(host='localhost', port=6379))
def update_user(user_id: str, name: str, email: str) -> dict:
user = {"id": user_id, "name": name, "email": email}
return cache.write(
f"user:{user_id}",
user,
lambda u: db.execute(
"UPDATE users SET name = %s, email = %s WHERE id = %s",
[u["name"], u["email"], u["id"]]
),
ttl=1800
)
TypeScript with Redis
import { createClient } from 'redis';
class WriteThroughCache {
private client: ReturnType<typeof createClient>;
constructor(client: ReturnType<typeof createClient>) {
this.client = client;
}
async write<T>(
key: string,
value: T,
dbWriter: (value: T) => Promise<void>,
ttl = 3600
): Promise<T> {
try {
// Write to database first
await dbWriter(value);
// Then update cache
await this.client.set(key, JSON.stringify(value), { EX: ttl });
return value;
} catch (error) {
// If DB write fails, do not update cache
// If cache write fails, invalidate to prevent stale reads
await this.client.del(key).catch(() => {});
throw error;
}
}
async delete(key: string, dbDeleter: () => Promise<void>): Promise<void> {
await dbDeleter();
await this.client.del(key);
}
}
// Usage
const redisClient = createClient({ url: 'redis://localhost:6379' });
await redisClient.connect();
const cache = new WriteThroughCache(redisClient);
async function updateUser(userId: string, name: string, email: string): Promise<User> {
const user = { id: userId, name, email };
return cache.write(
`user:${userId}`,
user,
async (u) => {
await db.query(
'UPDATE users SET name = $1, email = $2 WHERE id = $3',
[u.name, u.email, u.id]
);
},
1800
);
}
Java with Spring Cache
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// @CachePut always writes to cache after method execution
// The method writes to DB, Spring writes result to cache
@CachePut(value = "users", key = "#user.id")
public User saveUser(User user) {
return userRepository.save(user);
}
@CachePut(value = "users", key = "#id")
public User updateUser(Long id, String name, String email) {
User user = userRepository.findById(id)
.orElseThrow(() -> new NotFoundException("User not found"));
user.setName(name);
user.setEmail(email);
return userRepository.save(user);
}
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
Combining Read-Through and Write-Through
class ReadWriteThroughCache:
def __init__(self, redis_client: redis.Redis, ttl: int = 3600):
self.redis = redis_client
self.ttl = ttl
def read(self, key: str, loader: Callable) -> Any:
cached = self.redis.get(key)
if cached is not None:
return json.loads(cached)
value = loader()
self.redis.setex(key, self.ttl, json.dumps(value))
return value
def write(self, key: str, value: Any, db_writer: Callable, ttl: int = None) -> Any:
db_writer(value)
self.redis.setex(key, ttl or self.ttl, json.dumps(value))
return value
def delete(self, key: str, db_deleter: Callable) -> None:
db_deleter()
self.redis.delete(key)
cache = ReadWriteThroughCache(redis.Redis(host='localhost', port=6379))
def get_user(user_id: str) -> dict:
return cache.read(
f"user:{user_id}",
lambda: db.query_one("SELECT * FROM users WHERE id = %s", [user_id])
)
def update_user(user_id: str, **fields) -> dict:
user = {"id": user_id, **fields}
return cache.write(
f"user:{user_id}",
user,
lambda u: db.execute("UPDATE users SET name=%s WHERE id=%s", [u["name"], u["id"]])
)
Explanation
The write-through pattern keeps the cache consistent by writing to both stores in sequence:
- Write to database — the database is the source of truth. Writing here first means a cache failure never loses the data.
- Write to cache — after the database write commits, update the cache with the same value.
- Handle the gap — if the cache write fails after the database commit, delete the key. The next read misses and reloads through read-through or cache-aside, so staleness never lives longer than the failure itself.
The order is the whole pattern. Write to cache first and a failed database write leaves data in the cache that was never committed — reads now serve phantom state. Write to database first and the worst case is a brief stale window that the invalidate-on-failure path closes.
There’s still one consistency hole worth knowing: between the database commit and the cache update, a concurrent read can reload the old value into the cache. The window is milliseconds, but under hot-key contention it happens. If your domain can’t tolerate it, wrap both writes in a transaction or add a version number to the value and compare it on read.
Variants
| Approach | Write Order | Best For |
|---|---|---|
| DB first, then cache | DB then cache | Most use cases, safe default |
| Cache first, then DB | Cache then DB | Ultra-low write latency (risky — phantom data on DB failure) |
| Write-around | DB only, skip cache | Write-once, read-rarely data |
| Write-behind | Cache first, async DB | High-throughput writes, eventual consistency acceptable |
| Transactional | Both in one transaction | Strict consistency — bank transfers, quota counters |
Write-behind deserves a note because it’s the usual alternative. It returns after the cache write and flushes to the database asynchronously, so writes feel instant and bursts collapse into batched flushes. The cost is a window where the cache holds data the database has never seen — a cache restart in that window loses writes. Pick write-through when losing a write is worse than paying extra milliseconds for it.
Best Practices
- Write to database first — the database is the source of truth. If the cache write fails, the data still persists.
- Invalidate on cache write failure — if the cache write fails after the DB commit, delete the key so the next read fetches fresh data instead of serving stale.
- Keep a TTL as a safety net — even with write-through, set a TTL. A missed write (network partition, bug in another service writing directly to the DB) self-heals on expiry instead of staying wrong forever.
- Make writes idempotent — retrying a write-through operation shouldn’t duplicate data. Use upserts or idempotency keys on the database side.
- Measure the write penalty — write-through adds cache write time to every write. Track p99 write latency before and after; if it climbs past your budget, move non-critical keys to write-behind rather than abandoning the pattern everywhere.
Common Mistakes
- Writing to cache first — if the DB write then fails, the cache holds data that was never committed. Always write to DB first.
- Not handling cache write failure — a silently failed cache write serves stale data until TTL expiry. Invalidate on failure so the next read reloads.
- Using write-through for write-heavy workloads — every write hits both stores. Under write pressure, that double cost compounds; use write-behind or write-around instead.
- Skipping the TTL — write-through doesn’t protect against writers that bypass the cache (a migration script, another service, a manual
UPDATE). A TTL bounds how wrong the cache can be. - Caching everything — write-through writes to cache on every update. Keys that are rarely read just burn memory and add write latency for no benefit.
Troubleshooting
- Cache and database diverge after deploys: a second writer (cron, migration, another service) updates the DB without touching the cache. Find it via DB audit logs or binlog diffing against cache content, then route that writer through the cache layer or shorten the TTL as a stopgap.
- Write latency doubled after enabling the pattern: expected — you’re paying for two writes. If it’s a regression worth fixing, move only the hottest keys to write-behind and keep write-through for consistency-critical data.
- Stale reads right after a write: the gap between DB commit and cache update let a concurrent read reload the old value. Add versioning to the value (
{"data": ..., "v": 42}) and overwrite only on higher versions. - Cache restart wipes “recent” writes: you paired write-through with write-behind somewhere, and the async flush hadn’t run. Write-through data survives a cache restart by definition — if it doesn’t, some path is skipping the DB write.
- Memory climbing on a write-heavy endpoint: write-through caches every write. Check which keys are actually being read — evict-only or skip-cache policies belong on write-once, read-rarely data.
Production Notes
- Alert on cache-write failure rate, not just cache hit rate — write-through correctness degrades silently when cache writes start failing and your invalidate-on-failure path becomes the only thing between you and permanent staleness.
- Track write latency per endpoint before and after rollout; the pattern’s cost shows up in p99 writes, not averages.
- Log skipped keys — if you add bypass logic for hot keys, record it. Undocumented exceptions are how “the cache is always consistent” stops being true.
- Version the value format — pairing a version counter with the payload makes the concurrent-read race detectable instead of invisible.
Key Takeaways
- Write to database first, cache second — that ordering is the pattern; reversing it serves uncommitted data on DB failure.
- Invalidate on cache-write failure — it’s what keeps the failure window bounded to one read instead of lasting until TTL expiry.
- Pair it with a read strategy — write-through alone doesn’t populate a cold cache; combine it with read-through or cache-aside.
- The trade is write latency for consistency — if your workload is write-heavy or tolerates staleness, write-behind or write-around will serve you better.
See Also
- Cache-Aside Pattern — the read-side counterpart for lazy loading.
- Read-Through Cache Pattern — the natural pairing for this pattern.
- Write-Behind Cache Pattern — when write latency matters more than immediate consistency.
- Node.js Redis Cache Invalidation — practical invalidation when you can’t use write-through.
- AWS Prescriptive Guidance — Caching patterns — official comparison of caching strategies.
- Redis — Client-side caching and write patterns — behavior notes for Redis-backed caches.
- Spring Cache Abstraction —
@CachePutand@CacheEvictsemantics used in the Java example.
Frequently Asked Questions
What is the difference between write-through and write-behind?
Write-through writes to cache and database synchronously — the operation doesn't return until both succeed. Write-behind writes to cache first and flushes to the database asynchronously. Write-through is consistent but slower per write; write-behind is faster but can lose writes on cache restart.
When should I use write-through over cache-aside?
When the cache must reflect the latest write immediately. Cache-aside relies on developers remembering to invalidate on every write path; write-through makes freshness structural. If forgetting an invalidation is a real risk in your codebase, write-through removes that failure mode.
What happens if the database write fails?
The cache isn't touched and the operation throws. The cache keeps its previous value (or nothing, for a new key) — which is correct, because nothing was committed. The caller retries or surfaces the error.
Can I combine read-through and write-through?
Yes, and it's the most common pairing. Reads go through the cache with a loader callback that populates misses; writes update both stores. Together they cover both directions of cache-database consistency.
Does write-through still need a TTL?
Yes — as a safety net, not as the consistency mechanism. Write-through protects against forgotten invalidation, but not against writers that bypass the cache entirely (migrations, other services, manual fixes). A TTL bounds how stale the cache can get from those cases.
Is write-through appropriate for high-write workloads?
Usually not. Every write pays two round trips, which compounds under write pressure. If writes dominate, write-behind batches the database side; if the data is rarely read, write-around skips the cache write entirely.
Related Resources
Cache-Aside Pattern
Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.
PatternRead-Through Cache Pattern
A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.
RecipeImplement Redis Cache Invalidation in Node.js
Invalidate Redis cache entries in Node.js with TTL expiry, explicit deletion, pattern-based clearing, and pub/sub-based distributed invalidation.
PatternWrite-Behind Cache Pattern
Write to the cache synchronously and persist to the database asynchronously for high-throughput write workloads with eventual consistency.
PatternCache Invalidation Pattern
Strategies for keeping cached data fresh: TTL expiration, explicit invalidation, write-through, and event-driven cache eviction.
GuideComplete Guide to Redis Caching Strategies
Choose and implement the right Redis caching pattern — cache-aside to refresh-ahead — with eviction, TTL, and production ops guidance.