Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A service using a Jersey client starts timing out under load; thread dumps show many threads waiting to lease a connection, and the code creates ClientBuilder.newClient() inside each request handler. Explain the problems and the fix.

Creating a new Jersey Client inside every request handler rebuilds providers and a fresh connection pool on each call, wastes memory, and leaks sockets when the client is never closed, while responses that are not closed or fully read keep their connections leased so other threads wait. The fix is one shared, pooled Client with explicit limits and timeouts, try-with-resources around every Response, pool metrics, and bulkheads and retries applied at a single layer.

Why this question is asked

Timeouts that only appear under load are some of the hardest incidents to read, because every single request looks fine in a test. Interviewers ask this one because the thread dump tells the whole story if we know how a JAX-RS client manages connections, and the same mistakes appear with Spring RestTemplate, RestClient and plain Apache HttpClient. In this answer, we will recap what a Jersey Client owns, reproduce the broken pattern, read the thread dump, and then walk through the fix: a shared pooled client, closing responses, timeouts, metrics, and protection against a slow dependency.

1A Quick Recap of What a Jersey Client Owns

In JAX-RS, the client API starts with ClientBuilder.newClient(), which returns a Client. A Client is not a small object. It holds the configuration, the registered providers (the message body readers and writers that turn JSON into objects, filters, and interceptors), and a connector, the component that actually opens TCP connections. Jersey's default connector uses the JDK's HttpURLConnection; the optional Apache connector uses Apache HttpClient with a connection pool, a set of open connections that are kept alive and lent out to requests.

The JAX-RS specification says that Client instances are heavyweight and should be reused, and that they must be closed with close() when we are done, so that the connector can release its resources. A Response is also a resource: while its entity stream is open, the underlying connection belongs to that response and cannot be lent to anyone else.

2Reproducing the Broken Pattern

Here is the kind of handler that produces the incident. It looks harmless and passes every functional test.

Java
@GET
@Path("/orders/{id}")
public OrderView order(@PathParam("id") long id) {
Client client = ClientBuilder.newClient(config); // new providers, new connector, new pool
Response r = client.target(pricingUrl).path("prices/{id}")
.resolveTemplate("id", id).request().get();
if (r.getStatus() != 200) {
return OrderView.withoutPrice(id); // entity never read, response never closed
}
Price p = r.readEntity(Price.class); // reads and closes the stream
return OrderView.of(id, p); // client never closed
}

Three problems hide here. Every call builds a Client, so Jersey initialises its providers and the connector creates a new pool, only to use it once. The client is never closed, so its pool and any kept-alive sockets stay around until garbage collection eventually finds them, which shows up as growing memory and many sockets in CLOSE_WAIT or ESTABLISHED. And on the error path the Response is neither read nor closed, so the connection it holds is never returned.

3Reading the Thread Dump

The dump shows many threads parked inside the pool, waiting to lease a connection. That wait only happens when a pool has handed out all its connections and none come back. Unclosed responses are exactly how connections fail to come back: each leaked Response keeps one connection checked out until something closes it. With Apache HttpClient the default per-route limit is small (2 in HttpClient 4 and 5 in HttpClient 5, check your version), so a handful of leaks is enough to make every following request wait for its connection-request timeout, and if that timeout is not set, wait forever.

Load makes it worse: threads waiting for a lease serve nobody, so the container's thread pool fills up and our own callers time out too. That is why the symptom appears only under load.

Step throughHow one leaked response blocks the next request
Handler APool (max 2)Handler BPricing service
lease connection 1
GET /prices/1
404, body not read
returns without close(): connection 1 stays leased
lease connection
connection 2 granted
GET /prices/2, also not closed
next request: lease connection
waits: no free connection

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

Connections are only returned when the response is closed or its entity fully read.

4The Fix: One Shared, Pooled Client

We create the Client once, at startup, as a singleton (a CDI @ApplicationScoped producer, a Spring @Bean, or a static field in plain code), configure a pooled connector with explicit limits, and close it at shutdown. Clients are thread-safe for issuing requests, so one instance serves all threads.

Java
@ApplicationScoped
public class PricingClientProducer {
@Produces @ApplicationScoped
Client pricingClient() {
var pool = new PoolingHttpClientConnectionManager(); // Apache HttpClient 5
pool.setMaxTotal(200); // all routes together
pool.setDefaultMaxPerRoute(50); // per target host
ClientConfig cfg = new ClientConfig()
.connectorProvider(new Apache5ConnectorProvider()) // jersey-apache5-connector, check your version
.property(Apache5ClientProperties.CONNECTION_MANAGER, pool);
return ClientBuilder.newBuilder().withConfig(cfg)
.connectTimeout(2, TimeUnit.SECONDS) // time to open a TCP connection
.readTimeout(3, TimeUnit.SECONDS) // time to wait for data
.build();
}
void close(@Disposes Client c) { c.close(); }
}

