Quick revision
The short answer
I would submit one task per product id to Executors.newVirtualThreadPerTaskExecutor(), because the calls are blocking HTTP requests, and guard each call with a Semaphore(20) so no more than 20 requests are ever in flight. At 200 ms per call, 5,000 calls / 20 concurrent x 200 ms is about 50 seconds, within the 2-minute budget if the provider keeps up. invokeAll(tasks, 2, TimeUnit.MINUTES) waits up to the deadline and cancels unfinished tasks, and I sort the Futures into successes, failures and timeouts for a partial report. Each call gets its own HTTP timeout and a limited retry with backoff that also goes through the semaphore. StructuredTaskScope offers cleaner cancellation but is still a preview API in Java 25.
What to remember
In this answer, we first did the arithmetic: 5,000 calls at 200 ms with 20 in flight take about 50 seconds, inside the 2-minute deadline but with limited slack. Virtual threads make one blocking task per id cheap, a Semaphore(20) enforces the provider's concurrency limit exactly, and invokeAll with a 2-minute timeout cancels whatever has not finished, so we can report successes, failures and timeouts separately. Per-call HTTP timeouts and bounded retries that also pass through the semaphore protect the limit and the deadline, and StructuredTaskScope is a cleaner model that is still in preview in Java 25.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would submit one task per product id to Executors.newVirtualThreadPerTaskExecutor(), because the calls are blocking HTTP requests, and guard each call with a Semaphore(20) so no more than 20 requests are ever in flight. At 200 ms per call, 5,000 calls / 20 concurrent x 200 ms is about 50 seconds, within the 2-minute budget if the provider keeps up. invokeAll(tasks, 2, TimeUnit.MINUTES) waits up to the deadline and cancels unfinished tasks, and I sort the Futures into successes, failures and timeouts for a partial report. Each call gets its own HTTP timeout and a limited retry with backoff that also goes through the semaphore. StructuredTaskScope offers cleaner cancellation but is still a preview API in Java 25.
Why this question is asked
Calling a rate-limited external API for thousands of items under a deadline is everyday backend work: pricing updates, address validation, enrichment jobs. The numbers in the question are chosen so that the obvious approaches fail in different ways. Calling sequentially takes 1,000 seconds, and firing all 5,000 at once breaks the provider's limit. Interviewers want to see the arithmetic, the right concurrency tools in modern Java, and a plan for partial failure. In this answer, we will do the arithmetic, recap virtual threads and semaphores, write the job, handle the deadline and partial results, add timeouts and retries, and compare with structured concurrency.
1Doing the Arithmetic First
Sequentially, 5,000 calls x 200 ms is 1,000 seconds, almost 17 minutes, so we need concurrency. The provider allows 20 concurrent requests, so the best we can do is 20 calls every 200 ms, which is 100 calls per second, and 5,000 calls take 5,000 / 100 = 50 seconds. That leaves about 70 seconds of slack within the 2 minutes for slow responses and retries.
This tells us two things before we write any code. Concurrency must be exactly bounded at 20, not approximately, because more is a violation and fewer wastes the budget. And the deadline is realistic but not generous: if the provider slows to 500 ms per call, the job needs 125 seconds and will not finish, so the partial-results path is not hypothetical.
2A Quick Recap of Virtual Threads and Semaphores
A virtual thread, final since Java 21, is a lightweight thread managed by the JVM rather than the operating system. When it blocks on I/O, such as waiting for an HTTP response, the JVM parks it and frees the underlying carrier thread for other work. Creating thousands of them is cheap, so the simplest model, one thread per task blocking on its call, becomes efficient. Executors.newVirtualThreadPerTaskExecutor() starts a new virtual thread for every submitted task.
Virtual threads remove the cost of waiting, but not the provider's limit, so we need a separate limiter. A Semaphore with 20 permits does exactly that: each task acquires a permit before calling and releases it afterwards, so at most 20 calls run at once, while the other tasks wait cheaply on acquire.
3Writing the Job
Each task acquires a permit, calls the API with a per-request timeout, and always releases the permit in finally.
- Virtual thread starts5,000 start almost at once, cheaply
- acquire a permitwaits while 20 calls are in flight
- HTTP call with a 3 s timeoutabout 200 ms normally
- release the permit in finallythe next waiting task proceeds
- Deadline passed first?YesCancelled: reported as timed outNoSUCCESS or FAILED in the report
5 steps in order. Play them, or step through them one at a time.
invokeAll with a timeout submits every task, waits until they all finish or the deadline passes, and cancels with interruption any task still running or waiting at that point. It returns the futures in the same order as the tasks, which is why futures.get(i) lines up with ids.get(i). Future.state(), resultNow() and exceptionNow(), added in Java 19, make sorting the outcomes simple. The try-with-resources block closes the executor, and close() waits for the cancelled tasks to actually finish, so the per-call timeout keeps that wait short: an interrupted task blocked on the semaphore leaves at once, and a task in the middle of a call ends within its 3-second request timeout at worst.
4Timeouts and Retries Within the Limit
Every external call needs its own timeouts: a connect timeout and a request timeout, here 2 and 3 seconds. Without them, one hung connection could hold a permit until the global deadline, reducing our effective concurrency to 19, then 18, and so on. Check how your HttpClient version applies the request timeout, since it may cover only the time until the response headers arrive.
Transient errors, such as a 503 or a connection reset, deserve a retry, but carefully. Each attempt must go through the semaphore like any other call, so retries never push us above 20 concurrent requests, and the permit should be released while we sleep between attempts, so backoff does not waste a slot. A small limit, such as two retries with exponential backoff of 200 ms and then 400 ms plus some random jitter, and a check that enough of the deadline remains before starting another attempt, keep retries from eating the budget. Errors that will not change, such as 404 for an unknown id, are reported immediately without a retry.
5Structured Concurrency as an Alternative
StructuredTaskScope treats a group of subtasks as one unit: the scope starts them, waits for them, and if the scope is closed or one policy condition is met, cancels the rest, so no task can outlive the code that started it. That fits this job well. But in Java 25 it is still a preview API, so it needs --enable-preview, and its API has changed between releases, for example the factory methods and joiners in recent previews differ from the earlier subclass-based design; check your version. For production code on Java 25, the executor with invokeAll is final, standard and enough. I would mention structured concurrency as the direction the platform is moving.
6Follow-up questions
How would you respect a rate limit of 50 requests per second as well?
That limit is stricter than our current pace: 20 concurrent calls at 200 ms each would make 100 requests per second. I would add a rate limiter next to the semaphore, for example a token bucket refilled at 50 tokens per second, from Resilience4j or Bucket4j, or a small one of our own, and each task takes a token before acquiring its permit. The job then takes 5,000 / 50 = 100 seconds, still inside the 2 minutes but with only 20 seconds of slack, so I would make sure the partial-result report is solid and maybe cap retries more tightly.
Why not use a fixed thread pool of 20 platform threads instead?
That also limits concurrency to 20, and for this one job it works. The difference shows up when the limit and the threads are separate concerns: with virtual threads, the waiting tasks cost almost nothing, the semaphore states the provider's limit directly, and we can reuse the same pattern when other limits are added, such as a rate limit or a second provider, without resizing thread pools. With platform threads, a pool sized to the provider limit also has to consider memory per thread and cannot easily share threads with other kinds of work.
7Conclusion
In this answer, we first did the arithmetic: 5,000 calls at 200 ms with 20 in flight take about 50 seconds, inside the 2-minute deadline but with limited slack. Virtual threads make one blocking task per id cheap, a Semaphore(20) enforces the provider's concurrency limit exactly, and invokeAll with a 2-minute timeout cancels whatever has not finished, so we can report successes, failures and timeouts separately. Per-call HTTP timeouts and bounded retries that also pass through the semaphore protect the limit and the deadline, and StructuredTaskScope is a cleaner model that is still in preview in Java 25.
Open with
I would start with the arithmetic. Twenty concurrent calls of about 200 milliseconds give 100 calls per second, so 5,000 calls take about 50 seconds, which fits in two minutes with some slack but not a lot.
Then, if they want more
Since these are blocking HTTP calls, I would use a virtual-thread-per-task executor, one task per product id, and a Semaphore with 20 permits that each task acquires right before the call and releases in a finally block. Virtual threads make the waiting cheap, and the semaphore expresses the provider limit exactly.
Each request gets its own connect and request timeouts, a few seconds, so one hung connection cannot hold a permit for the whole job. For the deadline, I call invokeAll with a timeout of two minutes.
It returns the futures in task order, and anything not finished by then is cancelled, so I go through the futures and use Future.state to sort them into successes, failures with their exception, and cancelled ones, which I report as timed out. The executor is in try-with-resources, so closing it waits for the cancelled tasks to stop.
For transient errors like 503, I retry once or twice with backoff and jitter, but each retry goes through the semaphore so I never exceed 20, and I do not start a retry if the deadline is too close.
I would also mention StructuredTaskScope, which gives cleaner cancellation of subtasks, but in Java 25 it is still a preview API, so for production I would stay with the executor.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25, Java 19, Java 21
- 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 "You must call an external pricing API for 5,000 product ids. The provider allows at most...": https://scrivio-interview-library.netlify.app/java/coding-problems/3b230eb8ae/