python network_error ai_generated true

aiohttp.client_exceptions.ClientConnectionError: Cannot connect to host example.com:443 ssl:default [Connection refused]

ID: python/aiohttp-client-connection-pool-exhausted

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-04-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active
3.11 active

Root Cause

The connection pool limit is reached or the server refuses connections due to too many simultaneous requests, often because ClientSession's connector limit is too low or connections are not released.

generic

中文

连接池达到限制或服务器因并发请求过多而拒绝连接,通常是因为 ClientSession 的连接器限制过低或连接未释放。

Workarounds

  1. 85% success
    connector = aiohttp.TCPConnector(limit=100, limit_per_host=20)
    async with aiohttp.ClientSession(connector=connector) as session:
        # use session for multiple requests
  2. 90% success
    for attempt in range(3):
        try:
            async with session.get(url) as resp:
                return await resp.text()
        except aiohttp.ClientConnectionError:
            if attempt == 2:
                raise
            await asyncio.sleep(2 ** attempt)

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Higher limit can lead to resource exhaustion and doesn't address server-side refusal.

  2. 70% fail

    Creates many sessions, each with its own pool, causing overhead and still hitting OS limits.