Challenge
A cache stampede happens when a hot key expires and every concurrent request reads a miss at the same instant, so each one recomputes the same expensive value and hits the database together. Laravel's plain Cache::remember() has no protection against this.
Approach
- Two macros on Laravel's cache repository:
rememberWithLock()wraps the recompute in an atomic lock with double-checked reads so a cold key is computed exactly once rememberXFetch()implements probabilistic early expiration (the XFetch algorithm), refreshing hot keys before they expire through a queued job or inline, so readers never wait after the first fill- Supports Laravel 6 through 13 and PHP 7.2 through 8.5 from a single package, with Composer resolving the matching release line
- Concurrency proof in the test suite: 50 forked workers hit the same cold key on Redis 7 in CI
Impact
Measured, not claimed: with 50 concurrent workers, plain remember() runs the callback 50 times, both guarded strategies run it once. 98 tests run across every supported Laravel version on each CI leg. Published on Packagist under the MIT license.