Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A shared Retrofit-based SDK used by 40 services creates a new OkHttpClient for every API instance, and services run out of threads and file descriptors. Explain and fix at the library level.

Every OkHttpClient owns its own connection pool and its own dispatcher with a thread pool, so an SDK that creates a new client for every API instance multiplies idle sockets, which are file descriptors, and threads across every service that uses it. The fix at the library level is to share one OkHttpClient and derive per-API variants with newBuilder(), which shares the pool and dispatcher, to let the host application supply the client so it controls timeouts, metrics and TLS, and to close or evict resources when a client is really discarded. Then we add guidelines and a review step for resource handling in shared SDKs, so the next library does not repeat it.

Why this question is asked

A bug in a shared SDK is a bug in every service that uses it, and resource leaks are the worst kind because they only appear under real traffic and time. Here 40 services run out of threads and file descriptors, and each team first suspects its own code. Interviewers ask this scenario because the fix needs an understanding of what an HTTP client object actually holds, and because a good answer fixes the library's design, not just the symptom. In this answer, we will recap what an OkHttpClient owns, reproduce the leak, fix it with a shared client and newBuilder(), let the host supply the client, handle shutdown, and put guidelines in place.

1A Quick Recap of What an OkHttpClient Owns

An OkHttpClient is not a lightweight configuration object. It owns a ConnectionPool, which keeps idle connections open for reuse, by default up to 5 idle connections per pool kept alive for 5 minutes (check your version). Each open connection is a socket, and each socket uses a file descriptor, an operating system handle of which a process has a limited number, often 1,024 or 65,536 depending on configuration. It also owns a Dispatcher with an ExecutorService that creates threads for asynchronous calls made with enqueue(), and HTTP/2 connections use reader threads of their own.

OkHttp's documentation says it plainly: create one OkHttpClient and reuse it for all calls, because each instance holds its own pool and threads.

2Reproducing the Leak

The SDK's factory method looked harmless. Every call to OrdersSdk.create() built a fresh OkHttpClient, and some services called create() per request or per tenant.

Java
// Inside the shared SDK (before)
public static OrdersApi create(String baseUrl, String apiKey) {
OkHttpClient ok = new OkHttpClient.Builder() // new pool + new dispatcher every time
.addInterceptor(new ApiKeyInterceptor(apiKey))
.readTimeout(Duration.ofSeconds(5))
.build();
return new Retrofit.Builder().baseUrl(baseUrl).client(ok)
.addConverterFactory(JacksonConverterFactory.create()).build()
.create(OrdersApi.class);
}
// A service calling it per request at 200 req/s:
OrdersApi api = OrdersSdk.create(url, tenant.apiKey());
api.get(orderId).execute();
// each client keeps its idle connection open for up to 5 minutes:
// 200 req/s x 300 s = up to 60,000 idle sockets -> "Too many open files"
Resources per OkHttpClient instance
ResourcePer instanceWith thousands of instances
Connection poolown pool, idle sockets kept ~5 mintens of thousands of open sockets
Dispatcher threadsown executor for async callsthousands of threads, memory exhausted
HTTP/2 reader threadsone per open HTTP/2 connectionmore threads
TLS sessions, cachesnot shared between instancesrepeated handshakes, wasted memory
A client is a heavy object: create it once.

Notice that nothing is technically leaked in the Java sense: each client becomes garbage eventually. But its idle connections stay open until the keep-alive expires, and its dispatcher threads live until their idle timeout. Thousands of short-lived clients accumulate thousands of sockets and threads faster than they expire, and the process hits its file descriptor limit or runs out of memory for threads.

3Fix 1: Share One Client and Derive Variants With newBuilder()

Different APIs often need slightly different settings, such as another timeout or an API key interceptor. newBuilder() creates a builder that starts from an existing client's configuration and shares its connection pool, dispatcher and other resources. The resulting client is cheap, and all variants reuse the same sockets and threads.

Java
public final class OrdersSdk {
private static final OkHttpClient SHARED = new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(2))
.readTimeout(Duration.ofSeconds(5))
.build();
public static OrdersApi create(String baseUrl, String apiKey) {
return create(SHARED, baseUrl, apiKey);
}
public static OrdersApi create(OkHttpClient base, String baseUrl, String apiKey) {
OkHttpClient ok = base.newBuilder() // shares pool and dispatcher with base
.addInterceptor(new ApiKeyInterceptor(apiKey))
.build();
return new Retrofit.Builder().baseUrl(baseUrl).client(ok)
.addConverterFactory(JacksonConverterFactory.create()).build()
.create(OrdersApi.class);
}
}
// 200 req/s, any number of tenants: one pool, idle sockets bounded by the pool limit
Step throughAfter the fix: variants share the expensive parts
  1. OrdersApi per tenantRetrofit proxy, cheap
  2. Variant OkHttpClient from newBuilder()own interceptors and timeouts
  3. Shared base OkHttpClientone connection pool, one dispatcher
  4. Operating systembounded sockets and threads

