aio-libs/aiohttp · error · UnixClientConnectorError

Cannot connect to unix socket

Error message

Cannot connect to unix socket {path} ssl:{ssl} [{strerror}]

What it means

Raised as UnixClientConnectorError when UnixConnector._create_connection fails to connect to a Unix domain socket. The original OSError (except asyncio.TimeoutError) is wrapped with the socket path, connection key, and underlying OS error string. This is the Unix-socket analogue of ClientConnectorError.

Solutions

  1. Verify the socket file exists: ls -la /path/to/socket.sock
  2. Confirm the server process is listening on the socket: ss -lx | grep socket_name
  3. Check file permissions on the socket — the aiohttp process needs read/write access
  4. Catch aiohttp.UnixClientConnectorError (or its parent ClientConnectorError) and retry with backoff for transient failures

Example fix

# before
connector = UnixConnector(path='/tmp/myapp.sock')
session = ClientSession(connector=connector)
await session.get('http://localhost/info')

# after
import os, aiohttp
if not os.path.exists('/tmp/myapp.sock'):
    raise FileNotFoundError('Socket not found at /tmp/myapp.sock')
try:
    resp = await session.get('http://localhost/info')
except aiohttp.UnixClientConnectorError as e:
    log.error('Socket connect failed: %s', e)
Defensive patterns

Strategy: try-catch

Validate before calling

import os, socket
path = '/tmp/myapp.sock'
if not os.path.exists(path):
    raise FileNotFoundError(f'Socket {path} does not exist')
try:
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.connect(path)
    s.close()
except OSError:
    raise ConnectionError(f'Cannot reach socket {path}')

Try / catch

try:
    resp = await session.get(url)
except aiohttp.UnixClientConnectorError as e:
    log.warning('Unix socket unavailable: %s (errno %s)', e.os_error.strerror, e.os_error.errno)
    # retry or fall back to TCP

Prevention

When it happens

Trigger: Using UnixConnector(path=...) or an http+unix:// URL when the socket file does not exist, the server process is not listening, or the process lacks permission to access the socket file. Also raised when the connection is refused.

Common situations: Connecting to a Docker daemon socket (/var/run/docker.sock) that is not running; targeting a PostgreSQL or Redis Unix socket with the wrong path; running on a system where the socket lives in a different directory; file permission mismatch between the server process and the aiohttp client process.

Understand the failure class

Related errors


AI-assisted analysis of aio-libs/aiohttp@d041d4d0fd (2026-08-11). Data as JSON: /api/errors/d60b8fd9b206e468. Report an issue: GitHub.

Appendix: source

Thrown at aiohttp/connector.py:1716

    @property
    def path(self) -> str:
        """Path to unix socket."""
        return self._path

    async def _create_connection(
        self, req: ClientRequest, traces: list["Trace"], timeout: "ClientTimeout"
    ) -> ResponseHandler:
        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                _, proto = await self._loop.create_unix_connection(
                    self._factory, self._path
                )
        except OSError as exc:
            if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
                raise
            raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc

        return proto


class NamedPipeConnector(BaseConnector):
    """Named pipe connector.

    Only supported by the proactor event loop.
    See also: https://docs.python.org/3/library/asyncio-eventloop.html

    path - Windows named pipe path.
    keepalive_timeout - (optional) Keep-alive timeout.
    force_close - Set to True to force close and do reconnect
        after each request (and between redirects).
    limit - The total number of simultaneous connections.
    limit_per_host - Number of simultaneous connections to one host.
    loop - Optional event loop.
    """

View on GitHub (pinned to d041d4d0fd)