Overview
In Python async workloads against OpenAI, configuring HTTP/2 connection pooling in httpx (AsyncClient / httpx.Limits) lets multiple concurrent requests multiplex over established TCP/TLS connections rather than opening a fresh socket and performing TLS handshakes per call. Notice also that newer versions of the openai Python SDK use httpx2 internally by default, so you should pass the matching httpx2 or httpx client consistently (DefaultAsyncHttpx2Client / httpx2.AsyncClient when using httpx2, or httpx.AsyncClient when using httpx directly).
- HTTP/2 multiplexing + pool limits (
httpx.Limits): Enablinghttp2=True(which requires theh2package,pip install httpx[http2]) allows concurrent streams over shared HTTP/2 connections, whileLimits(max_connections=..., max_keepalive_connections=..., keepalive_expiry=...)controls total open connections, idle keep-alive pool size, and idle socket lifetime. - Why default limits bottleneck high concurrency:
httpx.Limitsdefaults tomax_connections=100,max_keepalive_connections=20, andkeepalive_expiry=5.0seconds. Under high concurrency or bursty traffic, too few total/keep-alive connections cause pool queueing (PoolTimeout) or repeated connection churn, whereas over-allocating connections without concurrency bounds can exhaust ephemeral ports or file descriptors. - Client reuse and bounded concurrency: Instantiate a single shared async HTTP client and
AsyncOpenAI(http_client=...)per event loop/application lifecycle—never per request—and pair it with anasyncio.Semaphoreso bursts respect upstream rate limits and memory budgets.
Steps
- Install HTTP/2 support (
h2) and import matching client types: Installhttpx[http2]and usehttpx2.AsyncClient/DefaultAsyncHttpx2Clientwith modernopenaiSDK versions (orhttpx.AsyncClientif usinghttpxdirectly). - Tune
LimitsandTimeoutfor your concurrency and latency profile: Setmax_connectionsandmax_keepalive_connectionshigh enough for your target concurrency, setkeepalive_expiryshorter than upstream/proxy idle timeouts (e.g.,20.0–30.0s), and configure explicitconnect,read,write, andpooltimeouts. - Inject the shared client into
AsyncOpenAI: Pass your configuredAsyncClientintoAsyncOpenAI(http_client=...)and manage its lifecycle cleanly (await client.aclose()/await openai_client.close()) on shutdown. - Gate dispatch with
asyncio.Semaphoreand retry safely: Wrap worker tasks in anasyncio.Semaphoreto smooth bursts and apply jittered backoff on429/5xxresponses.
Example
import asyncio
import httpx2
from openai import AsyncOpenAI, DefaultAsyncHttpx2Client
def create_high_concurrency_openai_client(
*,
max_connections: int = 512,
max_keepalive_connections: int = 256,
keepalive_expiry: float = 30.0,
request_timeout_sec: float = 120.0,
) -> tuple[AsyncOpenAI, httpx2.AsyncClient]:
"""Creates a shared HTTP/2-enabled async client and AsyncOpenAI instance."""
limits = httpx2.Limits(
max_connections=max_connections,
max_keepalive_connections=max_keepalive_connections,
keepalive_expiry=keepalive_expiry,
)
timeout = httpx2.Timeout(
timeout=request_timeout_sec,
connect=10.0,
read=request_timeout_sec,
write=30.0,
pool=10.0,
)
# Requires `h2` installed for HTTP/2 negotiation
http_client = DefaultAsyncHttpx2Client(
http2=True,
limits=limits,
timeout=timeout,
)
openai_client = AsyncOpenAI(http_client=http_client)
return openai_client, http_client
async def run_batch_prompts(
prompts: list[str],
*,
model: str = "gpt-4o-mini",
concurrency: int = 100,
) -> list[str]:
"""Executes prompts concurrently over the shared HTTP/2 pool with a semaphore."""
openai_client, http_client = create_high_concurrency_openai_client(
max_connections=max(256, concurrency * 2),
max_keepalive_connections=max(128, concurrency),
)
semaphore = asyncio.Semaphore(concurrency)
async def _worker(prompt: str) -> str:
async with semaphore:
resp = await openai_client.responses.create(
model=model,
input=prompt,
)
return resp.output_text
try:
return await asyncio.gather(*(_worker(p) for p in prompts))
finally:
await openai_client.close()
await http_client.aclose()
Tips
- Keep
keepalive_expirybelow load-balancer / NAT idle timeouts: If an intermediate proxy or NAT drops idle sockets after 60s and your client keeps them for 120s, requests on stale sockets can hit reset/protocol errors—keepkeepalive_expirymodestly lower (such as20s–30s). - Watch out for HTTP/2
GOAWAY/ stream limits under heavy load: Servers and proxies can close or limit streams on long-lived HTTP/2 connections—test under realistic concurrency and verifyh2is installed sohttp2=Truedoes not fall back unexpectedly. - Monitor file descriptors and NAT ephemeral ports: High connection counts (
max_connections) consume sockets/ports on the host or NAT gateway—raise OS open-file limits (ulimit -n) if needed and pair pool sizing with rate-limit/concurrency controls rather than unboundedasyncio.gather.
You must log in or register to comment.
