Laravel Caching: Tags, Stampede Locks &amp; Cache-Aside | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com) [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles  ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

  [ home ](https://www.msaied.com)    [ articles ](https://www.msaied.com/articles)    Laravel Caching Strategies: Tags, Stampede Prevention, and Cache-Aside at Scale        On this page       1. [  Beyond remember(): Production Caching in Laravel ](#beyond-coderemembercode-production-caching-in-laravel)
2. [  Cache Tags for Granular Invalidation ](#cache-tags-for-granular-invalidation)
3. [  Stampede Prevention with Atomic Locks ](#stampede-prevention-with-atomic-locks)
4. [  The Cache-Aside Pattern as a First-Class Service ](#the-cache-aside-pattern-as-a-first-class-service)
5. [  Key Takeaways ](#key-takeaways)

  ![Laravel Caching Strategies: Tags, Stampede Prevention, and Cache-Aside at Scale](https://cdn.msaied.com/727/7873d7495db459e7a6e3bfbb8835852d.png)

  #laravel   #caching   #redis   #performance  

 Laravel Caching Strategies: Tags, Stampede Prevention, and Cache-Aside at Scale 
=================================================================================

     2 Oct 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said  

       Table of contents

1. [  01   Beyond remember(): Production Caching in Laravel  ](#beyond-coderemembercode-production-caching-in-laravel)
2. [  02   Cache Tags for Granular Invalidation  ](#cache-tags-for-granular-invalidation)
3. [  03   Stampede Prevention with Atomic Locks  ](#stampede-prevention-with-atomic-locks)
4. [  04   The Cache-Aside Pattern as a First-Class Service  ](#the-cache-aside-pattern-as-a-first-class-service)
5. [  05   Key Takeaways  ](#key-takeaways)

 Beyond `remember()`: Production Caching in Laravel
--------------------------------------------------

Most Laravel applications start with `Cache::remember()` and never look further. That works until you hit two classic production problems: stale data that can't be selectively invalidated, and a thundering herd that hammers your database the moment a popular key expires. This article tackles both, plus a clean implementation of the cache-aside pattern.

---

### Cache Tags for Granular Invalidation

Cache tags let you group related keys and flush them together without touching unrelated entries. They require a tag-aware driver — Redis or Memcached.

```php
// Storing tagged entries
Cache::tags(['products', "product:{$product->id}"])
    ->put("product:{$product->id}:detail", $data, now()->addHour());

// Flush everything for one product on update
Cache::tags("product:{$product->id}")->flush();

// Flush the entire products namespace on bulk import
Cache::tags('products')->flush();

```

Tag granularity is a design decision. Tag too broadly and you over-invalidate; tag too narrowly and you miss stale entries. A useful rule: one tag per aggregate root (`product:{id}`) plus one per collection type (`products`). Flush the aggregate tag on any mutation, the collection tag only on structural changes (create/delete).

---

### Stampede Prevention with Atomic Locks

When a high-traffic key expires, dozens of requests can simultaneously find a cache miss and all query the database. Laravel's `Cache::lock()` solves this with an atomic Redis lock.

```php
function getPopularProducts(): Collection
{
    $key = 'products:popular';
    $ttl = 300;

    $cached = Cache::get($key);
    if ($cached !== null) {
        return $cached;
    }

    // Only one process rebuilds; others wait briefly then re-read
    $lock = Cache::lock('lock:' . $key, 10);

    try {
        if ($lock->get()) {
            // Double-check after acquiring the lock
            $cached = Cache::get($key);
            if ($cached !== null) {
                return $cached;
            }

            $data = Product::popular()->get();
            Cache::tags('products')->put($key, $data, $ttl);
            return $data;
        }
    } finally {
        optional($lock)->release();
    }

    // Lock not acquired — serve a short-lived stale value or wait
    return Cache::tags('products')->remember($key, 5, fn () => Product::popular()->get());
}

```

The double-check after lock acquisition is critical. Without it, every queued request rebuilds the cache sequentially after the first one finishes.

---

### The Cache-Aside Pattern as a First-Class Service

Rather than scattering `Cache::remember()` calls across controllers and repositories, encapsulate the pattern in a dedicated service.

```php
final class CacheAside
{
    public function __construct(private readonly Repository $cache) {}

    /**
     * @template T
     * @param array $tags
     * @param Closure(): T $loader
     * @return T
     */
    public function get(string $key, array $tags, int $ttl, Closure $loader): mixed
    {
        $store = $tags
            ? $this->cache->tags($tags)
            : $this->cache;

        return $store->remember($key, $ttl, $loader);
    }

    public function invalidate(string ...$tags): void
    {
        $this->cache->tags($tags)->flush();
    }
}

```

Bind it as a singleton and inject it wherever you need caching. This keeps cache key construction and tag management in one place, making it trivial to audit or swap drivers.

```php
// In a repository
public function findPopular(): Collection
{
    return $this->cache->get(
        key: 'products:popular',
        tags: ['products'],
        ttl: 300,
        loader: fn () => Product::popular()->get(),
    );
}

```

---

### Key Takeaways

- **Use cache tags** on Redis/Memcached to enable surgical invalidation per aggregate and per collection.
- **Atomic locks** with a double-check pattern eliminate thundering-herd stampedes on high-traffic keys.
- **Cache-aside as a service** centralises key naming, tag assignment, and TTL policy — don't scatter `remember()` calls.
- Keep TTLs short on collection caches and longer on immutable or slowly-changing aggregate data.
- Always test cache behaviour with `Cache::fake()` in unit tests; use a real Redis instance in integration tests to verify tag flushing.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Flaravel-caching-strategies-tags-stampede-prevention-and-cache-aside-at-scale-2&text=Laravel+Caching+Strategies%3A+Tags%2C+Stampede+Prevention%2C+and+Cache-Aside+at+Scale) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Flaravel-caching-strategies-tags-stampede-prevention-and-cache-aside-at-scale-2) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  Which cache drivers support tags in Laravel?        Only Redis and Memcached support cache tags. The file, database, and array drivers do not. If you call Cache::tags() on an unsupported driver, Laravel throws a BadMethodCallException at runtime. 

      Q02  What happens if the lock is never acquired in the stampede prevention example?        The fallback at the end of the function calls remember() with a very short TTL (5 seconds). This means non-lock-holding requests still get a value quickly, accepting a brief period of redundant queries rather than blocking indefinitely. 

      Q03  Should cache key construction logic live in the model or a dedicated service?        A dedicated service or repository is preferable. Embedding cache keys in Eloquent models couples persistence and caching concerns. A CacheAside service or a repository method keeps the logic in one auditable place and makes it easy to change key schemes without touching models. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://www.msaied.com/articles) 

 [ ![Laravel AI SDK: Tool-Calling Agents and Conversation Persistence](https://cdn.msaied.com/726/cde0e4e03a15ea0776e82aca8727f660.png) laravel ai agents 

### Laravel AI SDK: Tool-Calling Agents and Conversation Persistence

Build reliable tool-calling AI agents in Laravel using the AI SDK, with typed tool definitions, structured res...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 1 Oct 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/laravel-ai-sdk-tool-calling-agents-and-conversation-persistence-4) [ ![Laravel 14 Adds a defaults() Method to Eloquent Models](https://cdn.msaied.com/725/6d4daa85070ffb81d6a9a3e25a8ed08c.png) Laravel 14 Eloquent Model Defaults 

### Laravel 14 Adds a defaults() Method to Eloquent Models

Laravel 14 introduces a defaults() method for Eloquent models, letting you set dynamic default attribute value...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 30 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/laravel-14-adds-a-defaults-method-to-eloquent-models) [ ![Laravel AI SDK and Laravel MCP Security Fixes: Update Now](https://cdn.msaied.com/722/fbe8df92faa32e9b9cee984a18bd4411.png) security laravel-ai laravel-mcp 

### Laravel AI SDK and Laravel MCP Security Fixes: Update Now

Two security advisories were published for laravel/ai and laravel/mcp on September 30, 2026. Both are fixed—ru...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 30 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/laravel-ai-sdk-and-laravel-mcp-security-fixes-update-now) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://www.msaied.com)
- [Projects](https://www.msaied.com/projects)
- [Articles](https://www.msaied.com/articles)
- [Certificates](https://www.msaied.com/certificates)
- [Contact](https://www.msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
