Patterns

Caching Strategies Cheat Sheet

📦 Core Caching Patterns

PatternHow It WorksBest For
Cache-Aside
(Lazy Loading)
App checks cache first → miss → fetch from DB → store in cacheRead-heavy, data that may not be accessed
Write-ThroughApp writes to cache → cache writes to DB synchronouslyStrong consistency, critical data
Write-Behind
(Write-Back)
App writes to cache → cache writes to DB asynchronouslyWrite-heavy, eventual consistency OK
Read-ThroughApp only talks to cache → cache fetches from DB on missSimplify app logic, consistent reads
Refresh-AheadCache proactively refreshes before TTL expiresPredictable access patterns

🔄 Cache-Aside (Most Common)

Read Flow

  1. 1. Check cache for key
  2. 2. HIT: Return cached value
  3. 3. MISS: Query database
  4. 4. Store result in cache with TTL
  5. 5. Return result

Write Flow

  1. 1. Update database first
  2. 2. Invalidate cache (delete key)
  3. 3. Next read will re-populate cache

⚠️ Don't update cache on write—invalidate it!

🗑️ Cache Invalidation Strategies

TTL (Time-To-Live)

Data expires after X seconds

✓ Simple, automatic

✗ Stale reads possible

Event-Based

Invalidate on write/update events

✓ Fresh data

✗ More complex

Version-Based

Include version in cache key

✓ No explicit invalidation

✗ Key management

🚮 Eviction Policies

PolicyEvictsUse Case
LRULeast Recently UsedGeneral purpose (most common)
LFULeast Frequently UsedWhen access frequency matters
FIFOFirst In, First OutSimple, predictable
RandomRandom selectionCPU efficiency over accuracy

⚠️ Common Cache Problems

Cache Stampede

Many requests hit DB when cache expires

Fix: Locking, refresh-ahead, staggered TTL

Cache Penetration

Queries for non-existent keys hit DB

Fix: Cache null values, bloom filter

Hot Key

Single key overwhelms one cache node

Fix: Replicate hot keys, local cache

Redis vs Memcached

FeatureRedisMemcached
Data StructuresRich (lists, sets, hashes)Simple key-value
PersistenceYes (RDB, AOF)No
ClusteringNative clusterClient-side
Memory EfficiencyGoodBetter (slab allocator)
Multi-threadingSingle-threaded*Multi-threaded

*Redis 6.0+ has I/O threading

🎯 Interview Template

"I'd use a [cache-aside/write-through] pattern here with [Redis] because [read-heavy/need data structures]. For invalidation, I'd use [TTL of X minutes/event-based invalidation] to balance freshness with performance."