Caching
Where: client → CDN → API gateway → application cache (Redis/Memcached) → DB buffer pool.
| Strategy | How | Trade-off |
|---|---|---|
| Cache-aside (lazy) | app reads cache, on miss reads DB and fills | simple, most common; first read slow, possible stale |
| Read-through | cache library loads from DB on miss | cleaner app code |
| Write-through | write cache + DB synchronously | consistent; slower writes |
| Write-back | write cache, flush to DB async | fast writes; risk of loss |
| Write-around | write DB only, cache fills on read | avoids polluting cache |
- Eviction: LRU (default), LFU, TTL.
- Pitfalls: thundering herd / cache stampede (use request coalescing, locks, or probabilistic early refresh), hot keys (replicate the key, local in-process cache), invalidation (delete-on-write + TTL as a safety net), cache penetration (cache negative results, Bloom filter).
read(k): v = cache.get(k)
if v is None: v = db.get(k); cache.set(k, v, ttl)
write(k): db.put(k, v); cache.delete(k) # delete, don't update -> avoids races