4 layers, from the top down. Step through them one at a time.

Notice that per-tenant variants are now nearly free. Better still, services should create the API once per tenant and cache it, but even if they do not, the expensive resources are shared.

4Fix 2: Let the Host Application Supply the Client

A library that builds its own HTTP client takes decisions away from the service that uses it. The service cannot set its own timeouts, add its tracing interceptor, register metrics, or configure custom TLS certificates. So the SDK should accept an OkHttpClient from the host, as the second create() overload above does, and fall back to its shared default only when none is given. A Spring Boot service then defines one OkHttpClient bean, configured to company standards with Micrometer instrumentation, and passes it to every SDK that uses OkHttp. That also makes the 40 services' outbound calls visible in the same metrics.

5Fix 3: Release Resources When a Client Is Discarded

Sometimes a client really is temporary, for example in a test or a short-lived job. Then it should be shut down explicitly instead of waiting for keep-alive and idle timeouts. OkHttp documents the steps: shut down the dispatcher's executor, evict all pooled connections, and close the cache if one was configured. The SDK can expose a close() method that does this for clients it created itself, but must never shut down a client the host supplied.

Java
void shutdown(OkHttpClient client) {
client.dispatcher().executorService().shutdown(); // stop accepting async calls, let threads end
client.connectionPool().evictAll(); // close idle sockets now
if (client.cache() != null) client.cache().close();
}

6Preventing the Next One

The bug passed review because nobody reviewing an SDK thought about resource lifecycles. We add a short guideline for shared libraries: heavy clients (HTTP clients, connection pools, thread pools) are created once or supplied by the host; any resource the library creates has a documented owner and a close path; and libraries do not set network defaults the host cannot override. A review checklist for shared SDKs includes these questions, and a simple load test of the SDK, creating many API instances in a loop while watching open file descriptors and thread count, would have caught this before release. Finally, we publish a fixed version, tell the 40 teams which services call create() per request, and track the upgrade until open sockets and threads return to normal.

7Follow-up questions

Is it enough to make OkHttpClient a static singleton inside the SDK?

It fixes the leak, but it leaves the host unable to control timeouts, metrics and TLS, and two SDKs would still create two separate clients. Accepting a client from the host, with a shared default as fallback, fixes both.

How would you confirm the diagnosis in production?

Count open file descriptors and threads of the process over time, for example with lsof or the process metrics Micrometer exposes, and take a thread dump: many threads with OkHttp names, such as dispatcher or HTTP/2 reader threads, point to too many clients. A heap dump showing thousands of OkHttpClient and ConnectionPool instances confirms it.

Does the same problem exist with other clients?

Yes. Creating a new Apache HttpClient, JDK HttpClient or Reactor Netty connection provider per call has the same effect, because each owns pools and threads. The rule is general: HTTP clients are long-lived, shared objects.

8Conclusion

In this answer, we saw that each OkHttpClient owns a connection pool and a dispatcher, so an SDK that creates one per API instance multiplies idle sockets and threads until services exhaust their file descriptors and memory. We fixed it at the library level by sharing one client and deriving variants with newBuilder(), which shares the pool and dispatcher, by letting the host application supply the client so it controls timeouts, metrics and TLS, and by shutting down clients that really are discarded. Guidelines, a review checklist and a load test for shared SDKs keep it from happening again.

What to say in the interviewAbout 90 seconds aloud

Open with

An OkHttpClient is a heavy object. Each instance has its own connection pool, which keeps idle sockets open for about five minutes by default, and its own dispatcher with a thread pool for async calls, plus reader threads for HTTP/2.

Then, if they want more

So if the SDK builds a new client for every API instance, and some services create an API per request or per tenant, they accumulate tens of thousands of idle sockets, each a file descriptor, and lots of threads, faster than keep-alive expires them. That is the 'too many open files' and thread exhaustion across 40 services.

At the library level I would fix it in three ways. First, keep one shared base client and create per-API variants with newBuilder(), which shares the pool and dispatcher, so an extra interceptor or timeout costs almost nothing.

Second, let the host application pass in its own OkHttpClient, so the service controls timeouts, tracing, metrics and TLS and every SDK reuses the same pool; the shared default is only a fallback.

Third, for clients the SDK itself creates and discards, provide a close that shuts down the dispatcher executor, evicts the pool and closes the cache, but never close a host-supplied client.

Then I would ship it as a new version, help the teams upgrade, and add SDK guidelines and a review checklist about resource ownership, with a simple load test that watches file descriptors and threads.

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 "A shared Retrofit-based SDK used by 40 services creates a new OkHttpClient for every API...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/794cb74e82/