redis/redis-py · error · TimeoutError

Timeout writing to socket

Error message

Timeout writing to socket

What it means

Raised as a TimeoutError in send_packed_command when socket.sendall raises socket.timeout while writing a command to the wire. The connection is disconnected first, then the error propagates. It means the socket's timeout elapsed before the full command could be transmitted.

Source

Thrown at redis/connection.py:1352

                self._ping_failed,
                with_failure_count=True,
            )

    def send_packed_command(self, command, check_health=True):
        """Send an already packed command to the Redis server"""
        if not self._sock:
            self.connect_check_health(check_health=False)
        # guard against health check recursion
        if check_health:
            self.check_health()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except OSError as e:
            self.disconnect()
            if len(e.args) == 1:
                errno, errmsg = "UNKNOWN", e.args[0]
            else:
                errno = e.args[0]
                errmsg = e.args[1]
            raise ConnectionError(f"Error {errno} while writing to socket. {errmsg}.")
        except BaseException:
            # BaseExceptions can be raised when a socket send operation is not
            # finished, e.g. due to a timeout.  Ideally, a caller could then re-try
            # to send un-sent data. However, the send_packed_command() API
            # does not support it so there is no point in keeping the connection open.
            self.disconnect()
            raise

    def send_command(self, *args, **kwargs):
        """Pack and send a command to the Redis server"""

View on GitHub (pinned to da03cdc7e8)

Solutions

  1. Increase socket_timeout (and socket_connect_timeout) to accommodate large writes.
  2. Batch large values into smaller chunks or use pipelines judiciously.
  3. Upgrade network bandwidth / move the client closer to the server.
  4. Configure retry_on_timeout=True or retry_on_error=[TimeoutError] so transient timeouts are retried.

Example fix

// before
r = redis.Redis(host=h, socket_timeout=0.5)
r.set('k', huge_blob)
// after
r = redis.Redis(host=h, socket_timeout=5.0)
r.set('k', huge_blob)
Defensive patterns

Strategy: retry

Try / catch

from redis.exceptions import TimeoutError
try:
    r.set('k', huge_blob)
except TimeoutError as e:
    if 'writing to socket' in str(e):
        # increase socket_timeout then retry idempotent writes
        pass

Prevention

When it happens

Trigger: Sending a very large command/value over a slow or saturated network link where sendall cannot complete within socket_timeout; a stalled server not draining its read buffer; a congested connection. Fires for every command path that writes to the socket.

Common situations: Bulk-loading large payloads (SET of a huge blob, big pipeline/LUA script) on a tight socket_timeout; network contention; server CPU saturated so TCP buffers back up; cross-region links with high latency.

Related errors


AI-assisted analysis of redis/redis-py@da03cdc7e8 (2026-08-04). Data as JSON: /data/errors/981aa1244a9ec45a.json. Report an issue: GitHub.