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:
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.