Cache-aside vs write-through vs write-back — which caching pattern to use
cache-aside pattern, write-through cache, write-back cache, read-through cache, cache population, consistency trade-offs
Three Caching Patterns
The caching pattern determines when data goes into the cache and when it's written to the database. Wrong choice leads to stale reads or write bottlenecks.
Cache-Aside (Lazy Loading)
App checks cache first. On miss, app fetches from DB and populates cache.
def get_user(user_id):
user = cache.get(f'user:{user_id}')
if user is None:
user = db.query('SELECT * FROM users WHERE id = ?', user_id)
cache.set(f'user:{user_id}', user, ttl=3600)
return userPro: cache only holds requested data. Con: first request always hits DB (cache miss penalty).
Write-Through
Every write goes to cache AND database synchronously. Cache is always warm. Con: every write pays the cache-write overhead, and rarely-read data still gets cached.
Write-Back (Write-Behind)
Writes go to cache immediately; database is updated asynchronously later. Extremely fast writes. Con: if cache fails before DB sync, data is lost. Use only when write performance matters more than durability.
When to Use Each
- Cache-aside: most general-purpose use cases
- Write-through: when read-after-write consistency is required
- Write-back: high-frequency write workloads where some data loss is acceptable
