TL;DR: Out of the box, Apache HttpClient 4.x allows only 2 connections per host, has no timeouts, and quietly ignores some settings depending on how you build it. 5.x is better but still surprising, and it retries on its own. Set the pool size and all three timeouts yourself, every time. There’s a checklist at the end.
I wanted to really understand what Apache HttpClient does when you don’t configure it, so I set up a small experiment.
Picture two tiny services: a catalog service that shows books, and an inventory service that knows how many copies are in stock. Every catalog page asks inventory “how many of these do we have?” over HTTP. Simple.
Now send 10 requests at once, nothing dramatic. Each inventory call takes about a second (slow on purpose, to make the effect visible), so you’d expect all 10 back in about a second.
They take five.
No errors, nothing in the logs, CPU basically idle. Everything is just… waiting. The reason is one innocent line:
CloseableHttpClient client = HttpClientBuilder.create().build();
To see exactly what HttpClient does by default, I wrote a small local test server that counts how many requests it’s handling at the same moment and can sleep for as long as I tell it. Then I fired bursts of requests at it from Apache HttpClient 4.5.14 and 5.4.4 on JDK 25. Every number below is real output from those runs.
First, a 30-second picture of how HttpClient works
Opening a TCP connection is slow-ish, so HttpClient keeps a connection pool, a small stash of open connections it reuses.
Think of it like a supermarket with checkout lanes:
- Each lane is a connection.
- Your requests are shoppers.
- If all lanes are busy, shoppers queue until one frees up.
Everything in this post comes down to: how many lanes there are, how long a shopper waits in the queue, and how long each shopper is allowed to spend at the till.
1. Only two lanes per host (in 4.x)
Here are HttpClient 4.x’s pool defaults:
PoolingHttpClientConnectionManager m = new PoolingHttpClientConnectionManager();
m.getDefaultMaxPerRoute(); // 2
m.getMaxTotal(); // 20
2 connections per route and 20 in total. A “route” is basically one host and port, like inventory:8080. HttpClientBuilder.create().build() uses these same limits.
So my 10 concurrent requests, each taking 1 second:
default builder, 10 x 1s peak concurrent = 2 time = 5.1s
Two at a time, five rounds, five seconds. That’s the whole puzzle. Nothing failed and nothing was logged. Requests just queued politely for one of two lanes.
HttpClient 5.x raised the defaults to 5 per route and 25 in total. Better, but still small for anything busy:
5.x default, 10 x 1s peak concurrent = 5 time = 2.1s
A “route” is the host, not the endpoint
You might assume different endpoints get their own lanes. They don’t:
10 requests split across /orders and /stock peak concurrent = 2 time = 5.0s
Same host, same 2 connections. This matters more than it looks. If you reach several “different services” through a single host, like a reverse proxy, an API gateway, or a sidecar on localhost, then to HttpClient that’s one route, and they all share those 2 lanes.
The fix: open more lanes
CloseableHttpClient client = HttpClientBuilder.create()
.setMaxConnPerRoute(25)
.setMaxConnTotal(100)
.build();
maxPerRoute 25 / total 100 peak concurrent = 10 time = 1.0s
All 10 in parallel, done in 1 second, as I originally expected.
How big should the pool be? Start from how many calls you expect to be in flight at the same time to that host (roughly: requests per second × seconds per call), add some headroom, and make sure the server on the other end can actually handle that many.
2. Settings that are silently ignored
This one surprised me the most. If you give the builder your own connection manager, the builder’s pool settings stop doing anything:
HttpClientBuilder.create()
.setConnectionManager(new PoolingHttpClientConnectionManager())
.setMaxConnPerRoute(25) // ignored!
.setMaxConnTotal(100) // ignored!
.build();
custom manager + setMaxConnPerRoute(25) peak concurrent = 2 time = 5.0s
No warning, no exception. The code clearly says 25, and the client behaves as if it said 2. The builder’s limits only apply to the connection manager the builder creates itself.
The fix: when you bring your own manager, set the limits on the manager:
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(25);
cm.setMaxTotal(100);
CloseableHttpClient client = HttpClientBuilder.create()
.setConnectionManager(cm)
.build();
3. Three timeouts, and none of them is set (in 4.x)
HttpClient has three different timeouts. They sound alike but guard against different problems:
| Timeout | Supermarket version | 4.x default | 5.x default |
|---|---|---|---|
| Connection request | How long you’ll wait in the queue for a free lane | none (-1) | 3 minutes |
| Connect | How long it takes to open a new lane | none (-1) | 3 minutes |
| Socket / response | How long you’ll stand at the till waiting for the cashier | none (-1) | none (null) |
In 4.x, RequestConfig.DEFAULT has all three at -1, which means “wait as long as it takes”. In 5.x, the response timeout is still null, so the same thing applies.
To see what that means, I made inventory take 8 seconds to answer:
4.x default, server takes 8s time = 8.0s HTTP 200
5.x default, server takes 8s time = 8.0s HTTP 200
Both clients waited patiently for the full 8 seconds. That sounds harmless, but imagine the other service doesn’t answer slowly, it doesn’t answer at all. Every thread that calls it hangs. Soon all your threads are stuck waiting on a service that’s never going to reply, and your service stops responding too, even for pages that have nothing to do with inventory.
The fix: set all three, on purpose
In 4.x (values in milliseconds):
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(2_000)
.setSocketTimeout(3_000)
.setConnectionRequestTimeout(500)
.build();
CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.setMaxConnPerRoute(25)
.setMaxConnTotal(100)
.build();
In 5.x the settings moved around a bit. Connection-level timeouts and pool limits live on the connection manager, and request-level ones on RequestConfig:
PoolingHttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnPerRoute(25)
.setMaxConnTotal(100)
.setDefaultConnectionConfig(ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(2))
.setSocketTimeout(Timeout.ofSeconds(3))
.build())
.build();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMilliseconds(500))
.setResponseTimeout(Timeout.ofSeconds(3))
.build())
.build();
With a 3-second socket timeout, the 8-second call now gives up on time:
socketTimeout 3s, server takes 8s time = 3.0s SocketTimeoutException
Failing after 3 seconds might feel worse than succeeding after 8. But a fast, clear failure is something you can handle: show “stock unavailable”, retry, use a cached value. A thread that hangs forever is something you can’t handle at all.
The queue timeout fails fast, so plan for it
The connection request timeout (the time spent waiting in the queue) deserves special attention, because it turns “slow” into “failed”. With the default 2 lanes and a 500 ms queue limit, I sent 10 one-second requests:
default + pool wait 500ms time = 1.0s {HTTP 200=2, ConnectionPoolTimeoutException=8}
Two shoppers got a lane. The other eight waited half a second, gave up, and went home.
That’s usually the right behaviour, since failing fast beats queuing forever, but it means a small pool plus a short queue timeout gives you errors under perfectly normal load. So:
- Size the pool first.
- Then set the queue timeout.
- Handle
ConnectionPoolTimeoutExceptionproperly. The nice thing about it is that the request was never sent, so it’s always safe to retry.
One timeout doesn’t fit every endpoint
A 3-second socket timeout is great for “get the stock for one book”. It’s terrible for “re-import the whole catalogue of 5,000 books”. If both calls share one RequestConfig, the big one times out. And here’s the scary part: you don’t know whether the server finished the job or not. Maybe it imported everything and the reply just arrived late.
Two good options. Override the timeout for that one request:
HttpPost bulk = new HttpPost(url);
bulk.setConfig(RequestConfig.copy(config).setSocketTimeout(60_000).build());
Or, often better, split big batches into chunks, say 200 books per call, so every call stays small, fast and predictable.
4. Forget to close a response and the pool runs dry
This is the classic way to leak connections. In 4.x, a connection goes back to the pool only when you close the response (or fully read its body). Forget, and that lane stays “busy” forever.
I made three requests with a 3-second queue timeout, without ever closing the responses:
leaky request 1: HTTP 200 after 1.0s stats=[leased: 1; pending: 0; available: 0; max: 20]
leaky request 2: HTTP 200 after 1.0s stats=[leased: 2; pending: 0; available: 0; max: 20]
leaky request 3: ConnectionPoolTimeoutException after 3.0s
Two leaked connections and the per-route limit of 2 was used up. The third request never even left the building. With no queue timeout, the default, it would have waited forever.
The fix: always use try-with-resources and consume the body:
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
String body = EntityUtils.toString(response.getEntity());
// ...
}
In 5.x, the simplest safe option is the execute overload that takes a response handler. It releases the connection for you:
String body = client.execute(new HttpGet(url), response -> EntityUtils.toString(response.getEntity()));
Peek inside the pool
When something feels slow, the pool can tell you what’s going on:
System.out.println(cm.getTotalStats());
Here it is in the middle of my 10-request burst with the default pool:
pool stats mid-burst: [leased: 2; pending: 8; available: 0; max: 20]
That’s the puzzle from the start of this post in one line: 2 connections in use, 8 requests waiting. If you have metrics set up, Micrometer has binders for Apache HttpClient’s connection pool, so you can graph leased and pending over time instead of guessing.
5. Retries behave differently between versions
I sent one GET to an endpoint that always answers 503 Service Unavailable and counted how many requests actually reached the server:
4.x default server hits = 1 HTTP 503
5.x default server hits = 2 HTTP 503 (~1s later)
5.x, disableAutomaticRetries() server hits = 1
HttpClient 5 retries on its own. By default it retries idempotent requests (like GET) once, after a short pause, on a 503 or 429 and on some network errors. 4.x doesn’t retry on status codes at all.
Neither choice is wrong, but you really want to know which one you’ve got:
- Stacked retries multiply. If your code retries 3 times and the client retries each attempt once more, that’s 6 requests, not 3.
- Upgrades change traffic. Moving from 4.x to 5.x means a struggling service suddenly gets more requests from you, exactly when it can least handle them.
- Retries need idempotency. Only retry things that are safe to do twice. Whether a
POSTgets retried should be your decision, not a default you didn’t know about.
6. useSystemProperties(): an on/off switch with side effects
By default, HttpClientBuilder ignores JVM system properties. To check, I set -Dhttp.proxyHost / -Dhttp.proxyPort to point at a local “proxy” server and counted how many requests went through it:
HttpClientBuilder.create() proxy hits = 0 (went direct)
HttpClientBuilder.create().useSystemProperties() proxy hits = 1
So if your setup relies on JVM proxy flags, a plain create() client quietly skips the proxy.
The surprise is that useSystemProperties() also changes the pool, because it reads http.maxConnections, which defaults to 5:
useSystemProperties() peak concurrent = 5 time = 2.0s
One innocent-looking method changed both the network path and the concurrency. If you use it, set your pool limits explicitly afterwards anyway.
The checklist
Every time I create an HttpClient now, I go through this:
- Pool size set explicitly, per route and total, based on real concurrency
- Remember: everything on the same host shares one route
- Bringing your own connection manager? Set the limits on the manager
- All three timeouts set: connect, socket/response, and pool wait
- Longer timeouts or chunking for bulk calls
- Responses always closed (try-with-resources or a response handler)
- Know whether the client retries, and don’t stack retries blindly
- Decide on purpose whether to call
useSystemProperties() - One shared client per downstream service, never a new client per request
- Pool stats or metrics visible somewhere, so “slow” has an explanation
Defaults are designed to “work in a demo”. Anything with real traffic needs numbers you chose on purpose.
A well-sized pool is only half the story, though. The other half is what your code is holding on to while it waits for those HTTP calls. That’s the topic of the next post: database locks and HTTP calls don’t mix.