Notice that the limits are now written down. 50 connections per route means at most 50 concurrent calls to the pricing service from this instance, and the timeouts mean a slow pricing service costs at most a few seconds per call instead of a thread forever. Set Apache's connection-request timeout too, so waiting for a lease fails fast. If the team uses MicroProfile Rest Client, the same idea applies: inject the generated proxy, which the runtime reuses, instead of building one per call.

5Closing Every Response

The second half of the fix is making sure every Response goes back to the pool. Response implements AutoCloseable, so try-with-resources is the simplest guarantee.

Java
try (Response r = pricingClient.target(pricingUrl).path("prices/{id}")
.resolveTemplate("id", id).request(MediaType.APPLICATION_JSON).get()) {
if (r.getStatus() == 404) return OrderView.withoutPrice(id); // closed by try-with-resources
if (r.getStatus() != 200) throw new PricingUnavailable(r.getStatus());
return OrderView.of(id, r.readEntity(Price.class));
}
// Simpler when we only need the body: request().get(Price.class) reads and closes for us

readEntity() for a normal Java type reads the whole stream and closes it, and the typed get(Price.class) shortcut does the same, throwing a WebApplicationException for non-2xx statuses. The dangerous cases are the ones where we look at the status and leave, or read the entity as an InputStream and forget it. After the fix, we publish the pool's leased, available and pending counts as metrics, so a dashboard shows exhaustion coming.

6Protecting the Service From a Slow Dependency

A pricing service that slows from 50 ms to 3 seconds can still tie up every request thread. A bulkhead, a limit on how many concurrent calls may go to one dependency, keeps the damage contained: with a bulkhead of 40 and a pool of 50, at most 40 of our 200 request threads can ever be stuck on pricing, and the rest keep serving other work. MicroProfile Fault Tolerance (@Bulkhead, @Retry) and Resilience4j provide this.

Retries need care. If the client retries 3 times, the service mesh retries 3 times and the caller retries 3 times, one slow request becomes 27 calls at the worst moment. So we pick one layer to retry, retry only idempotent calls such as GET, use exponential backoff with jitter (for example 100 ms, 200 ms, 400 ms with random spread), and cap the total time below the caller's own timeout.

7Follow-up questions

Is a JAX-RS Client thread-safe?

Using a configured Client to build and send requests is safe from many threads, and that is how it is meant to be used. What we should not do is change its configuration, for example register new providers, while other threads are using it. If two endpoints need different settings, we create two clients at startup, each configured once.

Why not keep the default HttpURLConnection connector and just reuse the client?

Reusing the client already removes most of the cost, and the JDK does keep connections alive behind HttpURLConnection. But we get little control over it: no clear maximum per host, no lease timeout and few metrics. Under high load we want a pool whose limits we choose and can watch, so the Apache connector, or the JDK HttpClient based connector in newer Jersey versions (check your version), is the better choice.

8Conclusion

In this answer, we saw why creating ClientBuilder.newClient() per request hurts: each call rebuilds providers and a connection pool, and unclosed clients leak memory and sockets. The threads waiting for a lease pointed at responses that were never closed or fully read, so connections never returned to the pool. The fix is one shared client with a pooled connector, explicit pool limits, connect, read and lease timeouts, try-with-resources around every Response, pool metrics on a dashboard, and bulkheads and retries with backoff at a single layer so a slow dependency cannot take every thread.

What to say in the interviewAbout 80 seconds aloud

Open with

The thread dump is the key clue. Threads waiting to lease a connection means the pool has given out every connection and none are coming back, and the usual reason is Response objects that are never closed or fully read, for example when we check the status on an error path and return.

Then, if they want more

On top of that, the code creates a new Client in every handler, which is expensive: Jersey rebuilds its providers and the connector builds a new pool each time, and since nobody calls close(), those pools and sockets leak. My fix has a few parts.

First, one shared Client created at startup with a pooled connector, such as Jersey's Apache connector, with explicit max total and max per route, and connect, read and connection-request timeouts, closed at shutdown. Second, every Response goes in try-with-resources, or we use the typed get that reads and closes for us.

Third, I publish the pool's leased and pending counts so we can see exhaustion coming. Finally, because a slow dependency can still consume all request threads, I add a bulkhead per dependency and retries with backoff for idempotent calls, at one layer only, so retries do not multiply across the client, the mesh and the caller.

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.
Official documentation
Jakarta EE specifications
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 "A service using a Jersey client starts timing out under load; thread dumps show many...": https://scrivio-interview-library.netlify.app/java/jax-rs/7af99cc592/