Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A page aggregates data from 20 services with CompletableFuture.allOf. When one service fails quickly, the user still waits for the slowest service before seeing an error. How would you make it fail fast, and does cancelling the others stop their work?

allOf completes only when every input has completed, even if one failed early, so the user waits for the slowest service. To fail fast, we attach a handler to each input that completes a shared result future exceptionally on the first failure, and then cancel the rest. But CompletableFuture.cancel does not interrupt the running work, so to really stop it we cancel at the source, for example by aborting the HTTP requests, or we use structured concurrency where it is available. We should also decide which parts are optional and return a partial page for them.

Why this question is asked

Aggregation pages are where small latency problems turn into big ones. With 20 dependencies, something is almost always slow or broken, and how we combine the calls decides whether users wait 300 ms for an error or 8 seconds. Interviewers ask this scenario to see whether we know the exact semantics of allOf and whether we understand that cancelling a future is not the same as stopping work. In this answer, we will reproduce the slow failure, build a fail-fast combiner, look at what cancellation actually does, stop the work at its source, and finally handle optional parts with partial pages.

1Reproducing the Slow Failure

allOf returns a future that completes when all of its inputs have completed. If any input completes exceptionally, the combined future completes exceptionally too, but only at the moment the last input finishes. It does not short-circuit.

Java
List<CompletableFuture<Section>> parts = services.stream()
.map(s -> CompletableFuture.supplyAsync(() -> s.load(userId), io))
.toList();
CompletableFuture<Void> all = CompletableFuture.allOf(parts.toArray(CompletableFuture[]::new));
// recommendations fails after 50 ms with a 503
// the slowest service, search history, answers after 6 s
all.join(); // throws CompletionException, but only after about 6 s

Notice that the error was known after 50 ms. The user still waited six seconds, because allOf waited for every other service before reporting it.

2Building a Fail-Fast Combiner

We create our own result future and let every input complete it. Each input gets an exceptionally handler, which runs only on failure, and the first failure completes the result exceptionally. Success still goes through allOf, which completes once all inputs succeeded.

Java
static <T> CompletableFuture<List<T>> allOrFirstFailure(List<CompletableFuture<T>> parts) {
CompletableFuture<List<T>> result = new CompletableFuture<>();
for (CompletableFuture<T> p : parts) {
p.exceptionally(ex -> { result.completeExceptionally(ex); return null; }); // first failure wins
}
CompletableFuture.allOf(parts.toArray(CompletableFuture[]::new))
.thenRun(() -> result.complete(parts.stream().map(CompletableFuture::join).toList()));
result.whenComplete((v, ex) -> {
if (ex != null) parts.forEach(p -> p.cancel(true)); // stop waiting on the others
});
return result;
}
allOrFirstFailure(parts).join(); // throws after about 50 ms, cause: the 503 from recommendations
Step throughFail fast across 20 calls
  1. Start all 20 callseach has an exceptionally handler
  2. First failure?
    YesComplete the result exceptionallyNoKeep waiting
  3. Cancel the other futureswaiters stop; the work does not
  4. Cancel at the sourceabort HTTP requests, interrupt tasks
  5. Return the error pageafter about 50 ms instead of 6 s

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

Notice that completeExceptionally only takes effect once; later failures find the result already completed and do nothing, so the first failure is the one reported. The whenComplete at the end runs once the result is decided, and on failure it cancels the remaining inputs. That frees anyone waiting on them, but it does not do what the name suggests, as the next section shows.

3Does Cancelling the Others Stop Their Work?

No. CompletableFuture.cancel(true) completes the future with a CancellationException and ignores the mayInterruptIfRunning flag. The future has no link to the thread or the HTTP request that is producing its value. So the 19 other calls keep running: threads stay busy, connections stay open, and the downstream services keep working on answers nobody will read.

For one page view this waste is small. But when a dependency fails, it usually fails for every request, and then every page view leaves 19 orphaned calls behind. Under a traffic peak that can double the load on healthy services exactly when we can least afford it.

4Stopping the Work at Its Source

To stop the work, cancellation must reach the thing doing it. For HTTP calls, that means aborting the request in the client, so the connection is closed or returned and the remote side may notice. We can link each future to its request so that cancelling the future aborts the request; how a cancel is honoured depends on the client, so check its documentation. For our own blocking code on threads, the task must react to interrupts, which CompletableFuture never sends.

