patternphplaravelModerate
Laravel Cache: Tags, Stampede Prevention, and Invalidation Strategy
Viewed 0 times
cacheremembertagsstampedelockflexibleRedisinvalidationthundering herd
Problem
Cache entries become stale or cause thundering herd problems when many requests simultaneously find a cold cache entry and all attempt to regenerate the same expensive value.
Solution
Use Cache::remember() to atomically fetch-or-store. Use Cache::flexible() (Laravel 11+) for soft expiry with background refresh. Group related cache keys with Cache::tags([]) for bulk invalidation. For critical cache stampede prevention use atomic locks: Cache::lock('key')->block(5, fn() => ...).
Why
Cache::remember() is not atomic by default on all drivers. Multiple processes can still execute the callback simultaneously. Cache tags require a driver that supports them (Redis, Memcached). Locks serialize access to the expensive computation.
Gotchas
- Cache tags are not supported by the file and database drivers
- Forgetting a tagged cache entry using the tag also removes entries with other keys but same tag
- Cache::forever() stores without expiry—remember to explicitly flush when data changes
- Cache::flexible() (Laravel 11+) serves stale data while refreshing in background
Code Snippets
Cache with tags and lock
// Tagged cache for easy group invalidation
$posts = Cache::tags(['posts', 'user:'.$userId])
->remember('user-posts-'.$userId, 3600, fn() => Post::byUser($userId)->get());
// Invalidate all post caches
Cache::tags(['posts'])->flush();Revisions (0)
No revisions yet.