Working with Distributed Caching

1. Understanding Cache Strategies

StrategyRead PathWrite Path
Cache-aside (lazy)App reads cache; on miss, load from DB & populateApp writes DB; invalidate cache
Read-throughCache loads from DB transparentlyApp writes DB
Write-throughCache always queried firstCache writes DB synchronously
Write-behindCache always queriedCache writes DB async (risk of loss)
Refresh-aheadPredictively reload before TTL

2. Implementing Read-Through Caching

Example: Caffeine + LoadingCache

LoadingCache<String, User> cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .expireAfterWrite(Duration.ofMinutes(10))
    .recordStats()
    .build(key -> userRepo.findById(key));

User u = cache.get("user:42"); // loads from DB on miss

3. Implementing Write-Behind Caching

PropertyDetail
ProsLow write latency; write coalescing
ConsData loss on cache crash; ordering issues
Use casesHigh-write metrics, counters
MitigationsPersist queue (Redis Streams), shorter flush interval

4. Implementing Cache Invalidation Strategies

MethodDetail
TTLAuto-expire after N seconds
Explicit DELETEApp invalidates on write
Versioned keysuser:42:v3 bumped on update
Event-drivenSubscribe to DB CDC; invalidate
Write-throughUpdate cache as part of write
Note: "There are only two hard things in CS: cache invalidation and naming things." — Phil Karlton

5. Handling Cache Coherence

PatternDetail
Single source of truthOne cache shard owns key
Pub/sub invalidationBroadcast deletes (Redis CLUSTER, ElastiCache)
VersioningCheck version on read
Quorum readsMulti-replica caches

6. Implementing Distributed Cache Partitioning

MethodSystem
Consistent hashMemcached client (Ketama), Redis Cluster
Hash slotsRedis Cluster (16384 slots)
Client shardingApp hashes key → instance
ProxyTwemproxy, Envoy Redis filter

7. Understanding Cache Stampede Problem

CauseMitigation
Many clients miss simultaneously
Solution: Lock / mutexSingle loader per key (singleflight)
Solution: Probabilistic early refreshXFetch algorithm
Solution: Stale-while-revalidateServe stale; async refresh

8. Implementing Cache Warming

TriggerDetail
StartupPreload hot keys from DB
ScheduledRefresh top-N every hour
Replay logsReplay last hour's reads
PredictiveML-based prefetch

9. Implementing Cache Eviction Policies

PolicyBehaviorBest For
LRUEvict least recently usedGeneral purpose
LFUEvict least frequently usedStable hot set
FIFOEvict oldest insertionStreaming workloads
RandomRandom evictionCheap; near-LRU
TinyLFU / W-TinyLFUFrequency sketch + LRU windowCaffeine default
ARCAdaptive between recency & frequencyMixed workloads

10. Handling Cache Penetration and Breakdown

ProblemCauseSolution
PenetrationQueries for non-existent keys bypass cacheCache negative results; bloom filter pre-check
BreakdownHot key expires; flood to DBMutex / singleflight; never expire hot keys
AvalancheMany keys expire simultaneouslyJittered TTLs; staggered refresh