A cache makes a system feel fast by remembering the answer. The trouble begins when reality changes and the cache does not get the memo. These are the patterns I use to reason about that trade-off.
Cache-Aside (Lazy Loading)
The application manages the cache directly:
- Check cache first
- If miss, query database
- Store result in cache
- Return to client
Pros: Only requested data is cached, cache failure doesn't break the app Cons: Initial requests are slow, data can become stale
Write-Through
Write to cache and database simultaneously:
- Application writes to cache
- Cache writes to database
- Return success
Pros: Cache is always consistent Cons: Higher write latency, unused data may be cached
Write-Behind (Write-Back)
Write to cache, async write to database:
- Write to cache
- Return immediately
- Background process syncs to database
Pros: Lowest latency writes Cons: Risk of data loss, complexity
Choosing the Right Strategy
| Use Case | Strategy |
|---|---|
| Read-heavy, tolerates stale | Cache-Aside |
| Consistency critical | Write-Through |
| Write-heavy, latency sensitive | Write-Behind |