log in
consulting hosting industries the daily tools about contact

Redis Pipelining in Laravel: Cache::many() Is Not What You Think

Cache::many() looks like it should batch your Redis reads. It doesn't pipeline them. Here's what that costs you at scale and how to fix it.

I spent an embarrassing amount of time assuming Cache::many() was giving me pipelined Redis reads in Laravel. It is not. And once you're at a volume where that distinction matters, you will feel it in your p99s.

What I Thought Cache::many() Was Doing

The name implies batching. You pass an array of keys, you get back an array of values. Surely Laravel is smart enough to pipeline those reads under the hood, right?

Nope. Here is the relevant bit from the Laravel RedisStore source (checked against Laravel 10):

public function many(array $keys): array
{
    $results = [];

    $values = $this->connection()->mget(array_map(function ($key) {
        return $this->prefix.$key;
    }, $keys));

    foreach ($values as $index => $value) {
        $results[$keys[$index]] = ! is_null($value) ? $this->unserialize($value) : null;
    }

    return $results;
}

It uses MGET, which is a single Redis command that returns multiple values in one round trip. That is legitimately good - one network hop for N keys. I am not complaining about MGET. The issue surfaces when your use case involves more than just getting string values: when you need hashes, sorted sets, mixed commands, or conditional logic per key. At that point you drop out of Cache::many() entirely and start stringing together individual calls, and suddenly you are back to N round trips.

The Actual Problem

I hit this hard on a project for a Seattle e-commerce client. Their product listing page needed to hydrate about 60-80 keys per request: inventory counts, pricing overrides, featured flags, and per-product metadata stored as hashes. Some were plain strings via the Cache facade, some were Redis hashes accessed directly. The page was loading in ~180ms on a warm cache. Seemed fine until they ran a sale and traffic spiked.

Under load, that number crept toward 400ms. The database was idle. Redis CPU was barely ticking. The culprit was round-trip latency multiplied by the number of sequential Redis calls. Even at sub-millisecond latency per hop, 70 sequential calls add up fast when you have 50 concurrent requests hammering the same app servers.

This is the problem Redis pipelining actually solves: you queue up a batch of commands client-side, flush them to Redis in a single write, and read all the responses in a single read. Network round trips go from N to 1, regardless of command type.

A Real Working Example

Here is the pattern I settled on. I wrap it in a small service class rather than scattering Redis::pipeline() calls everywhere.

<?php

namespace App\Services;

use Illuminate\Support\Facades\Redis;

class ProductCacheHydrator
{
    public function hydrate(array $productIds): array
    {
        $prefix = config('cache.prefix');

        // Build the pipeline - queue all commands before any network I/O
        $results = Redis::pipeline(function ($pipe) use ($productIds, $prefix) {
            foreach ($productIds as $id) {
                // Mix command types freely - this is where MGET can't help you
                $pipe->get("{$prefix}product:price:{$id}");
                $pipe->hgetall("{$prefix}product:meta:{$id}");
                $pipe->zscore("{$prefix}featured:scores", (string) $id);
            }
        });

        // Results come back as a flat array in command order
        $hydrated = [];
        $chunkSize = 3; // commands per product: get, hgetall, zscore

        foreach ($productIds as $index => $id) {
            $offset = $index * $chunkSize;
            $hydrated[$id] = [
                'price'    => $results[$offset],
                'meta'     => $results[$offset + 1] ?? [],
                'featured' => $results[$offset + 2],
            ];
        }

        return $hydrated;
    }
}

And calling it:

$productIds = $products->pluck('id')->all();
$cached = app(ProductCacheHydrator::class)->hydrate($productIds);

The key thing to internalize: everything inside the pipeline() closure is queued locally. No Redis calls happen until the closure returns. That means you cannot branch on a result mid-pipeline. If you need to do GET foo, then decide whether to SET bar based on that value, you cannot do it in one pipeline. That is a real constraint.

