Redis Caching

Cache-Aside in Laravel with Redis: Invalidation, Stampedes and Redis Outages

For API endpoints that return the same data to many requests, such as product listings, category trees or public profiles, running the same database query on every request is wasted work. Cache-aside is the simplest fix: check the cache first, and only on a miss query the database and store the result for next time.

Laravel makes the basic version a one-liner with Cache::remember(). This guide covers that, and then the parts that decide whether caching helps or hurts in production: invalidating entries when data changes, preventing a cache stampede when a popular key expires, choosing keys, and what actually happens when Redis is unavailable.

How Cache-Aside Works

  1. The application asks the cache for a key.
  2. Hit: return the cached value without touching the database.
  3. Miss: run the query, store the result in the cache with an expiry (TTL), and return it.
  4. When the underlying data changes, delete the cached key so the next read loads fresh data.

The application owns all of this logic. The cache is just a key-value store, which is why the pattern works with any cache backend.

Step 1: Configure Redis as the Cache Store

Laravel needs either the phpredis PHP extension (faster, recommended) or the predis/predis Composer package to talk to Redis.

Bash
# phpredis via PECL (or your OS package, e.g. php8.3-redis on Debian/Ubuntu)
pecl install redis

# or, if you can't install extensions:
composer require predis/predis

Then point the cache at Redis in .env. Since Laravel 11 the variable is CACHE_STORE (older versions used CACHE_DRIVER):

.env
CACHE_STORE=redis
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=null

Laravel uses a separate Redis database for cache (REDIS_CACHE_DB, default 1) from the default connection, so clearing the cache doesn't wipe queues or sessions stored in Redis.

Step 2: Cache a Read Endpoint

PHP
// app/Http/Controllers/ProductController.php
namespace App\Http\Controllers;

use App\Http\Resources\ProductResource;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;

class ProductController extends Controller
{
    public function index()
    {
        $products = Cache::remember('products:active:v1', now()->addMinutes(10), function () {
            return ProductResource::collection(
                Product::where('is_active', true)->orderBy('name')->get()
            )->resolve();
        });

        return response()->json(['data' => $products]);
    }
}

Cache::remember() returns the cached value if the key exists. Otherwise it runs the closure, stores the result for 10 minutes, and returns it.

Note what gets cached: the closure returns plain arrays (the resolved API resource), not Eloquent models. Cached models are serialized PHP objects. They're larger, they break if you rename a class or property, and they bring back stale relationships. Caching the exact response shape is smaller and safer.

Step 3: Invalidate on Writes

A TTL alone means users may see stale data for up to 10 minutes after an edit. Delete the key whenever the data changes. Model events keep this in one place instead of in every controller that writes products:

PHP
// app/Models/Product.php
protected static function booted(): void
{
    $flush = fn () => Cache::forget('products:active:v1');

    static::saved($flush);
    static::deleted($flush);
}

And the write endpoints validate input instead of passing the raw request to the model:

PHP
public function update(UpdateProductRequest $request, Product $product)
{
    $product->update($request->validated()); // never $request->all()

    return new ProductResource($product);
}

Model events don't fire for query-builder bulk updates (Product::where(...)->update([...])). After those, forget the key explicitly.

If you cache many variations of the same data, such as one entry per page or per filter combination, deleting each key individually gets impractical. Two options:

  • Cache tags (supported by the Redis and Memcached stores): Cache::tags(['products'])->remember(...) and then Cache::tags(['products'])->flush() clears them all.
  • A version number in the key: store products:version in the cache and build keys like products:v{$version}:page:{$page}. To invalidate everything, increment the version. The old keys simply expire.

Step 4: Prevent Cache Stampedes

When a popular key expires, every request that arrives before it's rebuilt misses at once, and they all run the same expensive query at the same time. On a busy endpoint, that spike can overload the database the cache was protecting.

Laravel 11 added Cache::flexible(), which implements stale-while-revalidate:

PHP
$products = Cache::flexible('products:active:v1', [300, 900], function () {
    return ProductResource::collection(
        Product::where('is_active', true)->orderBy('name')->get()
    )->resolve();
});

For the first 300 seconds the value is fresh. Between 300 and 900 seconds it's served as-is, and Laravel refreshes it in the background after the response is sent. Only after 900 seconds does a request have to wait for the query. Popular keys get refreshed before they ever fully expire.

On older Laravel versions, wrap the rebuild in an atomic lock (Cache::lock('products:rebuild', 10)->block(5, fn () => ...)) so only one request runs the query while the others wait briefly and then read the fresh value.

Step 5: Decide What Happens When Redis Is Down

Cache::remember() does not fall back to the database if Redis is unreachable. The connection error is thrown as an exception, and the request fails with a 500. If your API should keep working without the cache, slowly but correctly, catch the failure explicitly:

PHP
use Illuminate\Support\Facades\Log;
use Throwable;

function rememberOrQuery(string $key, $ttl, \Closure $query)
{
    try {
        return Cache::remember($key, $ttl, $query);
    } catch (Throwable $e) {
        Log::warning('Cache unavailable, querying database directly', ['key' => $key, 'error' => $e->getMessage()]);
        return $query();
    }
}

Think about whether falling back is safe. If Redis normally absorbs most of your read traffic, sending all of it to the database at once can take the database down too. A short connection timeout (REDIS_TIMEOUT, or timeout/read_timeout in config/database.php) matters either way, so a hung Redis fails fast instead of holding every request.

💡 Tip: Name keys hierarchically and include a version (products:active:v1, user:42:profile:v2). The prefix makes keys easy to find with redis-cli --scan --pattern 'products:*', and bumping the version when the cached shape changes avoids reading old-format entries after a deploy.

Measuring It

Check that the cache is actually being hit. redis-cli INFO stats reports keyspace_hits and keyspace_misses for the whole Redis instance. For per-endpoint numbers, Laravel Pulse and Telescope both record cache hits and misses by key. Compare the endpoint's response time and query count before and after. If a key is rarely hit twice before it expires, caching it only adds work.

If the same records are also updated often and users expect to see their own changes immediately, look at write-through caching, which updates the cache on every write instead of deleting it.

Summary

  • Use Cache::remember() for cache-aside, and cache plain arrays or response data, not Eloquent models.
  • Invalidate on writes with model events, and use tags or versioned keys when one change affects many entries.
  • Use Cache::flexible() (or an atomic lock) for hot keys to avoid stampedes when they expire.
  • Redis failures throw exceptions. Decide deliberately whether to fall back to the database, and set short connection timeouts.
  • Configure the store with CACHE_STORE=redis on Laravel 11+, and validate input on write endpoints.
Advertisement