Cache Stampede Lock Plan
Plans stale-while-revalidate behavior and lock timing so busy routes do not stampede cache rebuilds.
Purpose
Plans stale-while-revalidate behavior and lock timing so busy routes do not stampede cache rebuilds.
Snippet details
ContextCacheLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Cache Stampede Lock Plan.
*
* Purpose:
* Plans stale-while-revalidate behavior and lock timing so busy routes do not stampede cache rebuilds.
*
* @param int $ttl_seconds Fresh cache lifetime.
* @param int $rebuild_seconds Estimated rebuild duration.
* @return array Cache stampede lock timing plan.
*/
function ogSnippetCacheStampedeLockPlan(int $ttl_seconds, int $rebuild_seconds): array {
if ($ttl_seconds < 60) {
$ttl_seconds = 60;
}
if ($rebuild_seconds < 1) {
$rebuild_seconds = 1;
}
$lock_seconds = $rebuild_seconds * 3;
$stale_seconds = $ttl_seconds + $lock_seconds;
return array('ttl_seconds' => $ttl_seconds, 'lock_seconds' => $lock_seconds, 'serve_stale_until_seconds' => $stale_seconds);
}
$stampede_plan = ogSnippetCacheStampedeLockPlan(300, 12);
echo $stampede_plan['lock_seconds'];