Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Show how to build an HTTP client in a Dropwizard application with configured timeouts and connection pool size, and explain why you would use Dropwizard's builder rather than a plain client.

We add a JerseyClientConfiguration field to the configuration class, set timeout, connectionTimeout, maxConnections, maxConnectionsPerRoute and gzipEnabled in the YAML, and build the client once in run with new JerseyClientBuilder(environment).using(config.getHttpClient()).build("payments-client"). Dropwizard's builder is better than a plain client because it ties the client to the application's lifecycle and ObjectMapper and instruments it with metrics under the client's name. HttpClientBuilder does the same for a plain Apache HttpClient, and either client must be built once and reused, since a client per request leaks connections and threads.

Why this question is asked

Almost every service calls other services, and most production incidents involving HTTP clients come from the same few mistakes: no timeouts, so one slow dependency ties up all threads; a connection pool too small or unbounded; and clients created per request, which leak connections until the process runs out of sockets. Dropwizard's client module exists to make the correct setup the easy one. Interviewers ask this to see whether we know the configuration and why each setting matters. In this answer, we will add the configuration, build the client, use it in a resource, look at what the builder adds over a plain client, and finish with the reuse rule.

1Adding the Client Configuration

The client settings belong in the YAML file like everything else, so they can differ per environment. dropwizard-client provides JerseyClientConfiguration, which extends HttpClientConfiguration with Jersey-specific settings. We add it as a field of our configuration class.

Java
public class OrdersConfiguration extends Configuration {
@Valid @NotNull
private JerseyClientConfiguration httpClient = new JerseyClientConfiguration();
@JsonProperty("httpClient")
public JerseyClientConfiguration getHttpClient() { return httpClient; }
@Valid @NotNull
private String paymentsUrl;
@JsonProperty public String getPaymentsUrl() { return paymentsUrl; }
}

Notice the annotations. @Valid tells Hibernate Validator to check the nested client settings too, so a negative pool size fails at startup rather than at the first request, and the default instance means the section may be omitted in development. Because the field is a normal part of the configuration, the check command validates it, and dw. system properties can override single values, such as -Ddw.httpClient.timeout=5s.

2The YAML Settings and What Each One Prevents

Here is the matching YAML section, with the meaning of each value in a comment.

YAML
# config.yml
paymentsUrl: https://payments.internal
httpClient:
timeout: 2s # read timeout: max wait for data on an open connection
connectionTimeout: 500ms # max time to open the TCP connection
connectionRequestTimeout: 500ms # max wait for a free pooled connection
maxConnections: 64 # total pooled connections
maxConnectionsPerRoute: 32 # per target host and port
keepAlive: 30s # reuse idle connections for this long
gzipEnabled: true # accept gzip-compressed responses
gzipEnabledForRequests: false # do not compress request bodies

Each setting answers a specific failure. timeout is how long we wait for data on an open connection; without a sensible value, a hung dependency holds our thread for minutes. connectionTimeout limits how long a TCP connection may take to open, which matters when a host is unreachable. connectionRequestTimeout limits how long a request waits for a free connection when the pool is exhausted, so overload fails fast instead of queueing forever. maxConnections and maxConnectionsPerRoute size the pool; per route means per target host and port, so with one downstream service the per-route limit is usually the one that matters.

The values should come from the downstream service's real behaviour, for example a timeout a little above its p99 latency, and a pool sized to the concurrency we expect towards it. Dropwizard's defaults are deliberately short rather than infinite; check your version's documentation for the exact values.

3Building the Client Once in run()

We build the client in run, because that is where both the validated configuration and the Environment are available, and pass it to the resources or service classes that need it.

Java
@Override
public void run(OrdersConfiguration config, Environment environment) {
Client client = new JerseyClientBuilder(environment)
.using(config.getHttpClient())
.build("payments-client"); // the name is used for metrics and threads
PaymentsGateway payments = new PaymentsGateway(client, config.getPaymentsUrl());
environment.jersey().register(new OrderResource(payments));
}
public class PaymentsGateway {
private final Client client;
private final String baseUrl;
PaymentsGateway(Client client, String baseUrl) { this.client = client; this.baseUrl = baseUrl; }
public PaymentResult charge(ChargeRequest request) {
return client.target(baseUrl).path("/charges")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(request), PaymentResult.class); // JSON written and read by the app's ObjectMapper
}
}
// A call that takes longer than 2s -> ProcessingException caused by SocketTimeoutException

Notice that the client is a standard JAX-RS Client, so the calling code is ordinary JAX-RS client code: target, path, request, post. The JSON request and response are handled by the same ObjectMapper the application uses for its own endpoints, so custom modules and date settings apply consistently. A timeout surfaces as a ProcessingException wrapping the socket timeout, which the gateway can translate into a domain error or a 503 for our caller.

