~/docs
Resonate
Resonate
0.x 0.9.0, current
Laravel RESP3 Cache
Toggle sidebar
Laravel RESP3 Cache
webpatser/laravel-resp3-cache 0.9.0

Laravel RESP3 Cache 0.x

Configuration

Cache store options, server features, client-side caching, cluster and sentinel connections.

Cache store

A store with 'driver' => 'resp3' in config/cache.php takes the same options as the redis driver (connection, lock_connection, prefix, serializable_classes), plus an optional client_tracking block.

'stores' => [
'resp3' => [
'driver' => 'resp3',
'connection' => 'cache', // key in config/database.php redis
'lock_connection' => 'default',
'prefix' => env('CACHE_PREFIX', 'app:'),
],
],

Key prefixing is the store prefix (or the global cache.prefix). The options.prefix setting on the Redis connection is not applied by this driver and is not supported.

Server features

The client reads the HELLO 3 reply once per connection and enables optional commands by server and version. Resp3Connection::capabilities() returns a ServerCapabilities object with delex(), setIfEq(), msetex(), increx(), has(string $feature), disable(string $feature), server(), version(), id(), mode(), isRedis(), isValkey() and toArray().

Feature Command Redis Valkey Used for
delex DELEX key IFEQ v 8.4.0 not detected Lock release
setIfEq SET key v IFEQ old 8.4.0 8.1.0 putIfEquals(), Resp3Lock::refresh()
msetex MSETEX numkeys k v ... EX s 8.4.4 9.1.0 putMany()
increx INCREX 8.8.0 not detected Reported only; no store method uses it yet

MSETEX needs Redis 8.4.4 because earlier 8.4 releases had an ACL bypass in that command. Valkey 9.2 added DELEX, but the client does not detect it there yet; force it on with the features option if you want it. Valkey answers HELLO as redis 7.2.x when its Redis compatibility mode is on; in that case the client runs INFO server once and reads valkey_version.

Override detection per connection with features in the Redis options. Each value is true, false or 'auto':

'redis' => [
'client' => 'resp3',
'options' => [
'features' => ['msetex' => false, 'delex' => 'auto'],
],
'default' => [/* ... */],
],

When the server answers a feature command with ERR unknown command, or with NOPERM and a message that contains "command" (an ACL or a proxy hides it), the feature is disabled for that connection and the call falls back once. After a sentinel failover the connection runs HELLO again, so a disabled feature is detected again.

Note: Cluster connections do not support features overrides. They detect capabilities from the first live master only.

Client-side caching

Opt-in, off by default. With it on, get() and many() on the resp3 cache driver are served from a process-local store, and the server tells the client when a key changed (CLIENT TRACKING, delivered as RESP3 push messages). With it off the store sends no extra command.

'stores' => [
'resp3' => [
'driver' => 'resp3',
'connection' => 'cache',
'prefix' => env('CACHE_PREFIX', 'app:'),
'client_tracking' => [
'enabled' => env('RESP3_CLIENT_TRACKING', false),
'mode' => 'optin', // or 'bcast'
'prefixes' => [], // bcast only; default: the store prefix
'noloop' => false,
'local_store' => 'auto', // 'array' | 'apcu'
'local_ttl' => 60, // seconds, upper bound for a local entry
'max_entries' => 10000,
'max_value_bytes' => 65536, // larger values are never cached locally
'max_bytes' => 33554432, // array store: key plus value bytes, 32 MiB
],
],
],

mode and local_store are validated only when enabled is true. A runnable demo is on the Examples page.

How it works:

  • In optin mode the client sends CLIENT TRACKING ON OPTIN once and prefixes each tracked read with CLIENT CACHING YES, so only cache reads are tracked. bcast mode tracks every key under the given prefixes instead.
  • A local entry lives for the smaller of local_ttl and the server TTL of the key.
  • Pushes are drained before every local hit, so an invalidation that has reached the socket is applied first. FLUSHDB and FLUSHALL clear the whole local namespace.
  • Writes (put, putMany, forever, forget, increment, decrement, putIfEquals) go to the server and then delete the local entry. Nothing is ever written to the local store by a write. add() and locks bypass the local store. flush() clears it, then runs FLUSHDB.
  • Values are stored locally as the serialized string and unserialized on every hit, so callers never share object instances.
  • A tracked read inside MULTI on the same connection throws LogicException.
  • tracking-redir-broken disables tracking for that connection; reads go to the server as before.

Local stores

  • array: a per-process LRU capped by max_entries, max_value_bytes per value and max_bytes for the whole store (key plus value bytes). Right for Octane, queue workers and other long-lived processes.
  • apcu: shared by the workers of one PHP-FPM pool. Needs the apcu extension (and apc.enable_cli=1 on the CLI) and a local_ttl of at least 1; with enabled true the config throws otherwise. Entry names are scoped with an HMAC keyed by app.key, and each value carries an HMAC over its entry name and value, so APP_KEY must be set. An explicit apcu store with an empty app key still works, but unsigned, like stock ApcStore.
  • auto: APCu when it is loaded, the connection is persistent, local_ttl is at least 1 and app.key is set, else array.

Warning: The APCu scope is not isolation. APCu is shared by everything under one PHP-FPM master, and any code there can list the entry names, read the values, delete entries and replay an earlier value of the same entry. Use apcu only when one FPM master serves one app.

Connections and persistence

Tracking belongs to one server connection. The local namespace is the process id plus the connection id from HELLO, so entries from another connection are never read. A plain PHP-FPM request opens a new connection and starts with an empty local store, so it gains nothing. To benefit under PHP-FPM set 'persistent' => true in the Redis options. A persistent socket is keyed per database, username and options.persistent_id. On reuse the handshake pipelines HELLO and a PING nonce to check the stream, and reconnects once if it is not aligned. When the HELLO id is unchanged the queued invalidations are applied and the entries stay; a different id drops the namespace.

