How to Manage a Connection Pool When Using Multiple Proxy IPs
When your code uses several proxy IPs, connection handling matters. See how to keep one pool per endpoint, cap concurrency, retire bad endpoints and avoid leaks.
10 min readUpdated Nov 13, 2026By XPASS Editorial Team

A single proxy endpoint is simple: create one agent, reuse it, done. Things change when your code can reach several proxy IPs, for example when a plan includes a list of addresses, when different jobs must use different outbound addresses, or when you split traffic to stay inside the limits of each endpoint. Now the question is how your program keeps track of connections. Handled badly, it opens thousands of short-lived sockets, leaks memory, sends a request through the wrong address or hammers one endpoint while others sit idle. Handled well, it reuses warm connections, stays within sensible limits and degrades gracefully when an endpoint misbehaves. This guide explains the ideas and gives a plain pattern you can adapt. Use proxies only for lawful work, follow the terms of the sites and APIs you call, and keep your traffic bounded.
What a connection pool actually does
Opening a connection is expensive. Before the first byte of your request travels, the client must resolve a name, open a TCP connection, possibly authenticate to the proxy, send CONNECT for HTTPS targets and finish a TLS handshake. A connection pool keeps finished connections open for a while, so later requests skip this work. HTTP/1.1 connections stay open by default unless someone closes them, and RFC 9110 describes how connections and intermediaries behave in general terms.
In most languages the pool lives in an agent or client object. It tracks idle sockets, hands one to the next request, opens a new one when none is free, and closes sockets that stay idle too long. Typical settings are the maximum number of sockets, the maximum number of idle sockets, the idle timeout and whether keep-alive is on.
With a proxy there is one more rule that surprises people: a pooled connection belongs to a specific proxy endpoint and, for HTTPS tunnels, to a specific target host. A tunnel opened to one target through one proxy cannot be reused for a different target. A good pool is therefore keyed by the combination of proxy and target, or by proxy only for plain HTTP forwarding.