The Gotchas That Will Bite You

Result order is your contract. The flat array coming back from Redis::pipeline() is indexed by execution order, not by key name. If you lose track of which position corresponds to which command, you will silently hydrate the wrong data into the wrong fields. I keep a $chunkSize constant and calculate offsets explicitly, as above. It is verbose but it is obvious.

Serialization is your problem now. When you use Cache::put() / Cache::get(), Laravel handles serialization and deserialization transparently. When you drop to Redis::pipeline() and call $pipe->get(), you get back the raw stored value. If Laravel stored it with serialize() (which it does for non-scalar types), you need to unserialize it yourself.

$raw = $results[$offset];
$value = is_null($raw) ? null : unserialize($raw);

This trips people up constantly. You store something through the Cache facade, read it back through a raw pipeline, and get a string that starts with s: or a: and wonder why your array turned into garbage.

The prefix mismatch. Laravel's cache prefix (set in config/cache.php as prefix) is prepended when you use the Cache facade. It is not automatically prepended when you call Redis::pipeline() directly. I always pull config('cache.prefix') explicitly and prepend it myself, as shown above. Miss this and your pipeline reads will return nothing but nulls, which is a confusing failure mode.

Cluster mode complicates things. If you are on Redis Cluster (not Sentinel, actual Cluster), pipelining across keys that hash to different slots is not supported. All keys in a pipeline must land on the same slot. The standard workaround is hash tags: {product}:price:123 and {product}:meta:123 force both keys to the same slot. If you are on a single Redis instance or Sentinel setup, ignore this. If you are on Cluster, build the hash tag into your key schema from day one - retrofitting it is painful.

Transactions vs pipelines. Redis::pipeline() does not give you atomicity. If you need that, you want Redis::transaction() which wraps in MULTI/EXEC. Transactions have more overhead and their own quirks around WATCH. For read-heavy hydration, pipeline is almost always what you want.

Actual Numbers

On that e-commerce project, switching the product hydration from sequential Cache facade calls to a single pipeline cut that portion of the request from ~95ms to ~8ms under load. Same Redis instance, same data, same app servers. The difference was entirely round-trip elimination.

For smaller key counts (under 10 or so), the difference is usually noise. At 20+ mixed commands per request, it becomes measurable. At 50+, it is significant. At scale under load, it is the difference between a usable page and a timeout.

When I'd Reach for This

I use raw pipelining when:

  • I need more than a handful of Redis operations in a single request and they cannot all be served by MGET (mixed command types, hashes, sorted sets, etc.)
  • I am hydrating a list of entities where I need 2-5 Redis reads per entity
  • Latency profiling has pointed at Redis round trips as the bottleneck - not before

I stick with Cache::many() / MGET when:

  • I only need plain string/serialized values
  • The key count is small
  • I want the automatic prefix handling and deserialization that the Cache facade provides

I would not pipeline when I need conditional logic mid-sequence, when I need Lua scripts (EVAL can often replace a pipeline with conditional logic and is atomic to boot), or when I am still in the "this might be fast enough" phase of a feature.

One More Thing

If you are reaching for pipelining because your cache read latency is high, also check whether you have a persistent Redis connection configured. In a PHP-FPM context without persistent_id set in your Redis config, you are reconnecting on every request, and that TCP handshake is adding latency that no amount of pipelining will fix.

// config/database.php, under redis.default
'options' => [
    'persistent' => 1,
    'persistent_id' => 'laravel_cache',
],

That one config change occasionally buys more than the pipeline work, depending on your infrastructure. Worth measuring.

Cache::many() is fine until it is not. When you hit the wall, the raw pipeline API is right there in Laravel - it is just not wired into the Cache facade abstraction. Know where the abstraction ends and what is underneath it, and you will not be debugging mysterious latency spikes at 2am during a sale event.

Related

Need help shipping something like this? Get in touch.