advanced
Backend caching
Cache expensive reads or computations with explicit keys, invalidation, TTLs, stampede protection, and consistency expectations.
Backend caches store expensive read results or computed values—often in Redis or in-process LRU—with explicit keys, TTLs, invalidation, and stampede protection.
| Pattern | Use when | |---------|----------| | Cache-aside | App reads cache, on miss loads DB and sets key | | Write-through | Writes update cache and DB together | | TTL | Stale data acceptable for short window | | Singleflight | Many misses for same hot key collapse to one rebuild |
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const fresh = await loadFromDb(id);
await redis.setex(key, 60, JSON.stringify(fresh));
Define **consistency** expectations: can users see stale inventory for 30s? Invalidate on writes that change authoritative data. Monitor hit rate, eviction, and memory.
On interviews: cache stampede; thundering herd; caching personalized data; when CDN is enough vs Redis.
Common pitfalls: no invalidation on update; caching errors; unbounded in-process cache on multi-tenant keys.
The trade-off is speed and DB offload versus staleness bugs and operational complexity.
Checklist:
- Name TTL and invalidation per key pattern.
- Protect hot keys with singleflight.
- Never cache secrets or per-user secrets in shared keys.
- Alert on hit-rate collapse.