Structured concurrency solves this more cleanly. A StructuredTaskScope forks subtasks on their own threads, usually virtual threads, and when one fails under the default policy, the scope cancels the others by interrupting their threads, and join returns with the failure. It is still a preview feature in Java 25 and its API has changed between previews, so check its status in your JDK before using it in production.

Java
// Java 25 preview API (compile with --enable-preview); check your JDK version
try (var scope = StructuredTaskScope.open()) { // fails on the first failed subtask
List<StructuredTaskScope.Subtask<Section>> tasks = services.stream()
.map(s -> scope.fork(() -> s.load(userId))) // each on a virtual thread
.toList();
scope.join(); // throws as soon as one fails; others are interrupted
return new Page(tasks.stream().map(StructuredTaskScope.Subtask::get).toList());
}

Notice that the interruption only helps if the client call responds to it, which blocking JDK socket calls on virtual threads generally do. That is still a better starting point than CompletableFuture, which never interrupts anything.

5Deciding Which Parts Are Optional

Failing fast is right for parts the page cannot work without, such as the account summary. But most of the 20 sections are probably optional: recommendations, recently viewed items, promotions. For those, failing the whole page is the wrong answer. We give each optional future its own timeout and fallback, so it can never fail the combination, and we fail fast only on the essential ones.

Java
CompletableFuture<Section> recs = recommendations.loadAsync(userId)
.completeOnTimeout(Section.hidden("recommendations"), 300, MILLISECONDS)
.exceptionally(ex -> Section.hidden("recommendations")); // never fails the page
CompletableFuture<List<Section>> essential = allOrFirstFailure(List.of(account, orders));

So the page shows within its latency budget even when an optional service is slow or down, and only a failure of an essential service gives the user an error, quickly.

6Follow-up questions

Why not wrap the whole allOf in orTimeout instead?

It caps the wait, which helps, but it fails the page after the timeout even when only an optional part was slow, and it still does not fail fast on an early error. Per-part timeouts with fallbacks plus a fail-fast combiner for essential parts give a much better result.

Could we use anyOf to detect the first failure?

Not directly, because anyOf completes on the first completion of any kind, success or failure. With 20 inputs, the first completion is usually a success. The exceptionally-handler approach reacts only to failures.

Does the orphaned work matter if the services are idempotent reads?

It matters for capacity rather than correctness. Orphaned calls still use threads, connections and downstream CPU. When a dependency is failing for everyone, that waste is multiplied by every request, so cancelling at the source protects the healthy services.

7Conclusion

In this answer, we saw that allOf waits for every input before reporting a failure, so one fast error still costs the user the slowest call. A fail-fast combiner completes a shared result future from each input's exceptionally handler and then cancels the rest, but CompletableFuture.cancel only stops the waiting, not the work. To stop the work we cancel at the source, by aborting HTTP requests or using structured concurrency where it is available in our JDK. And for optional sections, per-part timeouts and fallbacks give a partial page instead of an error.

What to say in the interviewAbout 80 seconds aloud

Open with

The reason is that allOf completes only when every input has completed. A failure early on does make the combined future fail, but only once the slowest of the 20 calls has finished, so the user waits for it.

Then, if they want more

To fail fast, I create my own result future, attach an exceptionally handler to each input that calls completeExceptionally on the result, and complete the result normally through allOf when everything succeeds. The first failure wins, and then I cancel the remaining futures. But that cancel does not stop their work.

CompletableFuture.cancel just completes the future with CancellationException and ignores the interrupt flag, because the future has no link to the thread or request behind it, so the other 19 calls keep using threads, connections and downstream capacity.

To really stop them I cancel at the source, by aborting the HTTP requests through the client, or I would use structured concurrency, which interrupts sibling subtasks when one fails, but it is still preview in Java 25, so I would check its status first.

Finally, most of those 20 sections are probably optional, so I would give each optional part its own timeout and fallback, return a partial page, and fail fast only on the essential parts.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
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 page aggregates data from 20 services with CompletableFuture.allOf. When one service...": https://scrivio-interview-library.netlify.app/java/completable-future/708f145add/