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:

  1. Check cache first
  2. If miss, query database
  3. Store result in cache
  4. 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:

  1. Application writes to cache
  2. Cache writes to database
  3. 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:

  1. Write to cache
  2. Return immediately
  3. Background process syncs to database

Pros: Lowest latency writes Cons: Risk of data loss, complexity

Choosing the Right Strategy

Use CaseStrategy
Read-heavy, tolerates staleCache-Aside
Consistency criticalWrite-Through
Write-heavy, latency sensitiveWrite-Behind