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): Enabling http2=True (which requires the h2 package, pip install httpx[http2]) allows concurrent streams over shared HTTP/2 connections, while Limits(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.Limits defaults to max_connections=100, max_keepalive_connections=20, and keepalive_expiry=5.0 seconds. 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 an asyncio.Semaphore so bursts respect upstream rate limits and memory budgets.

Steps

  1. Install HTTP/2 support (h2) and import matching client types: Install httpx[http2] and use httpx2.AsyncClient / DefaultAsyncHttpx2Client with modern openai SDK versions (or httpx.AsyncClient if using httpx directly).
  2. Tune Limits and Timeout for your concurrency and latency profile: Set max_connections and max_keepalive_connections high enough for your target concurrency, set keepalive_expiry shorter than upstream/proxy idle timeouts (e.g., 20.0–30.0s), and configure explicit connect, read, write, and pool timeouts.
  3. Inject the shared client into AsyncOpenAI: Pass your configured AsyncClient into AsyncOpenAI(http_client=...) and manage its lifecycle cleanly (await client.aclose() / await openai_client.close()) on shutdown.
  4. Gate dispatch with asyncio.Semaphore and retry safely: Wrap worker tasks in an asyncio.Semaphore to smooth bursts and apply jittered backoff on 429/5xx responses.

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_expiry below 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—keep keepalive_expiry modestly lower (such as 20s–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 verify h2 is installed so http2=True does 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 unbounded asyncio.gather.