python/cpython · error · ConnectionError

Connection closed by peer

Error message

Connection closed by peer

What it means

Error "Connection closed by peer" thrown in python/cpython.

Source

Thrown at Lib/asyncio/base_events.py:227

class _SendfileFallbackProtocol(protocols.Protocol):
    def __init__(self, transp):
        if not isinstance(transp, transports._FlowControlMixin):
            raise TypeError("transport should be _FlowControlMixin instance")
        self._transport = transp
        self._proto = transp.get_protocol()
        self._should_resume_reading = transp.is_reading()
        self._should_resume_writing = transp._protocol_paused
        transp.pause_reading()
        transp.set_protocol(self)
        if self._should_resume_writing:
            self._write_ready_fut = self._transport._loop.create_future()
        else:
            self._write_ready_fut = None

    async def drain(self):
        if self._transport.is_closing():
            raise ConnectionError("Connection closed by peer")
        fut = self._write_ready_fut
        if fut is None:
            return
        await fut

    def connection_made(self, transport):
        raise RuntimeError("Invalid state: "
                           "connection should have been established already.")

    def connection_lost(self, exc):
        if self._write_ready_fut is not None:
            # Never happens if peer disconnects after sending the whole content
            # Thus disconnection is always an exception from user perspective
            if exc is None:
                self._write_ready_fut.set_exception(
                    ConnectionError("Connection is closed by peer"))
            else:
                self._write_ready_fut.set_exception(exc)

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Handle the disconnection gracefully: catch the exception around the await point and reconnect or clean up resources.
  2. Verify the remote peer is not closing the connection prematurely; check server-side logs and timeouts.
  3. Wrap reads/writes in try/except ConnectionResetError and treat it as end-of-stream.

When it happens

Trigger: Raised in asyncio.base_events when the connection is closed by the remote peer while reading or writing.

Common situations: See trigger scenarios.

Understand the failure class


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/19fb788e66e5dc54. Report an issue: GitHub.