Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

Under load, outgoing calls through Apache HttpClient 5 queue for seconds even though the downstream service responds in 20 ms. Thread dumps show threads waiting in the connection pool. What do you check and change?

If threads wait in the connection pool while the downstream answers in 20 ms, the pool is the bottleneck, not the downstream. The usual causes are a per-route limit (defaultMaxPerRoute) that is far below our concurrency to that host, since Apache HttpClient's defaults are small (check your version), and connections that never return to the pool because response bodies are not consumed or closed. We raise maxTotal and the per-route limit on PoolingHttpClientConnectionManager to match the expected concurrency, make sure every response is closed, set a connection-request timeout so waiting fails fast, and expose leased, pending and available counts through Micrometer.

Why this question is asked

This is a classic production puzzle: the dependency's dashboards show 20 ms responses and plenty of capacity, yet our calls to it take seconds. Teams often blame the network or the downstream team, and the real cause is a limit inside our own process. Interviewers ask it because solving it needs an understanding of how a connection pool works and how to read a thread dump. In this answer, we will recap how the pool works, read what the thread dump is telling us, fix the limits, find leaked connections, add a fail-fast timeout, and make the pool visible with metrics.

1A Quick Recap of the Connection Pool

Opening a new TCP and TLS connection for every request is slow, so Apache HttpClient 5 keeps open connections in a pool managed by PoolingHttpClientConnectionManager. A route is a target host and port, such as inventory:8080. The pool has two limits: maxTotal, the most connections across all routes, and maxPerRoute, the most connections to one route, with defaultMaxPerRoute applying to every route not configured separately.

When a thread wants to send a request, it leases a connection for that route. If one is idle, it gets it at once. If the route is at its limit, the thread waits until another thread releases one. A connection is released when the response is fully consumed or closed. Historically the defaults have been small, on the order of 5 connections per route and 25 in total, so check the values for your version.

2Reading the Thread Dump

The thread dump in the question shows many request threads in the WAITING or TIMED_WAITING state with frames from the pool's lease method, for example inside the connection manager's lease and a pool class such as StrictConnPool. That pattern tells us they are not waiting for the network. They are waiting for permission to use a connection.

Little's law explains why. The number of requests in flight equals throughput times latency. At 1,000 requests per second to inventory with 20 ms each, we need about 1,000 x 0.020 = 20 connections busy on average, and more at peaks. With a per-route limit of 5, at most 5 requests run at once, so 5 / 0.020 = 250 requests per second is the most the pool can carry. Everything above that queues, and the queue grows until requests wait for seconds, even though each one, once it gets a connection, takes 20 ms.

Step throughThreads queue for a connection, not for the server
Request threadsConnection poolInventory
lease connection (route limit 5)
5 threads get one
thread 6 to 200: lease
no free connection, threads wait
5 requests in flight
responses in 20 ms
released connection goes to next waiter

7 messages in order. Play them, or step through them one at a time.

The downstream is fast; the pool lets only 5 requests through at a time.

3Raising the Limits to Match Concurrency

We size the pool from the expected concurrency to each host, with headroom for latency spikes. If inventory's p99 latency is 50 ms at a peak of 1,500 requests per second, 1,500 x 0.050 = 75 connections cover the slow tail, so a per-route limit of 100 is reasonable. maxTotal must be at least the sum of what all routes need.

Java
PoolingHttpClientConnectionManager pool = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnTotal(200) // across all hosts
.setMaxConnPerRoute(100) // default for every route
.setDefaultConnectionConfig(ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(1))
.setSocketTimeout(Timeout.ofSeconds(2))
.build())
.build();
RequestConfig requests = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMillis(200)) // wait at most 200 ms for a pooled connection
.setResponseTimeout(Timeout.ofSeconds(2))
.build();
CloseableHttpClient http = HttpClients.custom()
.setConnectionManager(pool)
.setDefaultRequestConfig(requests)
.build();
RestClient restClient = RestClient.builder()
.requestFactory(new HttpComponentsClientHttpRequestFactory(http))
.build();
// before: p99 3,200 ms under load; after: p99 40 ms

Notice that we also check the other side. A larger pool means more concurrent requests reach inventory, so we confirm it can take 100 connections from each of our instances. Raising a limit without that check moves the queue from our pool to the downstream's thread pool.

4Making Sure Connections Return to the Pool

