contentintech

Caching Cheatsheet

Quick reference for cache layers, patterns, eviction policies, stampede fixes, and Redis vs Memcached.

RedisLRUInvalidationStampede
NotesCheatsheet

Core Formulas

hit_ratio  = hits / (hits + misses)
miss_ratio = 1 - hit_ratio
avg_latency = hit_ratio*cache_lat + (1-hit_ratio)*origin_lat
origin_load = total_rps * miss_ratio     # capacity-plan for THIS

Ex: cache 1ms, origin 40ms
  0.90 -> 4.9ms   |  0.99 -> 1.4ms
  50k rps @ 95% hit -> origin sees 2.5k rps

Where to Cache

LayerLatencyNote
Browser0Cache-Control, ETag; no remote purge
CDN/edge~10msStatic + cacheable API; purge lag
App-local~100nsPer-instance, not coherent
Redis~0.5msShared, coherent, network hop
DB buffern/aTransparent, not yours to control

Patterns

PatternBehaviorConsistency
Cache-asideApp loads on missEventual
Read-throughCache lib loads on missEventual
Write-throughWrite cache+DB syncStrong
Write-behindCache now, DB asyncLoss risk
Refresh-aheadReload before expiryEventual
v = cache.get(k)
if v is None:
    v = db.read(k)
    cache.set(k, v, ttl=300)   # always set a TTL
return v
# on write: db.write(); cache.delete(k)  # invalidate after commit

Eviction Policies

PolicyEvicts
LRULeast recently used (default)
LFULeast frequently used; scan-resistant
FIFOOldest inserted
TTLExpired entries
RandomRandom key; cheapest

Redis: allkeys-lru, volatile-lfu. Caffeine uses W-TinyLFU (beats LRU).

Failure Modes & Fixes

ProblemFix
Stampede (herd)Single-flight, per-key lock, jittered TTL, early refresh
Penetration (missing keys)Cache null sentinel + Bloom filter
Hot keyReplicate key#1..N, local cache tier
Stale (delete race)Delete after commit + short TTL, double-delete
Avalanche (mass expiry)Randomize TTLs across keys

Distributed & Engines

Routing

hash(key) % N        -> add node remaps ~all keys (bad)
consistent hashing   -> ring; add/remove moves ~1/N keys
  + virtual nodes to balance load
Redis Cluster        -> CRC16(key) % 16384 slots

Redis vs Memcached

RedisMemcached
TypesRich structuresStrings only
PersistRDB+AOFNone
ThreadsSingle coreMulti
HASentinel/ClusterClient-side

Section navigation