Repository navigation
Description
Issue
When read_timeout expires after part of a bulk reply has arrived, phpredis throws socket error on read socket but leaves the socket open. The rest of the reply arrives later, and the next command on that connection reads it as its own reply. From then on the connection is out of step: each command returns the reply of an earlier command. In RedisCluster on 6.3.0 the leftover bytes are consumed silently and the offset grows, so the connection never recovers until the process ends.
We think this is what we hit in production. We run long-running PHP CLI workers that use RedisCluster (persistent, TLS, read_timeout 2 s) against AWS ElastiCache (Valkey 9.0, cluster mode). During a period of network trouble on the server side, two workers' connections went out of step and stayed that way for hours, until we restarted the processes. They logged GET replies for the wrong keys and Invalid reply type returned for DEL command, and SET NX lock results on those connections were unreliable. The workers retry a failed command on the same object, but any next command reads the leftover bytes.
Expected behaviour
When phpredis stops reading a reply before its end (timeout, EOF, or error), it closes the socket, so the next command reconnects and gets its own reply. redis_sock_gets() already does this when a header read fails.
Actual behaviour
The socket stays open with the rest of the reply unread. Output of the script below (the exact offsets vary a little between runs):
RedisCluster, 6.3.0: no error after the first exception, then replies are 15 commands behind and stay behind.
GET big => RedisException: socket error on read socket
GET key0 => false
GET key1 => false
...
GET key14 => false
GET key15 => 'value0'
GET key16 => 'value1'
GET key17 => 'value2'
Redis, 6.3.0: the leftover bytes cause protocol errors, but the socket stays open, then replies are 4 commands behind.
GET big => RedisException: socket error on read socket
GET key0 => RedisException: protocol error, got 'x' as reply type byte
GET key1 => RedisException: protocol error, got 'x' as reply type byte
GET key2 => RedisException: protocol error, got 'x' as reply type byte
GET key3 => RedisException: protocol error, got 'x' as reply type byte
GET key4 => 'value0'
GET key5 => 'value1'
Redis, develop @ 810984b, with a value that is CRLF-separated text (repro.php redis text 700): 584 protocol errors without a reconnect, then replies are 585 commands behind.
GET big => RedisException: socket error on read socket
GET key0 => RedisException: protocol error, got 'e' as reply type byte
GET key1 => RedisException: protocol error, got 'L' as reply type byte
...
GET key583 => RedisException: protocol error, got 'L' as reply type byte
GET key584 => false
GET key585 => 'value0'
GET key586 => 'value1'
RedisCluster, develop @ 810984b: in these tests it recovers after one more failed command, because the stricter header parsing on develop rejects the leftover bytes and the caller closes the socket. The socket is still left open after the short read, so leftover bytes that happen to parse as a valid reply (for example a line that starts with +) would still put it out of step.
GET big => RedisException: socket error on read socket
GET key0 => RedisClusterException: Error processing response from Redis node!
GET key1 => 'value1'
The same thing happens with node-directed RedisCluster commands when the whole reply is late (no partial read): $cluster->echo('key', 'x') with a 2.5 s delay throws Unable to send command at the specified node, the socket stays open, and the next commands read earlier replies.
I'm seeing this behaviour on
- OS: Linux (Docker
php:8.5-cli/php:8.5-cli-trixie); production on Linux - Redis: Valkey 9.0 (local, cluster mode, single node); AWS ElastiCache Valkey 9.0, cluster mode, TLS (production)
- PHP: 8.5.11
- phpredis: 6.3.0; also
develop@ 810984b
TLS and plain TCP behave the same. On a read timeout, PHP's socket and TLS streams return -1 without setting EOF (php_sockop_read in main/streams/xp_socket.c, php_openssl_sockop_io in ext/openssl/xp_ssl.c), so the bulk read loop stops with the payload half read.
Steps to reproduce, backtrace or example script
A single-node Valkey cluster with Toxiproxy in front of it. A slicer toxic sends the first 20000 bytes of each reply and then waits 2.5 s, which is longer than read_timeout.
docker compose up -d --wait valkey toxiproxy
docker compose run --rm php cluster # RedisCluster
docker compose run --rm php redis # Redis
PHPREDIS_REF=develop docker compose build php
docker compose run --rm php redis text 700 # Redis on develop, CRLF text valuecompose.yaml
services:
valkey:
image: valkey/valkey:9.0
command:
- sh
- -c
- >-
valkey-server --cluster-enabled yes --cluster-config-file /tmp/nodes.conf --save '' --appendonly no
--cluster-announce-hostname toxiproxy --cluster-preferred-endpoint-type hostname --cluster-announce-port 26379 &
until valkey-cli ping >/dev/null 2>&1; do sleep 0.2; done;
valkey-cli cluster addslotsrange 0 16383 >/dev/null;
wait
healthcheck:
test: ["CMD-SHELL", "valkey-cli cluster info | grep -q cluster_state:ok"]
interval: 1s
retries: 30
toxiproxy:
image: ghcr.io/shopify/toxiproxy:2.12.0
command: ["-host=0.0.0.0", "-config=/toxiproxy.json"]
volumes:
- ./toxiproxy.json:/toxiproxy.json:ro
php:
build:
context: .
args:
PHPREDIS_REF: ${PHPREDIS_REF:-6.3.0}
volumes:
- ./repro.php:/repro.php:ro
depends_on:
valkey:
condition: service_healthy
toxiproxy:
condition: service_started
entrypoint: ["php", "/repro.php"]toxiproxy.json
[
{
"name": "valkey",
"listen": "0.0.0.0:26379",
"upstream": "valkey:6379",
"enabled": true
}
]Dockerfile
FROM php:8.5-cli
ARG PHPREDIS_REF=6.3.0
RUN apt-get update \
&& apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/* \
&& git clone --depth 1 --branch "$PHPREDIS_REF" https://github.com/phpredis/phpredis.git /usr/src/phpredis \
&& cd /usr/src/phpredis \
&& phpize \
&& ./configure \
&& make -j"$(nproc)" \
&& make install \
&& docker-php-ext-enable redisrepro.php
<?php
function toxic(string $method, string $path, array $body = []): void
{
file_get_contents('http://toxiproxy:8474/proxies/valkey/toxics' . $path, false, stream_context_create(['http' => [
'method' => $method,
'header' => "Content-Type: application/json\r\n",
'content' => json_encode($body),
]]));
}
if (($argv[1] ?? 'redis') === 'cluster') {
$client = new RedisCluster(null, ['toxiproxy:26379'], 2, 2);
} else {
$client = new Redis();
$client->connect('toxiproxy', 26379, 2, null, 0, 2);
}
$big = ($argv[2] ?? 'binary') === 'text' ? str_repeat("Lorem ipsum dolor sit amet\r\n", 1100) : str_repeat('x', 30000);
$client->set('big', $big);
for ($i = 0; $i < 30; $i++) {
$client->set("key$i", "value$i");
}
// Deliver the first 20000 bytes of each server reply, then pause 2.5 s (longer than read_timeout).
toxic('POST', '', ['name' => 'stall', 'type' => 'slicer', 'stream' => 'downstream',
'attributes' => ['average_size' => 20000, 'size_variation' => 0, 'delay' => 2500000]]);
try {
$client->get('big');
} catch (Exception $e) {
echo 'GET big => ', get_class($e), ': ', $e->getMessage(), "\n";
}
toxic('DELETE', '/stall');
sleep(1);
for ($i = 0; $i < (int) ($argv[3] ?? 30); $i++) {
try {
printf("GET key%d => %s\n", $i, var_export($client->get("key$i"), true));
} catch (Exception $e) {
printf("GET key%d => %s: %s\n", $i, get_class($e), $e->getMessage());
}
}Root cause
phpredis leaves the socket open in several places where it stops reading a reply before its end (6.3.0, and the same on develop unless stated):
redis_sock_read_bulk_reply()throwssocket error on read socketafter a short read and does not close the socket.cluster_send_slot()(node-directedRedisClustercommands) andcluster_send_direct()(ASKING, READONLY, MULTI) do not close the socket when they fail to read the reply.- On 6.3.0,
RedisClusterreads leftover bytes as replies with no error, and response handlers that get a bulk reply they did not expect leave its payload unread. The offset therefore grows: in a GET / SET NX / SET / DEL workload it grew from about 1,500 to about 2,750 commands over 1,500 iterations, andSET NXreported locks as acquired while another client held them. Redisthrowsprotocol error, got '%c' as reply type byteand does not close the socket.
Suggested fix
Close the socket wherever phpredis stops reading a reply before its end, as redis_sock_gets() already does when a header read fails. We have a fix that does this. With it, the script above and the node-directed case recover after the first exception, and the next command gets its own reply. We will open a PR against develop.
Related issues
- #2940: a timeout inside a header line is accepted as a complete line. Fixed on
develop. This issue is the same class of bug for the bulk payload, node-directed commands, and leftover-byte handling. - #1818, #1080, #2324: wrong values for other keys and
Invalid reply type returned for DEL command, closed or open without a root cause. This may be one of the causes.
I've checked
- There is no similar issue from other users (related ones above, none with this root cause)
- Issue isn't fixed in
developbranch
Activity
cyppe commentedon Nov 14, 2026
We hit the same thing with
Redisand persistent connections, and have run a local patch for it in production since October. In case it helps #2961, here is a smaller reproducer that needs no Redis or Toxiproxy: a fake server whose first reply arrives after the client's read timeout.On 6.3.0 and on
developat 99ddfbe (PHP 8.5 CLI, Linux), the leftover body is returned as the next command's reply:With #2961 (79bb0ad) applied on
developat 99ddfbe, it prints"b","c"and"d", as expected.Two related paths in
redis_sock_read_bulk_reply()that #2961 doesn't touch yet, which our patch also closes the socket on:redis_sock_disconnect(), with the rest of that reply still on the wire;\r\n, so a length that doesn't match the body is accepted and the remaining bytes become the next reply.Happy to send those as a follow-up PR on top of #2961, with this reproducer as a test, if that's useful.
SnowySailor commentedon Nov 14, 2026
@cyppe Thanks for this, I've updated my PR with your changes as well as some additional things that I came across. Mentioned you in the commit message as well.
Close the socket when a reply is only partly read
Close the socket when a reply is only partly read