Video in progress
In an aggregator endpoint that assembles price, stock and reviews for a product page from different services, how do you handle timeouts and partial responses?
I make the calls in parallel and give the whole page one overall deadline. I mark each dependency as required or optional: if the price doesn't arrive it's an error, if the reviews don't arrive I return the response without them and say in the response which part is missing.
📖 Answer
If you call them one after another, latency adds up: 80 + 60 + 200 = 340 ms. In parallel it is the slowest one, about 200 ms. But the slowest sometimes takes 3 seconds, so you need a limit on every call and on the whole page.
A simple version with Java 21 virtual threads:
public ProductPage page(long id) throws InterruptedException {
Instant deadline = Instant.now().plusMillis(300);
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Price> price = executor.submit(() -> pricing.price(id));
Future<Stock> stock = executor.submit(() -> inventory.stock(id));
Future<List<Review>> reviews = executor.submit(() -> reviewsClient.top(id));
Price p = getOrFail(price, deadline); // required
Stock s = getOrDefault(stock, deadline, Stock.UNKNOWN);
List<Review> r = getOrDefault(reviews, deadline, List.of());
return new ProductPage(p, s, r);
}
}
Inside getOrDefault there is future.get(remaining time), and on a timeout or error it calls future.cancel(true) and returns the default. Canceling is a must: when try-with-resources closes the executor it waits for all tasks to finish, so a slow call that wasn't canceled holds the response up. The waits are computed from one shared deadline, not from 300 ms each in sequence. In Java 25 structured concurrency is still a preview, but it is designed for exactly this problem.
The response shape:
{"price": {...}, "stock": null, "reviews": [], "degraded": ["stock", "reviews"]}
The frontend looks at the degraded list and shows "stock unknown for now", and the page still opens.
Which part is required is a business decision. Can you show a product page without a price? Usually no. Without reviews, sure.
And a metric: the share of "degraded" responses per dependency. Otherwise nobody notices that the reviews service has been down for a week.
Sign up to mark studied questions and save your progress.