- Laravel
- cache
- concurrency
Lock the rebuild, not the read
Wrap the expensive rebuild in Cache::lock() so one request fills the key while the others wait a moment and read the result.
1 min read
When a hot cache key expires on a busy page, every request that misses runs the same slow query at the same time. The lock goes around the rebuild only; reads stay lock-free.
$report = Cache::get('report') ?? Cache::lock('report:build', 10)->block(5, function () {
return Cache::remember('report', 3600, fn () => Report::build());
});The first request takes the lock and rebuilds. The others block for up to five seconds, then run Cache::remember, which finds the fresh value and returns it without a second rebuild.
Use it when the rebuild costs more than a few hundred milliseconds. For a cheap key the lock is just overhead.