Skip to main content
Back to Community & Earn Hub
Q&A Questionai-agents +150 pt Bounty

FastAPI + OpenAI/Anthropic Async Client Connection Pool Exhaustion: How to fix 'PoolTimeout' under 200+ concurrent agent sub-calls?

@devansh_agrawal4 days ago 1515 views

Our FastAPI orchestrator uses AsyncOpenAI and AsyncAnthropic with asyncio.gather() to run 4–6 parallel sub-agent calls per user turn.

The Crash Under Load

At low traffic everything works. Once ~50 concurrent users trigger parallel agent fan-outs (~250 simultaneous outbound HTTPS calls), requests start failing with:

text
httpcore.PoolTimeout: All connections in the connection pool are busy

(Or httpx.PoolTimeout after waiting 5 seconds for a free socket!)

  1. Why does creating AsyncOpenAI() inside each request handler cause ephemeral port / TLS handshake exhaustion instead?
  2. What httpx.Limits and HTTP/2 multiplexing settings should we configure on a singleton client in FastAPI lifespan?
1 Answers

Community Answers

@aarav_sharma Accepted Answer4 days ago

Both extremes fail in production:

  • Creating AsyncOpenAI() per request leaks unclosed TCP sockets, wastes ~150ms on fresh TLS handshakes every call, and triggers OS TIME_WAIT ephemeral port exhaustion.
  • Using the default singleton AsyncOpenAI() inherits httpx's default Limits(max_connections=100, max_keepalive_connections=20), which immediately throws PoolTimeout as soon as fan-out exceeds 100 concurrent sockets!

Here is the production fix using a lifespan-managed httpx.AsyncClient with HTTP/2 multiplexing and raised pool limits:


1. Configure Singleton httpx.AsyncClient in FastAPI lifespan

Raising max_connections=500, enabling http2=True (allows multiplexing dozens of concurrent streams over fewer TCP connections!), and sharing that single client across AsyncOpenAI / AsyncAnthropic eliminates PoolTimeout:

python
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI
from openai import AsyncOpenAI
from anthropic import AsyncAnthropic

@asynccontextmanager
async def lifespan(app: FastAPI):
    shared_http = httpx.AsyncClient(
        http2=True,
        limits=httpx.Limits(
            max_connections=500,
            max_keepalive_connections=100,
            keepalive_expiry=30.0,
        ),
        timeout=httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=10.0),
    )
    app.state.openai = AsyncOpenAI(http_client=shared_http)
    app.state.anthropic = AsyncAnthropic(http_client=shared_http)
    try:
        yield
    finally:
        await shared_http.aclose()

app = FastAPI(lifespan=lifespan)

2. Bound Per-Worker Fan-Out with asyncio.Semaphore

Even with 500 pooled connections, add an asyncio.Semaphore(200) around asyncio.gather() fan-outs so a sudden traffic spike queues cleanly in Python memory rather than hammering upstream rate limits or timing out sockets.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.