Cheatsheet
Caching
Cache layers, read and write strategies, eviction, TTLs, invalidation, stampede protection, hit-ratio maths, key design and common pitfalls.
01Where caches live
| Layer | Holds | Typical latency | Invalidation |
|---|---|---|---|
| Browser / client | Static assets, API responses with cache headers | 0 ms (no request) | Cache-Control, ETag, versioned URLs |
| CDN edge | Static files, cacheable pages and API responses | 5–30 ms | TTL, purge API, versioned URLs |
| Reverse proxy / gateway | Whole HTTP responses | < 1 ms added | TTL, purge |
| In-process memory | Hot objects, config, lookups | ~100 ns | TTL; each instance has its own copy |
| Distributed cache (Redis, Memcached) | Shared objects, sessions, computed results | ~0.5–1 ms | TTL, explicit delete |
| Database buffer pool | Pages of tables and indexes | Managed by the database | Automatic |
02Read and write strategies
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Cache-aside (lazy loading) | App reads cache; on miss reads DB and fills cache | Simple, caches only what is used, survives cache loss | First read is slow; stale until TTL or delete |
| Read-through | Cache library loads from DB on miss | Loading logic in one place | Needs a cache that supports loaders |
| Write-through | Write to cache and DB synchronously | Cache always fresh for written keys | Slower writes; caches data that may never be read |
| Write-behind (write-back) | Write to cache; flush to DB asynchronously | Very fast writes, batching | Data loss if cache fails before flush; complex |
| Refresh-ahead | Reload popular keys before they expire | No miss latency for hot keys | Wasted work if predictions are wrong |
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 set03Eviction 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.
| Data | Suggested TTL | Reason |
|---|---|---|
| Versioned static assets | 1 year, immutable | URL changes on every release |
| Product catalogue, articles | Minutes to hours | Changes rarely; staleness acceptable |
| User profile, settings | 1–15 minutes plus delete on write | Users notice their own stale data |
| Prices, stock levels | Seconds, or no cache | Correctness matters more than speed |
| Negative results (not found) | Short, e.g. 30–60 s | Stops 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.
| Technique | How it helps |
|---|---|
| Request coalescing (single flight) | Only one request per key loads from the DB; others wait for its result |
| Distributed lock on miss | First caller takes a short lock and refills; others serve stale or retry briefly |
| Stale-while-revalidate | Serve the expired value while one background task refreshes it |
| Probabilistic early refresh | Each read has a growing chance to refresh as expiry approaches |
| TTL jitter | Spreads expirations of keys created together |
05Hit ratio maths
hit ratio h = hits / (hits + misses) effective latency = h × cache latency + (1 − h) × (cache latency + origin latency) origin load = total requests × (1 − h)
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.