{"record":{"id":"efcf397892e70792","repo":"redis/redis-py","slug":"timed-out-closing-connection-after-self-socket-co","errorCode":null,"errorMessage":"Timed out closing connection after {self.socket_connect_timeout}","messagePattern":"Timed out closing connection after (.+?)","errorType":"exception","errorClass":"TimeoutError","httpStatus":null,"severity":"warning","filePath":"redis/asyncio/connection.py","lineNumber":1106,"sourceCode":"            async with async_timeout(self.socket_connect_timeout):\n                self._parser.on_disconnect()\n                # Reset the reconnect flag\n                self.reset_should_reconnect()\n                if not self.is_connected:\n                    return\n                try:\n                    self._writer.close()  # type: ignore[union-attr]\n                    # wait for close to finish, except when handling errors and\n                    # forcefully disconnecting.\n                    if not nowait:\n                        await self._writer.wait_closed()  # type: ignore[union-attr]\n                except OSError:\n                    pass\n                finally:\n                    self._reader = None\n                    self._writer = None\n        except asyncio.TimeoutError:\n            raise TimeoutError(\n                f\"Timed out closing connection after {self.socket_connect_timeout}\"\n            ) from None\n\n        if error:\n            if health_check_failed:\n                close_reason = CloseReason.HEALTHCHECK_FAILED\n            else:\n                close_reason = CloseReason.ERROR\n\n            if failure_count is not None and failure_count > self.retry.get_retries():\n                await record_error_count(\n                    server_address=getattr(self, \"host\", None),\n                    server_port=getattr(self, \"port\", None),\n                    network_peer_address=getattr(self, \"host\", None),\n                    network_peer_port=getattr(self, \"port\", None),\n                    error_type=error,\n                    retry_attempts=failure_count,\n                )","sourceCodeStart":1088,"sourceCodeEnd":1124,"githubUrl":"https://github.com/redis/redis-py/blob/6a6b581b48225afa0b76912d1028c6035baee932/redis/asyncio/connection.py#L1088-L1124","documentation":"Raised as TimeoutError inside disconnect() when the async_timeout(self.socket_connect_timeout) context wrapping the writer close/wait_closed expires. It means the TCP teardown (writer.wait_closed()) did not finish within the configured connect timeout, which the code reuses as the close deadline. The connection is forcibly torn down and the timeout is re-raised.","triggerScenarios":"Calling await client.aclose() (or connection.disconnect()) when the remote is unresponsive or the network is lossy enough that the FIN handshake stalls longer than socket_connect_timeout. Common during app shutdown while the server is under heavy load or already gone.","commonSituations":"Graceful shutdown racing with a dead peer (no RST returned); lossy NAT/firewall dropping FIN packets; very small socket_connect_timeout (sub-second) on a high-latency link; disconnect triggered from a finally block during event-loop teardown.","solutions":["Increase socket_connect_timeout to a value larger than realistic teardown time (e.g. 5-10s).","Call disconnect(nowait=True) during forced shutdown to skip wait_closed() entirely.","Ensure the event loop is still running when aclose() is awaited (avoid closing during loop shutdown).","Diagnose the network path for packet loss/black-holing between client and server."],"exampleFix":"// before\nr = redis.asyncio.Redis(host=h, socket_connect_timeout=0.5)\n// after\nr = redis.asyncio.Redis(host=h, socket_connect_timeout=5.0)","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"def is_close_timeout(exc: BaseException) -> bool:\n    return isinstance(exc, TimeoutError) and 'closing connection' in str(exc).lower()","tryCatchPattern":"try:\n    await client.aclose()\nexcept TimeoutError:\n    # graceful close stalled; force\n    await client.connection_pool.disconnect(inuse_connections=True)","preventionTips":["Set socket_connect_timeout to a realistic teardown budget (>=5s).","Use disconnect(nowait=True) during forced shutdown.","Avoid aclose() after the event loop is already closing."],"tags":["network","timeout","disconnect","async","shutdown","socket-connect-timeout"],"backgroundTag":null,"analyzedSha":"6a6b581b48225afa0b76912d1028c6035baee932","analyzedAt":"2026-08-10T12:52:44.840Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}