4What the Builder Adds Over a Plain Client

We could create a client with ClientBuilder.newClient() or an Apache HttpClient directly. The Dropwizard builder does three things for us that we would otherwise have to remember. It ties the client to the Environment's lifecycle: the connection pool and the client's thread pool are registered as managed objects, so they are closed cleanly when the service shuts down. It configures the client with the Environment's ObjectMapper and validator, so serialisation matches the rest of the application. And it instruments the client with Dropwizard Metrics: the connection pool's leased, available and pending connections, and request timers per HTTP method, all named after the client, visible on the admin port's /metrics endpoint.

That last point is what makes the name important. With build("payments-client"), the dashboards show exactly which dependency is exhausting its pool or getting slower. If we need a plain Apache HttpClient instead of a JAX-RS client, for example for a library that expects one, HttpClientBuilder gives the same configuration, lifecycle and metrics.

Java
CloseableHttpClient raw = new HttpClientBuilder(environment)
.using(config.getHttpClient()) // JerseyClientConfiguration extends HttpClientConfiguration
.build("payments-raw");

5Reuse the Client; Never Create One per Request

A client owns a connection pool and, for Jersey's asynchronous calls, a thread pool. Creating one is expensive, and if it is not closed, its connections and threads stay alive. Code that builds a new client inside a request handler opens fresh connections every time, loses the benefit of keep-alive, and slowly leaks sockets and threads until the service fails with too many open files or runs out of memory, often days after deployment.

Step throughReusing one pooled client
Request threadspayments-clientConnection poolPayments service
post /charges (request 1)
lease connection
reuse kept-alive connection
200 OK
release connection
post /charges (request 2)
lease the same connection, no new handshake

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

A shared client reuses connections; a client per request opens and leaks new ones.

So the rule is one client per downstream service, built once at startup and shared. JAX-RS clients and Apache HttpClient are thread-safe for this use, so a single instance serves all request threads. If two downstream services need different timeouts, we create two clients with two configuration sections and two names, which also gives separate metrics and pools, so one slow dependency cannot exhaust the connections of the other.

6Follow-up questions

Should the client have retries enabled?

Only carefully. Retrying a POST that charges money can charge twice unless the downstream API is idempotent, for example through an idempotency key. The client's retries setting is best left at zero for non-idempotent calls, with retries handled deliberately in the gateway, with backoff and a limit, for safe operations.

How do you add a circuit breaker?

Dropwizard does not include one, so we wrap the gateway call with a library such as Resilience4j. The client's timeouts limit each call, and the circuit breaker stops calling a dependency that keeps failing, so our threads are not spent on calls that will time out anyway.

How do you test code that uses the client?

Start a stub server such as WireMock in the test, point the configuration's URL at it, and build the client with the same builder in a DropwizardAppExtension test. That exercises the real timeouts and JSON mapping, including a stubbed slow response to check the timeout behaviour.

7Conclusion

In this answer, we built an HTTP client in Dropwizard by adding a JerseyClientConfiguration to the configuration with timeout, connectionTimeout, pool sizes and gzip settings in YAML, and building it once in run with JerseyClientBuilder(environment).using(...).build("payments-client"). The builder ties the client to the application's lifecycle and ObjectMapper and adds metrics under the client's name, HttpClientBuilder does the same for a plain Apache HttpClient, and the client is shared rather than created per request, which would leak connections and threads.

What to say in the interviewAbout 80 seconds aloud

Open with

I add a JerseyClientConfiguration field to my configuration class, exposed as httpClient, so the settings live in the YAML: timeout for reading data, connectionTimeout for opening the connection, connectionRequestTimeout for waiting on the pool, maxConnections and maxConnectionsPerRoute to size the pool, and gzipEnabled.

Then, if they want more

I choose the values from the downstream service's real latency, for example a timeout a little above its p99. Then in run I build the client once with new JerseyClientBuilder(environment).using(config.getHttpClient()).build("payments-client") and inject it into a small gateway class that uses normal JAX-RS client calls.

I use Dropwizard's builder rather than a plain ClientBuilder because it registers the client's pools with the application lifecycle so they close at shutdown, it uses the application's ObjectMapper so JSON is consistent, and it instruments the client with metrics named after it, connection pool usage and request timers, which show up on the admin port and tell me exactly which dependency is slow.

If I need a raw Apache HttpClient, HttpClientBuilder gives the same configuration and metrics. The key rule is reuse: one client per downstream service, built at startup and shared, because creating a client per request leaks connections and threads and throws away keep-alive.

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 official documentation for the version you use. 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 "Show how to build an HTTP client in a Dropwizard application with configured timeouts...": https://scrivio-interview-library.netlify.app/java/dropwizard/5614e6573f/