Lesson 5 of 9 · 25m
Caching Layers: Hit Ratio, Stampede Control, and Invalidation Without Magic
How browser, CDN, reverse proxy, object, and database caching fit together — and how to avoid stampedes, stale writes, and cache poisoning.
Caching is easy to add and hard to reason about because every layer has different ownership, invalidation rules, and blast radius. The correct question is never 'should we cache this?' It is 'who is allowed to see a stale copy, for how long, and what happens when everyone expires at once?'
The layers have different jobs
browser/CDN shared HTTP objects, static assets, anonymous pages
reverse proxy fast HTML or API responses near the application
Redis/Memcached application objects, fragments, rate counters
APCu node-local immutable metadata
database buffer pool and query-working-set localityStatic assets should carry content hashes and immutable cache headers; anonymous HTML can often tolerate seconds or minutes of staleness; personalized responses should be explicit and defensive:
Cache-Control: public, max-age=31536000, immutable
Cache-Control: public, max-age=30, s-maxage=300, stale-while-revalidate=60
Cache-Control: private, no-store
Vary: Cookie, AuthorizationA missing Vary or careless shared cache key is how one customer's account page gets served to another customer. That is not a performance bug; it is a data breach.
Stampede control matters more than hit ratio
When a hot key expires, hundreds of workers can regenerate the same object simultaneously. Use request coalescing or probabilistic early refresh:
$value = $redis->get($key);
if ($value === null) {
$lockKey = $key . ':build';
if ($redis->set($lockKey, '1', ['nx', 'ex' => 10])) {
$value = rebuildExpensiveValue();
$redis->set($key, $value, 600);
$redis->del($lockKey);
} else {
usleep(20_000);
$value = $redis->get($key) ?: rebuildCheapFallback();
}
}This is not perfect distributed locking; it is congestion control. Add jitter to TTLs so keys do not expire in synchronized waves.
Invalidation is a product requirement
Event-driven invalidation is best when writes are rare and correctness matters. TTLs are best when staleness is tolerable and traffic is high. Versioned keys (user:42:v7) avoid deleting unknown dependent keys but require disciplined version storage. There is no universal answer — write down the staleness contract per object.
Field notes
- Measure hit ratio per key family, not one global number; a 95% average can hide 10% on the path that matters.
- Cache negative results briefly to stop hot misses hammering the database, but do not cache authorization failures forever.
- Redis eviction policy changes semantics.
allkeys-lruwill evict sessions or queues if you misuse the same instance. - Beware cache keys built from unnormalized input; trivial casing or ordering differences can fragment the cache.
Was this lesson helpful?