When the cache is empty for everyone: examining cache stampedes
A local multiprocess exercise in one Symfony project: a cold key, repeated reads under a lock, bounded admission, and recovery after failure or owner death.
The cache contains no home page. The first reader begins building it, and others arrive almost simultaneously. Each sees the same miss and repeats the work. By the time a result is finally saved, the application has already spent resources on several identical builds.
This is a useful cache-stampede case to examine: one missing result causes concurrent work on the same key. A larger server may delay overload, but it does not change the access order. A correct invalidation map also does not answer who should fill an empty cache.
Continue one article_demo on Symfony 8.1 and PHP 8.4+: several PHP processes on one Linux host compare unprotected reading with an explicit build-admission waiting budget. This is a local synthetic experiment rather than an HTTP-load benchmark.
First check what ordinary Cache Contracts already provide
For most reads, start with CacheInterface::get() and a callback that computes a missing value. The Symfony Cache documentation describes built-in locking on a per-host basis and probabilistic early recomputation. That protection belongs to Cache Contracts; PSR-6 calls such as getItem() and save() do not add it themselves.
After loading the Composer autoloader, a short example looks like this:
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\ItemInterface;
$cache = new FilesystemAdapter('contracts_demo_'.bin2hex(random_bytes(6)));
$key = hash('sha256', 'journal-a|uk|home');
$value = $cache->get($key, function (ItemInterface $item): array {
$item->expiresAfter(60);
return ['title' => 'Synthetic home page'];
});
The random namespace isolates this demonstration run. In a real application, readers of the same result must use a consistent namespace and key. Creating a fresh namespace for each HTTP request would simply prevent them from sharing a cache.
The beta parameter controls early recomputation; 0 disables that particular mechanism. It does not disable every lock. Before introducing your own mechanism, identify the requirement that the standard call does not cover in your contract. In this exercise, that requirement is an explicit budget for waiting for permission to build. The next section therefore uses a separate PSR-6 policy, not an additional lock around Contracts get().
Sequential calls do not reproduce a concurrent miss
If a function is called repeatedly in a loop, the first iteration may fill the cache and every later iteration may read the ready value. That tests repeated access, not the moment when several processes have already observed a miss.
The exercise starts several child PHP processes through Symfony Process. Each opens the shared cache directory, performs its first read, and marks itself ready only after recording a miss. It then waits at a barrier. The coordinator opens that barrier once every participant has left its marker.
In the baseline, each process computes a value after the barrier, without another read or a lock. For this deliberately synchronized scenario, we therefore expect a separate callback start from every participant. There is no need to guess whether the requests happened to overlap: all have already observed the cold key.
In the protected version, the same barrier comes before lock contention. Both waves use fresh, separate directories so that an earlier attempt cannot warm the next one. Barrier markers belong to the test harness, not the caching algorithm. Waiting at the barrier is outside the build-admission budget.
Permission to build belongs to a particular key
The local setup uses Symfony Lock with FlockStore. Participants share an absolute lock directory on the same physical filesystem. The lock name includes the result key; one global name would make independent pages wait for each other.
After the first miss, a process tries to acquire the lock with the nonblocking call acquire(false). Between attempts it checks the cache, which another participant may already have filled. One more read is required after acquiring the lock. Otherwise, a process arriving late at a free lock will repeat work that has already finished.
The complete src/Stampede/BoundedCache.php shows the admission loop. MonotonicClock and WaitBudgetExceeded belong to this teaching module:
<?php
declare(strict_types=1);
namespace App\Stampede;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Lock\LockFactory;
/** Local PSR-6 teaching policy. Do not wrap a Cache Contracts get() with this lock. */
final class BoundedCache
{
public function __construct(private CacheItemPoolInterface $cache, private LockFactory $locks)
{
}
public function get(string $key, \Closure $builder, int $waitBudgetMs, ?\Closure $afterMiss = null): mixed
{
if ($waitBudgetMs < 1 || $waitBudgetMs > 60000) {
throw new \InvalidArgumentException('Wait budget must be between 1 and 60000 ms.');
}
$item = $this->cache->getItem($key);
if ($item->isHit()) {
return $item->get();
}
// The optional test barrier is outside the admission-wait budget.
$afterMiss?->__invoke();
$deadline = MonotonicClock::now() + $waitBudgetMs * 1000000;
$lock = $this->locks->createLock('cache-build:' . $key, null);
while (true) {
$item = $this->cache->getItem($key);
if ($item->isHit()) {
return $item->get();
}
if (MonotonicClock::now() >= $deadline) {
throw new WaitBudgetExceeded();
}
if ($lock->acquire(false)) {
try {
// Scheduling or the acquire call itself may have crossed the deadline.
if (MonotonicClock::now() >= $deadline) {
throw new WaitBudgetExceeded();
}
$item = $this->cache->getItem($key);
if ($item->isHit()) {
return $item->get();
}
if (MonotonicClock::now() >= $deadline) {
throw new WaitBudgetExceeded();
}
$value = $builder();
$item->set($value)->expiresAfter(60);
if (!$this->cache->save($item)) {
throw new \RuntimeException('Cache write failed.');
}
return $value;
} finally {
$lock->release();
}
}
// Polling is a lab choice, not a claim of a hard real-time bound.
usleep(5000);
}
}
}
The loop checks the deadline before acquire, after acquire, and immediately before the builder following the repeated cache read. A ready hit can return without another build. Saving is checked explicitly; finally releases the lock. This mechanism uses PSR-6 without placing another lock around Contracts get().
The waiting budget is not a deadline for the whole operation
Timing uses PHP hrtime(): monotonic time does not depend on adjustments to the calendar clock. The setup requires 64-bit PHP and compares integer nanoseconds. It refuses to continue if the required monotonic clock is unavailable.
The budget limits waiting for admission to the critical section on a cold key. It does not interrupt a callback that has already gained permission to build, and it does not limit filesystem I/O duration. A scheduled process pause can also last longer because of operating-system scheduling. The loop therefore provides neither a hard real-time guarantee nor a maximum HTTP-request duration.
When the budget is exhausted and no ready value exists, BoundedCache::get() throws WaitBudgetExceeded without starting its own builder. The product must then choose a response: a controlled temporary failure, an explicitly permitted older value, or another scenario. Silently falling back to unrestricted computation would recreate the original stampede.
An older value is not always allowed: changing content visibility, for example, may impose stricter requirements. Such a policy needs defined limits on data suitability. This exercise does not implement serving stale responses.
An exception and an owner's death need different checks
If the callback throws, the finally block releases the lock. No incomplete value is saved, and the next reader can attempt a build. The log must retain both starts: the unsuccessful attempt and the successful one. A single ready item does not imply that its callback has run only once throughout its history.
A separate scenario stops a child process after its builder starts, while it still owns the lock and has not saved a value. The coordinator signals only a process that it started itself. Once termination is confirmed, a new participant should obtain the local lock and fill the cache.
FlockStore locks do not expire; release is tied to the process resource. This is not a lease with an arbitrary TTL or a distributed owner-election algorithm. A lock file remaining on disk does not by itself prove that an active owner exists.
What the setup should establish
| Scenario | What to check |
|---|---|
| Synchronized baseline | Every participant observed a miss and began a build |
| Protected cold key | One builder starts; the others receive the shared value |
| Warm repeated wave | No additional builder starts |
| Another participant holds the lock | The budget expires without starting the builder |
| First builder throws | A subsequent attempt proceeds, while the failed start remains in the log |
| Owner dies | A new local process recovers the build |
| Different key | Holding the first key does not block an independent result |
Callback starts are written to shared JSONL with locking around the append itself. Without that, the observation counter could lose records and create the appearance of a single builder. The log is read for the scenario summary after the corresponding child processes have finished.
The harness preserves process responses, completed scenarios, and an error when a check differs from the expectation. Child-call time includes the test-barrier wait, so it must not be called API latency. The artificial pause inside the callback only makes concurrency convenient to exercise; it does not model a real database.
Add src/Stampede, two Console commands, and tests/Stampede to the same application. Use Linux, 64-bit PHP, proc_open, local filesystem locks, and permission to terminate owned child processes. Participants must share cache and lock directories on one local filesystem; NFS and separate container filesystems are outside the experiment.
Add native dependencies from the existing article_demo root, preserving its composer.json/lock and earlier capabilities:
composer require symfony/lock:'8.1.*' symfony/process:'8.1.*'
Merge the command entries below into the existing services block, preserving the rest of the configuration.
services:
App\Command\StampedeDemoCommand: ~
App\Command\StampedeWorkerCommand: ~
From the same application root, run the harness at a new absolute directory:
APP_ENV=dev APP_DEBUG=0 php bin/console cache:clear --no-debug
STAMPEDE_WORKSPACE="$(mktemp -d)"
php bin/console app:stampede-demo "$STAMPEDE_WORKSPACE/run"
The run target must not exist yet. The harness uses app:stampede-worker for its own child processes. It operates on synthetic cache files and owned process signals, without external APIs or production workers.
Four unit tests with 11 assertions check admission boundaries, including the final deadline check before the builder. The separate multiprocess experiment has seven groups: baseline, protected, warm, held lock, exception, owner death, and different key. A callback-start count is neither latency nor throughput.
The seven executed multiprocess groups recorded these callback starts: baseline 8, protected 1, warm +0, held lock 0, exception recovery 2, owner death recovery 2, and different key 1. This observes a synthetic run rather than guaranteeing one callback over the entire history of a key.
Where the conclusion stops
Stampede protection also does not remove the late-fill race: a builder may read old data before a change and save it after invalidation. Versions or another freshness-coordination mechanism are needed for that. Reducing duplicate work and ensuring the correctness of its result are separate requirements.
The conclusion concerns one host, its local filesystem, and the installed components. A callback may run again after failure or owner death. Distributed coordination, lease renewal, HTTP/FPM load, stale serving, and production-performance guarantees remain outside the model. A shared key, repeated read, and bounded admission reduce duplicate work in this setup; result freshness needs a separate mechanism.