PHP › Caching Strategies in PHP
How does the cache stampede problem occur, and what strategies help prevent it in a high traffic PHP application?
AdvancedAnswer
A cache stampede occurs when a popular cached item expires and many concurrent requests simultaneously attempt to recompute and repopulate that same expensive cache entry at once, temporarily overwhelming the backend resource the cache was meant to protect, and common prevention strategies include using a locking mechanism so only one request recomputes the value while others wait or serve a slightly stale version, and staggering expiration times slightly so many related cache entries do not all expire at the exact same moment.
if ($lock = $cache->lock('rebuild_top_products', 10)) {
$lock->get(function () use ($cache) {
$products = $database->getTopProducts();
$cache->put('top_products', $products, 3600);
});
}Real-world example A high traffic e commerce site experiences a brief but severe database load spike every time its heavily cached homepage data expires simultaneously across many servers, and resolves it by implementing a locking mechanism so only one server rebuilds the cache while others briefly serve the previous cached version.