Skip to content

Socket stays open after a read timeout in the middle of a reply, so every later command reads an earlier command's reply #2960

Closed

Description

@SnowySailor

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 value
compose.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 redis
repro.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):

  1. redis_sock_read_bulk_reply() throws socket error on read socket after a short read and does not close the socket.
  2. cluster_send_slot() (node-directed RedisCluster commands) and cluster_send_direct() (ASKING, READONLY, MULTI) do not close the socket when they fail to read the reply.
  3. On 6.3.0, RedisCluster reads 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, and SET NX reported locks as acquired while another client held them.
  4. Redis throws protocol error, got '%c' as reply type byte and 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 develop branch

Activity

  1. cyppe commented on Nov 14, 2026

    @cyppe

    We hit the same thing with Redis and 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.

    <?php // server.php
    $srv = stream_socket_server('tcp://127.0.0.1:6390');
    $clients = []; $first = true;
    while (true) {
        $read = array_merge([$srv], $clients); $w = $e = null;
        if (stream_select($read, $w, $e, 5) === false) { break; }
        foreach ($read as $s) {
            if ($s === $srv) { $clients[] = stream_socket_accept($srv); continue; }
            $buf = fread($s, 4096);
            if ($buf === '' || $buf === false) { $clients = array_filter($clients, fn ($c) => $c !== $s); fclose($s); continue; }
            $lines = explode("\r\n", rtrim($buf)); $key = end($lines);
            if ($first) {
                $first = false;
                fwrite($s, "\$12\r\n");                // header now, body after the client's read timeout
                usleep(800_000);
                fwrite($s, "\$6\r\nINJECT\r\n\r\n");   // a 12-byte body that is itself a valid reply
                continue;
            }
            fwrite($s, '$' . strlen($key) . "\r\n" . $key . "\r\n"); // GET k returns "k"
        }
    }
    <?php // client.php
    $r = new Redis();
    $r->connect('127.0.0.1', 6390, 1.0, null, 0, 0.3); // read_timeout 0.3 s
    try { var_dump($r->get('a')); } catch (RedisException $e) { echo 'get(a) threw: ', $e->getMessage(), PHP_EOL; }
    usleep(1_000_000);
    foreach (['b', 'c', 'd'] as $k) { echo "get($k) => "; var_dump($r->get($k)); }

    On 6.3.0 and on develop at 99ddfbe (PHP 8.5 CLI, Linux), the leftover body is returned as the next command's reply:

    get(a) threw: socket error on read socket
    get(b) => string(6) "INJECT"
    get(c) => bool(false)
    get(d) => string(1) "b"
    

    With #2961 (79bb0ad) applied on develop at 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:

    • the "invalid bulk length" exception returns without redis_sock_disconnect(), with the rest of that reply still on the wire;
    • the body isn't checked for its trailing \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.

  2. SnowySailor commented on Nov 14, 2026

    @SnowySailor
    ContributorAuthor

    @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.

  3. added a commit that references this issue on Nov 15, 2026
    40132ea
  4. added a commit that references this issue on Nov 15, 2026
    7ad2f79
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions