Scrivio Interview library
DesignIntermediate10 min read · updated 12 November 2026

Design the thread pool configuration for a service that calls a payment provider with p50 latency 80 ms and p99 600 ms, at peak 500 calls per second, where the provider allows at most 200 concurrent connections from you.

Little's law says the calls in flight equal the arrival rate times the time each call takes: 500 per second times 0.08 s is about 40 in normal times, but a slowdown towards the 600 ms tail would need 300, which the provider will not allow. So we cap the threads and the HTTP connection pool together below the provider's limit of 200 (shared across all our instances), put a small bounded queue in front with a fail-fast rejection, keep timeouts below the request deadline behind a circuit breaker, and prove the numbers with metrics and a load test.

Why this question is asked

Calls to a payment provider are where a thread pool configuration is tested for real. The provider is slower than our own code, its latency has a long tail, and it limits how many connections we may open. If the pool is too small, customers wait at checkout; if it is too large, we break the provider's limit or pile up threads that all wait on the same slow dependency. Interviewers ask this question to see whether we can turn latency numbers into a concrete configuration instead of guessing. In this answer, we will recap how ThreadPoolExecutor uses its parameters, size the pool with Little's law, line up the HTTP client with the pool, choose the queue and rejection policy, add timeouts and a circuit breaker, and finish with the metrics and load test that tell us whether we were right.

1A Quick Recap of the ThreadPoolExecutor Parameters

A ThreadPoolExecutor has a core size, a maximum size, a work queue and a rejection handler. When a task arrives and fewer than core threads exist, the pool starts a new thread. When core threads are all busy, the task goes into the queue. Only when the queue is full does the pool start extra threads, up to the maximum. When the maximum is reached and the queue is full too, the task is rejected and the rejection handler decides what happens.

Notice the order, because it surprises many people: the pool grows past the core size only after the queue is full. With a core of 20, a maximum of 200 and a queue of 1,000, we would run 20 threads and let 1,000 calls wait before the 21st thread ever starts. For a pool in front of a slow dependency, we usually want the threads first and only a small queue, so we set core and maximum to the same value.

2Sizing the Pool With Little's Law

Little's law is a simple rule from queueing theory: the average number of items in a system equals the rate at which they arrive times the average time each one spends inside. For us, the items are payment calls, so the number of calls in flight, which is the number of threads busy at once, is calls per second times seconds per call.

The question gives us a p50 of 80 ms, which means half the calls finish within 80 ms, and a p99 of 600 ms, which means one call in a hundred takes 600 ms or more. The average sits above the p50 because the slow tail pulls it up, so we work through a few cases.

Java
double rate = 500; // calls per second at peak
double atP50 = rate * 0.080; // 40 calls in flight if every call took 80 ms
double atMean = rate * 0.120; // 60 if the real average, tail included, is about 120 ms
double slowDay = rate * 0.600; // 300 if the provider degrades and every call takes 600 ms
int providerLimit = 200; // concurrent connections the provider allows from us, in total
From latency numbers to pool size
CaseLatency usedCalls in flight (all pods)Fits under 200?
Normal, p5080 ms40yes, plenty of room
Normal, tail includedabout 120 ms average60yes
Provider slowdown600 ms for every call300no: we must queue or shed
Our cap-180 total, 60 per podyes, 20 kept for deploys
Little's law turns rate and latency into concurrency; the provider's limit decides where we stop.

So in normal operation we need roughly 40 to 60 threads, and we want headroom above that for bursts and for the tail. But we cannot follow the provider all the way into a slowdown: 300 concurrent calls is more than we are allowed. That tells us the most important design fact. When the provider gets slow, some calls must wait or fail; the configuration decides which, and how quickly.

There is a catch in the provider limit: 200 is the limit from us, not from one instance. If our service runs on three pods, the pods share it. During a rolling deploy there may briefly be four or five pods, and retries add a few connections too. So we keep a margin, for example 180 usable, and divide it: 60 per pod across three pods. Each pod then needs about 13 to 20 threads at peak in normal times and has room for three to four times that before it hits its cap.

3Matching the HTTP Client's Connection Pool

A thread that wants to call the provider needs an HTTP connection. If the client library holds fewer connections than we have threads, the extra threads wait inside the library for a connection and our thread count means nothing. If it holds more, nothing stops a second code path from opening connections beyond our budget. So the thread pool and the connection pool get the same number.

Java
int perPod = 60; // (200 - 20 spare) / 3 pods
ThreadPoolExecutor paymentPool = new ThreadPoolExecutor(
perPod, perPod, // core = max: threads start before anything queues
30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(30), // a small queue, sized below
Thread.ofPlatform().name("payment-", 0).factory(),
new ThreadPoolExecutor.AbortPolicy()); // a full pool fails fast
paymentPool.allowCoreThreadTimeOut(true); // idle threads go away at night
PoolingHttpClientConnectionManager connections = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnTotal(perPod) // the same 60
.setMaxConnPerRoute(perPod) // one route: the provider's host
.setDefaultConnectionConfig(ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofMilliseconds(300))
.setSocketTimeout(Timeout.ofMilliseconds(1200))
.build())
.build();

Notice the per-route setting. Apache HttpClient 5 has low defaults for connections per route (check your version), and a payment client talks to one host, so the per-route limit is the one that actually applies. Forgetting it is a classic way to end up with 60 threads sharing a handful of connections.

4Choosing the Queue and the Rejection Policy

A queue lets us absorb a short burst without failing anyone. But every queued call adds waiting time on top of the provider's latency, so we size the queue from the extra wait we can accept, not from memory. With 60 threads and 80 ms calls, one pod completes about 60 / 0.08 = 750 calls per second. A queue of 30 therefore adds at most about 40 ms of waiting. A queue of 10,000 would add over 13 seconds, long after the customer has given up.

When the queue is full, we want a fast, clear answer. AbortPolicy throws RejectedExecutionException, which our code turns into a quick error such as HTTP 503 with a Retry-After header, or into the checkout's own fallback such as asking the customer to try again. We avoid CallerRunsPolicy here because it would make the web server's request threads call the slow provider themselves, which spreads the slowdown to every endpoint. We avoid DiscardPolicy because silently dropping a payment is never acceptable.

Step throughWhat happens to one payment call
  1. Free thread in the pool?up to 60 per pod
    YesCall the provider nowNoCheck the queue
  2. Space in the queue of 30?about 40 ms of extra wait
    YesWait, then callNoReject
  3. Reject with AbortPolicymap to 503 or a checkout fallback
  4. Call the providerconnect timeout 300 ms, read timeout 1.2 s
  5. Circuit breaker open?too many slow or failed calls
    YesFail fast without callingNoSend the request

5 steps in order. Play them, or step through them one at a time.

Each stage has a limit, so a slow provider produces fast errors instead of piled-up threads.

So the full path of one payment call is: take a free thread if there is one, otherwise wait briefly in the small queue, otherwise fail fast. The picture below shows the decision.

5Timeouts and a Circuit Breaker

The pool only protects us if threads come back. A call without a timeout can hold a thread and a connection for minutes when the provider hangs. So we set a connect timeout, the time allowed to open the TCP connection, of about 300 ms, and a read timeout, the time allowed to wait for response bytes, of about 1.2 s. Both stay below the deadline of the whole request, say 2 seconds for the checkout call, so our service can still answer the customer after the provider times out.

A circuit breaker watches the results of recent calls. When too many fail or are too slow, it opens and fails new calls immediately for a short time, then lets a few test calls through. This stops us from sending 500 calls per second into a provider that is already struggling, and it frees our threads at once instead of after each timeout.

Java
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
.failureRateThreshold(50) // open when half the recent calls fail
.slowCallDurationThreshold(Duration.ofMillis(800)) // a call slower than this counts as slow
.slowCallRateThreshold(50) // open when half the recent calls are slow
.waitDurationInOpenState(Duration.ofSeconds(10)) // then try again after 10 s
.build();

But there is a catch specific to payments: a read timeout does not mean the payment failed. The provider may have charged the card and only the response was late. So every request carries an idempotency key, a unique id the provider uses to recognise a retry of the same payment, and after a timeout we query the payment's status instead of blindly charging again.

6Metrics and a Load Test

All the numbers above are estimates, so we make them visible. Micrometer's ExecutorServiceMetrics can bind the pool and publish active threads, queued tasks and pool size. We add a counter in a small wrapper around the rejection handler, and the connection manager's leased and pending connections, so a dashboard shows all three limits side by side. An alert on rejections and on queue depth tells us when the configuration is too tight.

Then we load test against the provider's sandbox or a stub that copies its latency distribution: 500 calls per second with the real p50 and p99, then a run where the stub's latency jumps to 600 ms, then one where it hangs. We check that threads stay at or below 60 per pod, that rejections appear quickly in the slowdown, that the circuit breaker opens, and that the service recovers on its own once the stub is healthy again.

7Follow-up questions

Why not simply set the pool to 200 threads per pod?

Because the provider counts connections from all our pods together. Three pods with 200 threads each could open 600 connections and break the agreement, and in a slowdown all 600 threads would just wait on the same slow provider. The cap must be derived from the shared limit and divided across instances.

Would virtual threads change this design?

They would remove the cost of each waiting thread, so we would not need a pool to keep thread counts low. But the provider's limit of 200 does not change, so we would still need an explicit limit, such as a Semaphore with 60 permits per pod in front of the client, plus the same timeouts, circuit breaker and metrics.

Why is the mean latency higher than the p50?

Latency distributions are skewed: most calls are fast and a few are very slow. The p50 ignores how slow the slow ones are, while the mean includes them. With a p99 of 600 ms, a small fraction of very slow calls is enough to pull the average well above 80 ms, which is why we size from the mean plus headroom, not from the median.

8Conclusion

In this answer, we turned latency numbers into a pool configuration. Little's law gave about 40 to 60 calls in flight normally and 300 in a slowdown, which is more than the provider's limit of 200. So we divided that limit across our pods, matched the HTTP connection pool to the thread pool, used core equal to maximum with a small bounded queue and a fail-fast AbortPolicy, kept connect and read timeouts below the request deadline behind a circuit breaker, and made the whole setup visible with metrics and a load test that includes a slow and a hanging provider.

What to say in the interviewAbout 100 seconds aloud

Open with

I would start with Little's law: concurrency is rate times latency. At 500 calls per second and 80 ms that is about 40 calls in flight, maybe 60 with the tail included, but if the provider slows to its p99 of 600 ms we would need 300, and the provider only allows 200 connections from us in total.

Then, if they want more

So the design has to decide what happens in a slowdown. First, the 200 is shared by all our instances, so I keep a margin for deploys and retries and divide the rest, for example 60 per pod across three pods.

I set the thread pool's core and maximum to 60, because ThreadPoolExecutor only grows past core when the queue is full, and I set the HTTP client's total and per-route connections to the same 60.

In front of it I put a small bounded queue, around 30, which adds about 40 milliseconds of wait at that throughput, and AbortPolicy so a full pool becomes a fast 503 or a checkout fallback. I would not use CallerRunsPolicy, because it moves the slow call onto request threads.

Then I set a connect timeout around 300 milliseconds and a read timeout around one second, below the request deadline, and wrap the client in a circuit breaker. Because it is payments, every call has an idempotency key and a timeout leads to a status check, not a blind retry.

Finally I publish active threads, queue depth, rejections and leased connections, and load test with the normal latency, a 600 millisecond slowdown and a hanging provider.

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 "Design the thread pool configuration for a service that calls a payment provider with...": https://scrivio-interview-library.netlify.app/java/executors/b949f6fa0e/