Skip to content
Latchkey

Python "aiohttp.ClientConnectorError" in CI

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host ... is raised when the aiohttp client fails to establish a TCP connection, the async equivalent of a connection-refused error.

What this error means

An async test fails with "aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api:8000 ssl:default [Connection refused]".

python
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api:8000 ssl:default [Connect call failed]

Common causes

The target host is not listening yet

A dependent service in the CI network had not finished starting when the request fired.

Incorrect host/port for the CI topology

localhost was used where the service is reachable under a container name.

How to fix it

Await readiness and bound retries

  1. Poll the endpoint until it responds before running dependent async tests.
  2. Use the correct service hostname for the CI network.
  3. Wrap idempotent calls in an async retry with backoff.
Python
import aiohttp, asyncio

async def get(url):
    async with aiohttp.ClientSession() as s:
        for attempt in range(5):
            try:
                async with s.get(url) as r:
                    return await r.json()
            except aiohttp.ClientConnectorError:
                await asyncio.sleep(0.5 * (attempt + 1))
        raise

How to prevent it

  • On Latchkey managed runners, transient connect failures during service startup are auto-retried.
  • Use service hostnames, not localhost, in container networks.
  • Gate async integration tests on readiness.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →