Cheatsheet

Caching

Cache layers, read and write strategies, eviction, TTLs, invalidation, stampede protection, hit-ratio maths, key design and common pitfalls.

01Where caches live

Cache layers from the user inwards
LayerHoldsTypical latencyInvalidation
Browser / clientStatic assets, API responses with cache headers0 ms (no request)Cache-Control, ETag, versioned URLs
CDN edgeStatic files, cacheable pages and API responses5–30 msTTL, purge API, versioned URLs
Reverse proxy / gatewayWhole HTTP responses< 1 ms addedTTL, purge
In-process memoryHot objects, config, lookups~100 nsTTL; each instance has its own copy
Distributed cache (Redis, Memcached)Shared objects, sessions, computed results~0.5–1 msTTL, explicit delete
Database buffer poolPages of tables and indexesManaged by the databaseAutomatic

02Read and write strategies

Caching strategies compared
StrategyHow it worksStrengthWeakness
Cache-aside (lazy loading)App reads cache; on miss reads DB and fills cacheSimple, caches only what is used, survives cache lossFirst read is slow; stale until TTL or delete
Read-throughCache library loads from DB on missLoading logic in one placeNeeds a cache that supports loaders
Write-throughWrite to cache and DB synchronouslyCache always fresh for written keysSlower writes; caches data that may never be read
Write-behind (write-back)Write to cache; flush to DB asynchronouslyVery fast writes, batchingData loss if cache fails before flush; complex
Refresh-aheadReload popular keys before they expireNo miss latency for hot keysWasted work if predictions are wrong
Cache-aside in pseudocode
value = cache.get(key)
if value is missing:
    value = db.query(key)
    cache.set(key, value, ttl)
return value

on update: db.write(key, value); cache.delete(key)   # delete, do not set

03Eviction and TTL

LRU (least recently used)
Evict the key untouched for longest. Good default for most workloads.
LFU (least frequently used)
Evict the key with fewest hits. Resists one-off scans; slower to adapt to new hot keys.
FIFO
Evict the oldest inserted key. Simple, ignores popularity.
Random
Evict any key. Cheap and surprisingly reasonable at large sizes.
TTL expiry
Every key expires after a fixed time regardless of memory pressure.
TTL guidance (starting points; tune with metrics)
DataSuggested TTLReason
Versioned static assets1 year, immutableURL changes on every release
Product catalogue, articlesMinutes to hoursChanges rarely; staleness acceptable
User profile, settings1–15 minutes plus delete on writeUsers notice their own stale data
Prices, stock levelsSeconds, or no cacheCorrectness matters more than speed
Negative results (not found)Short, e.g. 30–60 sStops repeated misses hammering the DB
  • Add random jitter to TTLs (e.g. 300 s ± 10%) so keys written together do not expire together.
  • Always set a TTL, even with explicit invalidation: it bounds the damage of a missed delete.

04Invalidation and stampedes

Delete on write
After updating the DB, delete the cache key. Next read reloads it. Safer than setting the new value, which can race with a concurrent stale read.
Versioned keys
Put a version in the key (user:42:v7). Bump the version instead of deleting; old entries expire naturally.
Event-driven invalidation
Publish change events (or use change data capture) and let caches delete affected keys.
Cache stampede
A hot key expires and thousands of requests miss at once, all hitting the database.
Stampede mitigations
TechniqueHow it helps
Request coalescing (single flight)Only one request per key loads from the DB; others wait for its result
Distributed lock on missFirst caller takes a short lock and refills; others serve stale or retry briefly
Stale-while-revalidateServe the expired value while one background task refreshes it
Probabilistic early refreshEach read has a growing chance to refresh as expiry approaches
TTL jitterSpreads expirations of keys created together

05Hit ratio maths

Formulas
hit ratio          h = hits / (hits + misses)
effective latency  = h × cache latency + (1 − h) × (cache latency + origin latency)
origin load        = total requests × (1 − h)
Example: cache 1 ms, database 20 ms, 10,000 RPS
h = 0.90 → 0.9 × 1 + 0.1 × 21 = 3.0 ms average,  1,000 RPS reach the DB
h = 0.99 → 0.99 × 1 + 0.01 × 21 = 1.2 ms average,   100 RPS reach the DB
  • Going from 90% to 99% hits cuts database load by 10x. Small hit-ratio gains matter a lot at the top end.
  • A cold or flushed cache sends full traffic to the origin; make sure the origin survives that, or warm the cache first.

06Key design and pitfalls

  • Namespace keys: service:entity:id[:variant], e.g. catalog:product:123:en.
  • Include everything that changes the value (locale, currency, user role) or users will see each other’s data.
  • Never cache personalised responses in a shared CDN without varying on the user.
  • Keep values small; split very large objects or store references.
  • Watch for hot keys: one celebrity key can saturate a single cache node. Replicate it or add a local in-process layer.
  • Treat the cache as optional: a cache outage should slow the system, not break it.
  • Measure hit ratio, eviction rate, memory use and latency per key prefix.