Skip to content

Redis

Pam\Redis\Client is a small Redis client that ships with the runtime. It speaks RESP2 over PAM’s async sockets, so while Redis is answering, only the current request’s Fiber waits; the worker keeps serving other requests. It needs no PHP extension.

It covers the common cases directly (get, set, delete) and lets you send any other command with command() or batch commands with pipeline().

index.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
use Pam\Redis\Client as Redis;
Server::create(static function (Request $request, Response $response): Response {
$redis = new Redis(host: '127.0.0.1', port: 6379);
$visits = $redis->command(['INCR', 'visits']);
return $response->json(['visits' => $visits]);
})->listen(3000, '127.0.0.1');
use Pam\Redis\Client as Redis;
$redis = new Redis(
host: 'redis.internal',
port: 6379,
timeout: 2.0, // seconds per command, including connect
password: getenv('REDIS_PASSWORD') ?: null,
database: 1,
maxResponseBytes: 16 * 1024 * 1024,
cancellation: null, // optional CancellationToken for every command
);
Argument Default
host '127.0.0.1'
port 6379
timeout 5.0
password null (sends AUTH when set)
database 0 (sends SELECT when not 0)
maxResponseBytes 16 * 1024 * 1024
cancellation null

The connection opens lazily on the first command and stays open until the client is closed or destroyed. Read Sharing a Connection before you keep one client for the whole worker. There is no TLS or username (ACL) option; for those, use a Composer client or the redis extension if your runtime profile includes it.

$redis->set('greeting', 'hello'); // true
$redis->set('session:42', $payload, ttlSeconds: 3600);
$redis->get('greeting'); // "hello"
$redis->get('missing'); // null
$redis->delete('greeting', 'session:42'); // number of keys removed

set() takes string values only; encode arrays and objects yourself (for example with json_encode()).

command() sends one command and returns the decoded reply: strings for simple and bulk strings, int for integers, null for a nil reply, and arrays for multi-bulk replies (nested up to 32 levels).

$redis->command(['HSET', 'user:42', 'name', 'Alice', 'plan', 'pro']);
$user = $redis->command(['HGETALL', 'user:42']); // ['name', 'Alice', 'plan', 'pro']
$redis->command(['EXPIRE', 'user:42', 600]);
$redis->command(['ZADD', 'leaderboard', 1500, 'alice']);

Arguments may be strings, integers or floats.

pipeline() writes several commands in one round trip and returns their replies in order:

[$set, $incr, $ttl] = $redis->pipeline([
['SET', 'rate:alice', '0', 'EX', '60', 'NX'],
['INCR', 'rate:alice'],
['TTL', 'rate:alice'],
]);

Pipelines are not transactions. Wrap commands in ['MULTI'] and ['EXEC'] inside the pipeline when you need them applied atomically, or use a Lua script with EVAL.

  • An error reply from Redis (-ERR ..., -WRONGTYPE ...) throws Pam\Redis\RedisException with the server’s message. So do protocol problems, a failed AUTH or SELECT, oversized replies and the command timeout (Redis operation timed out.).
  • A network failure, such as a refused connection, surfaces as the underlying RuntimeException (for example Unable to write to stream.).
  • After any failure, the client closes its connection and reconnects on the next command. It never retries a command for you.
use Pam\Redis\RedisException;
try {
$value = $redis->get('feature:checkout');
} catch (RedisException | RuntimeException $exception) {
$value = null; // fall back to defaults when the cache is down
}

close() closes the connection explicitly; it also happens when the client object is destroyed.

A client owns exactly one connection and has no internal locking. While one command waits for its reply, the request Fiber is suspended and the worker may run another request. If that request sends a command on the same client, the two exchanges interleave on one socket and the replies get mixed up.

Pick one of these patterns:

  • One client per request (simplest): create the client inside the handler, as in the first example. You pay one TCP connect per request.
  • One client per worker, serialized: keep a client and a Mutex at boot and run every command inside synchronized():
app/RedisConnection.php
<?php
declare(strict_types=1);
namespace App;
use Pam\Async\Mutex;
use Pam\Redis\Client;
final class RedisConnection
{
private static ?Client $client = null;
private static ?Mutex $mutex = null;
/** @param list<string|int|float> $arguments */
public static function command(array $arguments): mixed
{
self::$client ??= new Client(host: '127.0.0.1');
self::$mutex ??= new Mutex();
return self::$mutex->synchronized(static fn (): mixed => self::$client->command($arguments));
}
}

The same rule applies to concurrent futures inside one request.

BLPOP, XREAD BLOCK and SUBSCRIBE keep the connection busy. Use a dedicated client for them, and set timeout longer than the block time. Pub/Sub’s push messages are not supported by this client; for cross-worker WebSocket broadcasts use the Redis Streams adapter.

  • Nimbus has its own connection pool (Nimbus\Redis\RedisPool::fromEnvironment()), a Redis cache store, Redis job queues and Redis scheduler locks. See Scheduling and the Nimbus README.
  • Laravel keeps using phpredis or Predis through its normal configuration.