Claude API Connection Pooling Best Practices
Why connection pooling matters for the Claude API
Every call to the Claude API is an HTTPS request over TLS. If your application opens a fresh TCP connection and performs a new TLS handshake for every request, you pay that overhead — typically 50–200ms depending on network conditions — on top of the model's own response time. Under load, this gets worse: you can exhaust ephemeral ports, hit file descriptor limits, or get throttled by intermediate proxies that don't expect thousands of short-lived connections per second.
Connection pooling solves this by reusing established TCP/TLS connections across multiple requests. Instead of handshake-connect-request-close for every call, your HTTP client keeps a pool of warm connections open to api.anthropic.com (or your API gateway) and dispatches requests through them. The result: lower p99 latency, fewer dropped requests under burst traffic, and less CPU spent on TLS negotiation. This article covers the concrete settings and patterns that matter in practice.
HTTP keep-alive is the foundation
Connection pooling only works if keep-alive is enabled. Most modern HTTP clients enable it by default, but it's worth verifying explicitly rather than assuming.
Node.js (undici / native fetch):
import { Agent, setGlobalDispatcher } from "undici";
const agent = new Agent({
keepAliveTimeout: 30_000,
keepAliveMaxTimeout: 60_000,
connections: 50, // max concurrent connections per origin
});
setGlobalDispatcher(agent);
Node.js (axios on top of http/https agents):
import https from "https";
import axios from "axios";
const client = axios.create({
httpsAgent: new https.Agent({
keepAlive: true,
maxSockets: 50,
maxFreeSockets: 10,
timeout: 60_000,
}),
});
Python (requests / httpx):
import httpx
client = httpx.Client(
limits=httpx.Limits(max_connections=50, max_keepalive_connections=20),
timeout=httpx.Timeout(60.0, connect=5.0),
)
The key is: don't create a new client/agent per request. Instantiate it once at application startup and reuse it for the lifetime of the process. This is the single most common mistake — serverless functions and request handlers that build a fresh HTTP client on every invocation lose all pooling benefits.
Sizing your pool correctly
There's no universal "right" number of connections — it depends on your concurrency profile. A few rules of thumb:
- Set max connections to your realistic peak concurrency, not an arbitrary round number. If your app rarely issues more than 20 simultaneous Claude requests, a pool of 50 is wasted overhead; a pool of 10 will cause queuing.
- Separate pools for streaming vs non-streaming calls. Streaming connections stay open for the duration of generation, which can be 10–60+ seconds. If streaming and short requests share a pool with a low connection cap, long-lived streams can starve short requests of available sockets.
- Watch your keep-alive timeout vs server-side idle timeout. If your client holds a connection open longer than the server allows, you'll intermittently get connection reset errors on reuse. A keep-alive timeout of 30–60 seconds with proper retry-on-stale-connection logic avoids this.
- Don't pool across untrusted tenants. If you're building a multi-tenant product, isolate connection pools (or at least rate-limit) per tenant so one customer's burst traffic can't exhaust sockets for everyone else.
Retry logic and pool health
Pooled connections can go stale — the remote end may close them after an idle period even if your client thinks they're still valid. This surfaces as ECONNRESET or socket hang up errors on otherwise healthy systems. The fix is not bigger pools, it's correct retry behavior:
async function callClaude(payload, attempt = 0) {
try {
return await client.post("/v1/messages", payload);
} catch (err) {
const isStaleConnection = err.code === "ECONNRESET" || err.code === "EPIPE";
if (isStaleConnection && attempt < 2) {
return callClaude(payload, attempt + 1);
}
throw err;
}
}
Only retry idempotent-safe failures (connection-level errors), never blindly retry on 4xx responses, and always cap retry attempts with a short backoff to avoid amplifying load during an outage.
Concurrency limits beyond the pool
Connection pooling controls how many TCP connections you keep warm, but you also need an application-level concurrency limiter to avoid overwhelming the Claude API's own rate limits. A semaphore or queue in front of your request dispatcher keeps you within both your connection pool size and your account's requests-per-minute ceiling:
import pLimit from "p-limit";
const limit = pLimit(15); // match your account's safe concurrency
const results = await Promise.all(
prompts.map((p) => limit(() => callClaude(p)))
);
This matters more in batch-processing workloads — document pipelines, bulk summarization jobs, agent fan-out — where it's easy to accidentally fire hundreds of requests at once and get rate-limited or exhaust your pool simultaneously.
Where a managed gateway simplifies this
If you're calling Claude through a thin proxy layer — for team usage tracking, per-project API keys, or just a cleaner HTTPS interface — connection pooling behavior is largely the same, since you're pooling connections to the gateway rather than directly to Anthropic. SubToAPI sits in that role: it exposes a standard REST endpoint at api.subtoapi.app with its own sub_live_... application keys, so your existing pooling and retry code works unchanged — you just point your HTTP client's base URL at SubToAPI instead of managing raw Claude credentials and connection behavior yourself across every service.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"claude-opus-4","messages":[{"role":"user","content":"Hi"}]}'
Check the quickstart and messages docs for request shapes, streaming for long-lived connection handling, and tools if your agent workloads use tool calls — all of which interact with the same pooling considerations above. Plans start with a free trial at /signup; see /pricing for Solo, Team, and Scale tiers.
questions
Does connection pooling reduce Claude API token costs? No. Pooling only affects transport-layer overhead (TCP/TLS handshakes and latency). Token usage and billing are determined by input/output tokens, not connection behavior.
How many connections should I keep in my pool? Size it to your realistic peak concurrency, not a fixed default. Start around 10–20 for typical web apps, separate streaming and non-streaming pools, and monitor queuing/wait times to tune further.
Why am I getting ECONNRESET errors with a pooled client? This usually means a pooled connection went stale and was closed server-side before your client reused it. Implement retry logic for connection-level errors and set a keep-alive timeout shorter than the server's idle timeout.