Why multiple IPs complicate pooling
When you only have one proxy, mistakes are visible straight away. With several, mistakes hide inside averages.
- Shared pools mix endpoints. If one agent is configured with one proxy URL, it only ever uses that proxy. Developers sometimes swap the URL on a shared agent, which leaves old sockets pointing to the previous endpoint.
- Agent churn. Creating a new agent per request, a common shortcut, means no connection is ever reused and idle sockets may linger until the operating system reclaims them.
- Uneven load. Without a plan, one endpoint ends up with most of the traffic. That can push it past its limits while others sit unused.
- Unclear failures. If you cannot tell which endpoint produced an error, you cannot tell whether the cause is the endpoint, the target or your own code.
The remedy is straightforward: keep one agent per proxy endpoint, give each its own limits and counters, and put a small scheduler in front.
A simple structure: registry, scheduler and limits
Think in three layers.
- Registry. A map from endpoint identifier to a record containing the agent, counters (active requests, recent failures, last success) and a state such as healthy, cooling-off or disabled.
- Scheduler. A function that, given a task, picks an endpoint. Common strategies are round robin for independent requests, least-active for uneven workloads, and sticky assignment where all requests belonging to one workflow, such as a login followed by several calls, keep using the same endpoint.
- Limits. A global cap on concurrent requests, a per-endpoint cap, and a queue for work that has to wait. A semaphore is the usual tool.
Here is a compact sketch in JavaScript:
const { HttpsProxyAgent } = require("https-proxy-agent");
const endpoints = new Map(); // id -> { agent, active, failures, state, until }
function addEndpoint(id, url) {
endpoints.set(id, {
agent: new HttpsProxyAgent(url, { keepAlive: true, maxSockets: 10, maxFreeSockets: 2 }),
active: 0,
failures: 0,
state: "healthy",
until: 0,
});
}
function pick() {
const now = Date.now();
const usable = [...endpoints.entries()].filter(([, e]) =>
e.state === "healthy" || (e.state === "cooling" && e.until <= now)
);
if (usable.length === 0) throw new Error("no usable proxy endpoint");
usable.sort((a, b) => a[1].active - b[1].active); // least active first
return usable[0];
}
Real code would add the semaphore, the request wrapper that increments and decrements active, and the health logic described below. Keep the proxy URLs, which contain credentials, in environment variables or a secrets store, never in source files.
Sizing the limits
There is no magic number, but a few rules of thumb help.
| Setting | What to consider |
|---|---|
| Global concurrency | Your CPU and memory, plus the target's published rate limits. Start low and raise slowly |
| Per-endpoint concurrency | The connection limits of your plan, which you should read on the plan page rather than assume |
| Max sockets per agent | Usually equal to the per-endpoint concurrency, so the pool does not open more than you intend |
| Max free sockets | A small number, enough to absorb bursts without holding resources |
| Idle timeout | Shorter than the shortest idle limit along the path, so you do not reuse a socket the other side already closed |
| Queue size | Bounded; reject or delay new work when the queue is full instead of growing without limit |
Measure instead of guessing. Track the number of active requests, queue length, and error rates per endpoint. If errors rise as you add concurrency, you have passed the sweet spot. A higher number is not a better number. The target site and your plan both define how much traffic is acceptable, and those limits are rules to respect, not obstacles.
Health checks and removing bad endpoints
Endpoints fail for ordinary reasons: a network issue, an overloaded target, expired credentials or maintenance on the provider's side. Give your registry a simple health model.
- Count consecutive failures per endpoint, separating errors that point at the proxy (connection refused, 407, failures while opening the tunnel) from errors that point at the target (a 404, a timeout from one specific site).
- When proxy-side failures cross a threshold, set the state to cooling-off for a period, such as a minute, and stop sending new work.
- After the period, let one low-risk probe request through. If it succeeds, return the endpoint to rotation, and if it fails, extend the cooling-off time.
- Surface the state in your logs and dashboards so that a human sees when half the pool is out.
- If an endpoint stays unhealthy, tell your provider rather than hoping it recovers.
How the retries inside each request interact with this is covered in handling retry and timeout with a proxy. A short summary: let each request retry a couple of times with backoff, and let the health model make the larger decision about whether an endpoint is still worth using. Do not use rotation as a way to evade a block or rate limit placed by a site; if a site refuses your traffic, change your behaviour or ask for permission.
A plain worked example
Suppose a reporting service calls a partner API for several customers, and each customer's data must be fetched from a specific outbound address that the partner has allowed.
- Load the endpoint list from configuration at start-up and create one agent per endpoint with keep-alive and a socket cap.
- Map each customer to an endpoint by a stable rule, such as a stored assignment. This is the sticky strategy, and it matters because the partner expects a given customer to come from a given address.
- Run each customer's fetches through a per-endpoint semaphore, so a large customer cannot starve the others on the same endpoint.
- Wrap every request so that it records endpoint id, duration, status and bytes transferred, ideally into the usage log described in logging proxy traffic usage in your backend.
- If an endpoint enters cooling-off, queue its customers' work instead of silently moving them to another address, because moving them would break the partner's allow-list.
- On shutdown, stop accepting new work, wait for in-flight requests up to a deadline, then destroy the agents so sockets close cleanly.
The details of configuring a single Axios client for each endpoint are in the guide to setting up an Axios proxy for API work.
Consider an illustrative setup with six proxy endpoints and a per-endpoint limit of four concurrent connections, so the pool can hold twenty-four active connections in total. A batch job asks for thirty parallel requests. The scheduler hands out twenty-four immediately and queues six. When one request finishes, the scheduler gives the next queued request to the endpoint with the most spare capacity. If one endpoint fails two health checks in a row, it is marked unavailable, its four slots disappear, and the pool temporarily shrinks to twenty. The numbers are invented, but they show why limits per endpoint and a global ceiling should both be explicit.
Limits and what to watch for
- Socket and file descriptor limits. Each connection uses a file descriptor. Many endpoints times many sockets can reach the operating system limit. Check it before raising caps.
- Memory leaks. Agents held in a map are fine; agents created per request and never destroyed are not. Make sure retired endpoints have their agents destroyed.
- Stale connections. Idle sockets can be dropped by firewalls or by the proxy. A failed first request on a reused socket is common after a quiet period; a single quick retry on a fresh socket usually solves it.
- Credentials in logs. Endpoint identifiers in logs should be labels, not URLs with passwords.
- Plan terms. Check what your plan says about the number of simultaneous connections and about how traffic is counted. Failed or retried requests may count.
- Target rules. Distributing requests across IPs does not remove the target's rules. Respect robots directives, terms of use and rate limits.
- Stickiness versus balance. Sticky assignment keeps behaviour consistent but can leave load uneven. Choose per workflow and document the choice.
Before you put a pool into production, run a short checklist: confirm that every endpoint has its own limit, that queued work has a maximum wait time, that failed endpoints are retested rather than discarded for good, and that logs record which endpoint served which request. A decision rule that helps with sizing: start low, raise the limit in small steps while watching error rates, and stop raising it as soon as errors or latency begin to climb.
Summary
Keep one pooled agent per proxy endpoint, created once and held in a registry with its own counters and state. Put a scheduler in front that matches your needs, whether round robin, least-active or sticky, and enforce global and per-endpoint concurrency with bounded queues. Size limits by measurement and by the rules of your plan and the target, make idle timeouts shorter than the path's shortest idle limit, and remove failing endpoints for a cooling-off period instead of hammering them. Log which endpoint handled each request, and shut everything down cleanly. When you want to see how proxy options are described, visit the XPASS proxy page.
Frequently asked questions
Why keep a separate connection pool for each proxy IP?
A pooled connection is tied to one proxy endpoint. Sharing a single pool across endpoints mixes sockets, hides which endpoint is failing and can send a request through a different IP than you intended.
Should I create a new agent for every request?
No. A new agent per request defeats connection reuse, wastes handshakes and can leak sockets. Create agents once, keep them in a map keyed by endpoint, and reuse them.
How many concurrent connections should I allow?
It depends on your plan, the target's rules and your own hardware. Set a global cap and a per-endpoint cap, start low, and raise them only while error rates stay healthy and within what your plan allows.
How do I handle a proxy IP that keeps failing?
Track failures per endpoint, take it out of rotation for a cooling-off period once it crosses a threshold, and bring it back with a small test request. Report persistent problems to your provider.
References
About the author

Bob Kanokphon Thongdee
- Founder of XPASS VPN
- Co-founder of eSIMonline.asia
- More than 7 years in online marketing
- Founder of Cojourney Visa and Cojourney Travel
Need a proxy for this?
XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.
See proxy plansKeep reading

Proxy Guides
How to Handle Retry and Timeout When Using a Proxy
Proxied requests have more places to fail. Learn how to set layered timeouts, choose which errors deserve a retry, add backoff and keep retries polite.
9 min read

Proxy Guides
How to Log Proxy Traffic Usage in Your Backend
Know where your proxy traffic goes. Learn which fields to log, how to count bytes, how to store and summarise usage, and how to keep the logs private.
9 min read

Proxy Guides
How to Set Up an Axios Proxy for API Work
A practical guide to routing Axios requests through a proxy in Node.js, from the built-in proxy option to agents, environment variables, timeouts and testing.
9 min read