A pool that is large enough can still run dry if connections leak. A connection returns to the pool only when the response entity is fully consumed or the response is closed. Code that reads the status and ignores the body, or returns early on an error, keeps the connection leased until it is garbage-collected, if ever.

Java
// Leaks: on 404 we return without consuming or closing the response
ClassicHttpResponse res = http.executeOpen(null, new HttpGet(url), null);
if (res.getCode() == 404) return Optional.empty(); // connection stays leased
// Safe: a response handler consumes the entity and releases the connection
Optional<Stock> stock = http.execute(new HttpGet(url), response -> {
if (response.getCode() == 404) return Optional.empty(); // entity consumed by execute()
return Optional.of(mapper.readValue(response.getEntity().getContent(), Stock.class));
});

Through RestClient, retrieve() with body() or toBodilessEntity() reads and closes the response for us. The risky places are exchange() callbacks and code that uses the Apache client directly, so those are where we look first. The pool metrics below show a leak clearly: leased connections stay high even when traffic drops.

5Failing Fast and Watching the Pool

The connection-request timeout we set above changes the failure mode. Without it, waiting can last a long time by default (check your version), so a pool problem shows up as mysterious multi-second latency. With 200 ms, an exhausted pool produces a clear ConnectionRequestTimeoutException, which our error handling, metrics and alerts can see.

For visibility, Micrometer has a binder for Apache HttpClient 5 pools, PoolingHttpClientConnectionManagerMetricsBinder, which publishes the leased, pending and available connection counts and the limits as gauges (check the exact metric names for your Micrometer version). Pending above zero for long periods means the pool is too small or connections are leaking; leased equal to the limit at peak means we are at capacity.

Java
new PoolingHttpClientConnectionManagerMetricsBinder(pool, "inventory").bindTo(meterRegistry);
// gauges per pool: leased 37, pending 0, available 63, max 200

6Follow-up questions

How would you size the pool from expected throughput and latency?

With Little's law: connections needed equal requests per second times latency in seconds. I use peak throughput and a high percentile such as p99 rather than the average, because the slow requests hold connections longest. For 1,500 requests per second at a p99 of 50 ms, that is 75, so I set the per-route limit to about 100 for headroom, check that maxTotal covers all routes, and confirm the downstream can handle that many connections from every instance of our service.

Why not just set the limits to 10,000?

Because the pool is also a safety valve. An enormous pool lets a slow dependency absorb thousands of connections and threads, and can overload the downstream with more concurrency than it can serve. A sized pool with a short acquire timeout fails fast and protects both sides.

Does Spring Boot configure the Apache pool for us?

When Apache HttpClient 5 is on the classpath, Spring Boot can use it for auto-configured clients, but the pool limits are not tuned for our traffic, and the defaults may still be the library's. If the limits matter, and they always do under load, I build the connection manager myself or use the customisation hooks Boot provides in that version.

7Conclusion

In this answer, we saw that threads waiting inside the connection pool's lease method mean the pool, not the downstream, is the bottleneck. Little's law showed how a small per-route limit caps throughput far below demand. We raised maxTotal and maxPerRoute on PoolingHttpClientConnectionManager to match peak concurrency, checked that the downstream can take the extra load, made sure every response is consumed or closed so connections come back, added a short connection-request timeout so a dry pool fails fast, and exposed leased, pending and available counts through Micrometer.

What to say in the interviewAbout 80 seconds aloud

Open with

Threads parked in the pool's lease method tell me they are waiting for a connection, not for the network, so the bottleneck is our own pool. The first suspect is the per-route limit.

Then, if they want more

Apache HttpClient's defaults are small, historically 5 per route and 25 in total, though I would check the version. By Little's law, 5 connections at 20 milliseconds carry at most 250 requests per second, so if we send 1,000, the rest queue and wait for seconds.

I would size the pool from peak throughput times p99 latency, for example 1,500 per second at 50 milliseconds is 75, so a per-route limit around 100, and set maxTotal to cover all routes, after checking the downstream can take that many connections per instance.

Second, I would look for leaks: a connection only returns when the response is consumed or closed, so code that returns early on a 404 without closing keeps it leased. Response handlers or RestClient's retrieve().body() handle that. Third, I would set a connection-request timeout of a couple of hundred milliseconds so an exhausted pool fails fast with a clear exception.

And I would bind the pool to Micrometer to watch leased, pending and available connections, because pending above zero is the early warning.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Under load, outgoing calls through Apache HttpClient 5 queue for seconds even though the...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/5f0789d9a5/