redis/redis-py · error · ConnectionError

Connection closed by server.

Error message

Connection closed by server.

What it means

Raised by the sync RESP3 pure-Python parser when SocketBuffer.readline() returns empty — the server closed the connection before a complete reply. It is the RESP3 equivalent of the RESP2 server-close guard.

Source

Thrown at redis/_parsers/resp3.py:67

        else:
            if self._buffer is not None:
                try:
                    self._buffer.purge()
                except AttributeError:
                    # Buffer may have been set to None by another thread after
                    # the check above; result is still valid so we don't raise
                    pass
            return result

    def _read_response(
        self,
        disable_decoding=False,
        push_request=False,
        timeout: Union[float, object] = SENTINEL,
    ):
        raw = self._buffer.readline(timeout=timeout)
        if not raw:
            raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)

        byte, response = raw[:1], raw[1:]

        # server returned an error
        if byte in (b"-", b"!"):
            if byte == b"!":
                response = self._buffer.read(int(response), timeout=timeout)
            response = response.decode("utf-8", errors="replace")
            error = self.parse_error(response)
            # if the error is a ConnectionError, raise immediately so the user
            # is notified
            if isinstance(error, ConnectionError):
                raise error
            # otherwise, we're dealing with a ResponseError that might belong
            # inside a pipeline response. the connection's read_response()
            # and/or the pipeline's execute() will raise this error if
            # necessary, so just return the exception instance here.
            return error

View on GitHub (pinned to 43bf5ac31a)

Solutions

  1. Enable health_check_interval and retry_on_error=[ConnectionError, TimeoutError].
  2. Set socket_keepalive=True.
  3. Tune Redis `timeout`.
  4. Catch ConnectionError and reconnect.

Example fix

# before
r = redis.Redis(host='redis', protocol=3)
r.get('k')
# after
r = redis.Redis(host='redis', protocol=3, health_check_interval=30,
                socket_keepalive=True,
                retry_on_error=[redis.ConnectionError, redis.TimeoutError])
Defensive patterns

Strategy: retry

Validate before calling

try:
    assert r.ping()
except redis.ConnectionError:
    r.close(); r = redis.Redis(...)
r.get('k')

Type guard

def is_closed_error(exc: Exception) -> bool:
    from redis.exceptions import ConnectionError
    return isinstance(exc, ConnectionError) and 'closed by server' in str(exc)

Try / catch

from redis.exceptions import ConnectionError
try:
    return r.get('k')
except ConnectionError:
    r = redis.Redis(...)
    return r.get('k')

Prevention

When it happens

Trigger: Any sync command via the pure-Python RESP3 parser when the server half-closes the socket: restart, `timeout`, CLIENT KILL, failover, proxy idle drop.

Common situations: Managed Redis/proxies reaping idle flows, rolling deploys, failover, maxmemory-clients eviction.

Understand the failure class

Related errors


AI-assisted analysis of redis/redis-py@43bf5ac31a (2026-08-06). Data as JSON: /api/errors/e52ab68fadd77563. Report an issue: GitHub.