DEV Community

Cover image for Laravel Redis Caching: Cache-Aside, Keys and Invalidation
devTalk
devTalk

Posted on Originally published at dev-talk.com

Laravel Redis Caching: Cache-Aside, Keys and Invalidation

Most Laravel caching bugs are not about Redis. They are about what the code stores, how long it lives, and who removes it when the data changes. This is Part 1 of a two-part series on Redis caching in Laravel 13. Here we cover the basic read-through pattern, what Redis actually holds, and invalidation. Part 2 covers cache stampedes, locks, counters and memory limits.

Every example below was run on Laravel 13.40.0, PHP 8.3.6 with phpredis 5.3.7, and Redis 7.0.15. The outputs are copied from those runs.

Setup

Laravel's docs say Redis caching needs either the PhpRedis extension or the predis/predis package, and that PhpRedis is the default client. In .env:

CACHE_STORE=redis
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Enter fullscreen mode Exit fullscreen mode

Now write one value and look at what Redis stores:

Cache::put('product:42', ['id' => 42, 'name' => 'Widget'], 600);
Enter fullscreen mode Exit fullscreen mode
db1 (cache connection): laravel-database-laravel-cache-product:42
db0 (default connection): []
TTL=600 TYPE=string
RAW: a:2:{s:2:"id";i:42;s:4:"name";s:6:"Widget";}
Enter fullscreen mode Exit fullscreen mode

Three things to notice:

  • The key has two prefixes. laravel-database- comes from the Redis connection options (REDIS_PREFIX), and laravel-cache- comes from config/cache.php (CACHE_PREFIX). Both default to your slugified APP_NAME. The Laravel docs warn that two instances of the same app on one Redis server share the prefix and read each other's data, so give each its own REDIS_PREFIX.
  • Cache keys live in Redis database 1. The default cache connection uses REDIS_CACHE_DB (default 1), while the default connection uses database 0.
  • The value is a PHP-serialized string with a TTL. It is not JSON, so other languages can't read it, and what you store decides what you can safely unserialize later (see the model section below).

Cache-aside with remember()

The pattern: look in the cache, and on a miss load from the database and store the result. Cache::remember does exactly that:

use Illuminate\Support\Facades\Cache;

class ProductReader
{
    public function find(int $id): array|false
    {
        return Cache::remember("product:$id", 600, function () use ($id) {
            return Product::find($id)?->only(['id', 'name', 'price']) ?? false;
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

The Laravel docs describe it the same way: if the item does not exist, the closure runs and its result is stored. I counted closure executions across three calls with the same key:

value={"computed":true} closure_runs=1
value={"computed":true} closure_runs=1
value={"computed":true} closure_runs=1
Enter fullscreen mode Exit fullscreen mode

Why the example returns false for "not found"

I ran the closure three times in a row for four different return values and counted how often it executed:

null: closure ran 3 times in 3 calls
false: closure ran 1 times in 3 calls
empty-array: closure ran 1 times in 3 calls
zero: closure ran 1 times in 3 calls
Enter fullscreen mode Exit fullscreen mode

A closure that returns null is never cached, so every request for a product that doesn't exist goes to the database. Returning false (or any non-null placeholder) caches the "not found" answer for the TTL. Use a shorter TTL for negative results than for real ones so a newly created record doesn't stay invisible.

Cache arrays, not Eloquent models

This one is specific to Laravel 13. The default config/cache.php now contains 'serializable_classes' => false, and the upgrade guide says it was added to harden unserialization against gadget chain attacks if your APP_KEY leaks. The effect on a cached model:

Cache::put('user:model', User::find(1), 60);
get_class(Cache::get('user:model'));   // __PHP_Incomplete_Class
Enter fullscreen mode Exit fullscreen mode
model class on read: __PHP_Incomplete_Class
raw model value starts: O:15:"App\Models\User":36:{s:1
Enter fullscreen mode Exit fullscreen mode

The write works, the read silently gives you an unusable object. There are two ways out:

  1. Store plain arrays (what the upgrade guide recommends as the non-object option). They are smaller, they survive a class rename or refactor, and they don't depend on the unserialize allow-list:raw array value: a:3:{s:2:"id";i:1;s:4:"name";s:3:"ann";s:5:"email";s:16:"ann@example.test";}
  2. Allow-list the classes you intentionally cache, as the upgrade guide shows:// config/cache.php 'serializable_classes' => [ App\Models\User::class, ], With that in place the same test returned App\Models\User.

Apps upgraded from Laravel 12 may not have this key in their own config/cache.php. In the Laravel 13.40 source, a missing key resolves to null and the Redis store then calls plain unserialize(). I read that in the code and did not run an upgraded app, so check your config file.

Invalidate on write

A TTL is a fallback, not an invalidation strategy. When the underlying record changes, remove the key yourself, after the database write has committed:

public function rename(Product $product, string $name): void
{
    $product->update(['name' => $name]);

    Cache::forget("product:{$product->id}");
}
Enter fullscreen mode Exit fullscreen mode
after forget: NULL
Enter fullscreen mode Exit fullscreen mode

The next reader repopulates it through remember. If you put the same value back immediately instead (Cache::put), you avoid one miss but you also have to be sure the cached shape is identical to what the reader would build. Deleting is the simpler contract.

Tags: group keys so you can flush them together

When one change affects many keys (a product list, a category page, a search result), tags let you flush a group. Per the Laravel docs, tags are not supported by the file, dynamodb, database or storage drivers; Redis works.

Cache::tags(['products'])->put('product:1', 'Widget', 600);
Cache::tags(['products', 'sale'])->put('product:2', 'Gadget', 600);
Cache::tags(['users'])->put('user:1', 'ann', 600);

Cache::get('product:1');                       // NULL: tagged items need their tags to be read
Cache::tags(['products'])->get('product:1');   // 'Widget'

Cache::tags(['products'])->flush();
Enter fullscreen mode Exit fullscreen mode
get without tags: NULL
get with tags   : 'Widget'
after flush products -> product:1=NULL, product:2=NULL, user:1='ann'
Enter fullscreen mode Exit fullscreen mode

Flushing the products tag removed both products, including the one that also carried the sale tag, and left the unrelated users tag alone. Inside Redis, the keys of tagged items are namespaced with a hash, and each tag has its own bookkeeping key:

laravel-database-laravel-cache-<sha1>:user:1
laravel-database-laravel-cache-tag:sale:entries
laravel-database-laravel-cache-tag:users:entries
Enter fullscreen mode Exit fullscreen mode

Two practical consequences. You can't look up a tagged item by its plain key, so forgetting to pass the tags is a silent miss (shown above). And the leftover tag:sale:entries key shows the bookkeeping isn't removed for every tag on a flush, so don't use tags for an unbounded set of one-off values. Prefer a small, fixed set of tag names.

Never call Cache::flush() on a shared database

The docs say Cache::flush() ignores your prefix and removes everything in the cache store. I put a key from "another application" in the same Redis database and flushed:

mine after Cache::flush(): NULL
foreign key after flush: []  keys in db1: 0
Enter fullscreen mode Exit fullscreen mode

The foreign key was gone. If several applications use one Redis server, give each its own database number (REDIS_CACHE_DB) or its own server, and delete groups of keys with tags or forget instead of flushing.

Key design

  • Put the entity and the id in the key (product:42), and anything that changes the result (product:42:locale:en).
  • Don't put user input directly in a key without limiting its shape. Unbounded key names fill memory (Part 2).
  • Keep the format in one place (a small class or enum), so reads and invalidation can't drift apart.
  • Set a TTL on every cache key. Part 2 shows why a key without one can't be evicted under some memory policies.

Common mistakes

  • Caching Eloquent models in Laravel 13 without allow-listing the class.
  • Returning null for "not found" and wondering why the database still gets hit.
  • Relying on TTL alone for data users expect to see change immediately.
  • Reading a tagged item without its tags.
  • Using Cache::flush() on a Redis database other apps share.
  • Sharing one prefix between staging and production on the same Redis server. The docs note that changing a prefix later makes existing cached values and queued jobs under the old prefix be ignored, so choose it before go-live.

Alternatives

  • Predis instead of PhpRedis, if you can't install the extension. Set REDIS_CLIENT=predis and install the package. I only tested PhpRedis.
  • HTTP caching (ETag, Cache-Control) for responses that don't need a server-side cache at all.
  • The database or file store for tiny apps. Redis becomes worthwhile when you need tags, atomic operations or multiple servers sharing one cache.

Related Dev Talk articles

Frequently asked questions

Should I cache the query result or the final HTML/JSON?

Cache the smallest thing that is expensive to compute and cheap to reuse. Query results as arrays are the safest default. Full responses are fine when the output is identical for all users; otherwise the key must include whatever varies.

Is a long TTL always better for hit rate?

It raises the hit rate and the chance of serving stale data. If you invalidate on write, a long TTL is safe because writes keep the cache correct. If you can't invalidate precisely, keep the TTL short.

Why do cache keys and queue keys end up in different databases?

The default cache connection uses database 1 and the default connection uses database 0. Logical databases share one Redis server's memory and settings, so this separates keys, not resources. Part 2 covers what that means for eviction.

Do I need Redis for caching at all?

No. The database or file stores work. Redis adds speed, tags, atomic counters and locks that work across servers.

Sources


Originally published on DEV Talk.

Top comments (0)