Stores with the same tracking arguments (mode, prefixes, noloop) on one connection share one namespace; each keeps its own local store. A store whose tracking arguments differ gets no client-side cache on that connection and reads through to the server.

A single push drain is capped at 8 MiB. Over the cap the connection closes with a ConnectionException and the store falls back to a plain GET for that read. The tracking listener and a listener set with setPushListener() are chained, tracking first. Use a separate connection for pub/sub anyway.

Warning: 'noloop' => true makes the server skip invalidations caused by this connection's own writes. Writes made outside the store on the same connection (Redis facade writes) then never invalidate the local entries. Do not combine noloop with raw writes on the cache connection. Tag flushes are safe.

Client-side caching works on single node and sentinel connections. Cluster connections ignore the client_tracking block.

Cluster

Set 'cluster' => 'redis' and provide a clusters block, in the same shape as the standard Laravel cluster config.

'redis' => [
'client' => 'resp3',
'options' => [
'cluster' => 'redis',
],
'clusters' => [
'default' => [
['host' => env('REDIS_HOST', '127.0.0.1'), 'port' => 6379],
['host' => env('REDIS_HOST_2', '127.0.0.1'), 'port' => 6380],
['host' => env('REDIS_HOST_3', '127.0.0.1'), 'port' => 6381],
],
'options' => [
'timeout' => 2,
'cluster_read_replicas' => env('REDIS_CLUSTER_READ_REPLICAS', false),
],
],
],

Topology comes from CLUSTER SHARDS (Redis 7+) with a CLUSTER SLOTS fallback. The slot map is loaded lazily on the first command and refreshed on MOVED. ASK redirects send ASKING then the original command without touching the cached map. Failed nodes drop out of the pool with up to 5 retries (exponential backoff capped at 200ms).

'cluster_read_replicas' => true routes read commands to a random replica for the slot. Writes always go to the master. Replica connections get READONLY, again after every reconnect.

If the socket fails after a write command went out, the command is not sent again: the caller gets a ConnectionException with requestSent set, because the server may have run it. Read-only commands are retried within the retry budget, and so is any command that failed before it was written. A MULTI or WATCH lost with its socket is reported by one exception (sessionLost) and never continued on another node connection.

Multi-key commands (MGET, MSET, transactions) need all keys in one slot; use {hash tags}. The cache driver's many() and putMany() split per slot for you, and Resp3ClusterConnection::mgetAcrossSlots(array $keys): array does the same for raw MGET.

Sentinel

Set 'replication' => 'sentinel', the master service name and a list of seed sentinels.

'redis' => [
'client' => 'resp3',
'options' => [
'replication' => 'sentinel',
'service' => env('REDIS_SENTINEL_SERVICE', 'mymaster'),
'sentinel_password' => env('REDIS_SENTINEL_PASSWORD'),
'password' => env('REDIS_PASSWORD'),
'database' => 0,
'timeout' => 0.5,
],
'default' => [
['host' => env('REDIS_SENTINEL_1_HOST'), 'port' => 26379],
['host' => env('REDIS_SENTINEL_2_HOST'), 'port' => 26379],
['host' => env('REDIS_SENTINEL_3_HOST'), 'port' => 26379],
],
],

The connector queries the sentinels for the current master and opens a normal connection. Failover is reactive: a dropped connection or a READONLY reply from a demoted master triggers a fresh SENTINEL get-master-addr-by-name query. The seed list is rotated on every failed attempt. There is no background pub/sub on +switch-master; the next command notices.

After a failover a command is sent again only when nothing of it reached the server, or it cannot change data (read commands, PING, ECHO). Any other command whose request went out fails with a ConnectionException (requestSent). A MULTI or WATCH lost with its connection is reported by one exception (sessionLost); the next EXEC fails without being sent.

Sentinel queries default to plaintext without a username. Set 'sentinel_scheme' => 'tls' (or 'sentinel_ssl' => [...] with stream context options) and 'sentinel_username' for TLS-only or ACL sentinels.

Warning: The data plane connects to whatever address the sentinel returns. A TLS data plane behind plaintext sentinels trusts an unauthenticated answer. Enable sentinel TLS, or keep verify_peer on and pin peer_name in ssl.

Replica reads

'options' => [
'replication' => 'sentinel',
'service' => env('REDIS_SENTINEL_SERVICE', 'mymaster'),
'sentinel_read_replicas' => env('REDIS_SENTINEL_READ_REPLICAS', false),
// ...
],

With sentinel_read_replicas true, read commands go to replicas found via SENTINEL replicas <service>; replicas flagged s_down or o_down are filtered out. Writes, pipelines and EVAL/EVALSHA always go to the master. A read that finds no healthy replica falls back to the master. Selection is random. Normal replication lag applies: a read right after a write can return the previous value.

Idle connection check

Before each command the client checks, like phpredis, whether the server closed an idle connection, so the command goes out once on a new one instead of into a dead socket. The cost is one non-blocking stream_select() with a zero timeout per command. The check is skipped inside MULTI and WATCH, and after a caller-set connection state such as SELECT or CLIENT SETNAME.

Local development

make cluster-up # boots 6-node Valkey cluster on 127.0.0.1:7100-7105
make cluster-test # runs the cluster suite + tears it down
make cluster-down # tears it down manually
make sentinel-up # boots 1 master + 2 replicas + 3 sentinels
make sentinel-test # runs the sentinel suite + tears down
make sentinel-down # tears down manually