Content · Web Development · PHP

Preventing Cache Stampedes in PHP

Use short-lived locks or stale-while-revalidate to avoid many workers recomputing one missing key.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 Admin

Use short-lived locks or stale-while-revalidate to avoid many workers recomputing one missing key.

What It Does and When to Use It


A local flock prevents duplicate refreshes on one host; distributed apps need a shared lock. APCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code.

Requirements, Inputs and Expected Behavior


Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Lock TTL must cover work duration and the fallback must remain safe if lock acquisition fails.

Example 1: Basic Operation


A local flock prevents duplicate refreshes on one host; distributed apps need a shared lock.

<?php
$lockName='cache-refresh:popular-products';
$handle=fopen(sys_get_temp_dir().'/cache-refresh.lock','c');
if (!$handle) throw new RuntimeException('Lock unavailable');
try { if (flock($handle,LOCK_EX|LOCK_NB)) { echo 'Only one local process refreshes'; flock($handle,LOCK_UN); } }
finally { fclose($handle); }

Example 2: Behavior and Validation


Spread cache expirations so hot entries do not all refresh simultaneously.

<?php
$ttl=300+random_int(-30,30);
echo 'Jittered TTL: ',$ttl,' seconds';

Practical Example: Application Use


Stale-while-revalidate may smooth spikes; bound the stale window for correctness.

<?php
$stale=['value'=>['count'=>9],'expires_at'=>time()-5];
if ($stale['expires_at']<time()) echo 'Serve stale briefly while one worker refreshes';

Important Behavior and Edge Cases


The second example highlights: Spread cache expirations so hot entries do not all refresh simultaneously. The practical example adds: Stale-while-revalidate may smooth spikes; bound the stale window for correctness.

Comparison with Related Approaches


ApproachWhat changes
APCu versus Redis and OPcacheAPCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code.
Choosing safelyDefine TTL, invalidation, and concurrency behavior separately from the cache storage API.

Common Beginner Mistakes


MistakeCorrect approach
Assuming a cache is shared across multiple serversConfirm process- and host-level cache scope; use a distributed store when needed.
Never invalidating cached dataSet a TTL or versioned cache key and test release-time invalidation.
Skipping operational constraintsLock TTL must cover work duration and the fallback must remain safe if lock acquisition fails.

Key Takeaways


  • Use short-lived locks or stale-while-revalidate to avoid many workers recomputing one missing key.
  • Stale-while-revalidate may smooth spikes; bound the stale window for correctness.
  • Define TTL, invalidation, and concurrency behavior separately from the cache storage API.
Share this resourceSend this page to someone who may find it useful.