Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a Spring MVC endpoint that returns a report generated in about 10 seconds without holding the servlet thread, using Callable or DeferredResult, and configure the async timeout and the executor. What does the client see on timeout?

We return Callable<Report>, which Spring MVC runs on its async task executor while the servlet thread goes back to the pool, or DeferredResult<Report>, which another thread completes with setResult. We configure the timeout and a bounded executor in WebMvcConfigurer.configureAsyncSupport, or set spring.mvc.async.request-timeout in Spring Boot. If the report is not ready in time, Spring raises AsyncRequestTimeoutException and the client receives 503 Service Unavailable by default, unless a DeferredResult supplies a timeout result.

Why this question is asked

A report that takes 10 seconds to build is common: a big query, a PDF render, a call to a slow partner system. If the controller simply blocks, each request holds one of the container's worker threads for those 10 seconds, and 200 users asking for reports at once can freeze the whole service. Async return types let the request wait without holding that thread. Interviewers ask for this to see whether we can write it, configure it safely and explain what happens at the edges. In this answer, we will see the blocking version and its problem, write the Callable version, configure the executor and timeout, write the DeferredResult version, look at what the client sees on timeout, and finish with how this fits streaming responses.

1The Blocking Version and Its Problem

Here is the straightforward version. It works, but it holds a Tomcat worker thread for the whole 10 seconds.

Java
@GetMapping("/reports/{id}")
Report report(@PathVariable long id) {
return reports.generate(id); // about 10 s; the worker thread waits the whole time
}
// Tomcat has 200 worker threads by default (server.tomcat.threads.max)
// 200 concurrent report requests -> every other endpoint queues behind them

Notice that the problem is not this request's speed; the user waits 10 seconds either way. The problem is that a scarce shared resource, the container's worker threads, is tied up, so unrelated fast requests suffer.

2Returning a Callable

With Callable, we hand Spring the work instead of doing it. Spring MVC starts servlet async processing, submits the Callable to its async task executor and releases the worker thread. When the Callable returns, Spring dispatches the request back into DispatcherServlet on a container thread, which writes the Report as JSON.

Java
@GetMapping("/reports/{id}")
Callable<Report> report(@PathVariable long id) {
log.info("accepted on {}", Thread.currentThread().getName());
return () -> {
log.info("generating on {}", Thread.currentThread().getName());
return reports.generate(id); // about 10 s, on the executor thread
};
}
// accepted on http-nio-8080-exec-4 (released immediately)
// generating on report-1 (our executor, see below)
// client receives 200 {"id":7,"rows":1520} after about 10 s
Step throughCallable: the worker thread is released
ClientTomcat threadSpring MVCReport executor
GET /reports/7
controller returns Callable
submit Callable
back to the pool
generate report, 10 s
Report ready
async dispatch on a container thread
200 with the report JSON

8 messages in order. Play them, or step through them one at a time.

Callable is the simplest async option because Spring runs the code for us. The catch is that it still occupies a thread, just a different one, from the async executor. So that executor's size becomes the real limit on concurrent reports, and it must be configured deliberately.

3Configuring the Executor and the Timeout

We configure both in configureAsyncSupport. The executor is a bounded ThreadPoolTaskExecutor, so at most a known number of reports are generated at once and the rest wait in a bounded queue. The default timeout is set slightly above the expected 10 seconds, here 15.

Java
@Configuration
class AsyncConfig implements WebMvcConfigurer {
@Bean
ThreadPoolTaskExecutor reportExecutor() {
var ex = new ThreadPoolTaskExecutor();
ex.setCorePoolSize(8);
ex.setMaxPoolSize(8); // at most 8 reports generated at once
ex.setQueueCapacity(50); // the next 50 wait; beyond that, rejected
ex.setThreadNamePrefix("report-");
ex.initialize();
return ex;
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(reportExecutor());
configurer.setDefaultTimeout(15_000); // milliseconds
}
}
# Or, for the timeout only, in application.properties (Spring Boot):
# spring.mvc.async.request-timeout=15s

Why bother with the executor? Without configuration, what Spring uses depends on the version. Recent Spring Boot versions wire MVC to the application task executor that Boot auto-configures, while plain Spring MVC, and older setups, used SimpleAsyncTaskExecutor, which creates a new thread per task with no limit, and Spring even logs a warning about it. Check your version, but in either case a dedicated, bounded executor for slow reports keeps them from starving other async work.

If the queue fills up, the executor rejects the task, and the request fails quickly instead of piling up threads. That is a deliberate choice: an honest error under overload is better than a service that runs out of memory.

4The DeferredResult Version

DeferredResult suits cases where the result is produced by something other than our own code on our own thread: a message from a queue, a callback from a client library, or a job that another component runs. Spring does not run anything for us; it waits until some thread calls setResult or setErrorResult.

Java
@GetMapping("/reports/{id}")
DeferredResult<Report> report(@PathVariable long id) {
var result = new DeferredResult<Report>(15_000L, Report.notReady(id)); // timeout and timeout result
reportExecutor.submit(() -> {
try {
result.setResult(reports.generate(id)); // completes the request
} catch (Exception e) {
result.setErrorResult(e); // goes to @ExceptionHandler / ControllerAdvice
}
});
result.onTimeout(() -> log.warn("report {} timed out", id));
return result;
}
// ready within 15 s -> 200 {"id":7,"rows":1520}
// not ready -> 200 {"id":7,"status":"NOT_READY"} (the timeout result)

Notice the catch block. If the background code throws and nobody calls setErrorResult, the request is never completed and hangs until the timeout. Every code path must complete the DeferredResult.

5What the Client Sees on Timeout

If a Callable takes longer than the timeout, or a DeferredResult without a timeout result is not completed in time, Spring raises AsyncRequestTimeoutException. Spring's default exception handling maps it to 503 Service Unavailable, and with ProblemDetail support enabled the body is a standard problem document. An @ExceptionHandler for AsyncRequestTimeoutException can choose another status or body, but 503, or 202 Accepted with a link to poll later, are the honest answers.

There is one more subtlety: the timeout ends the HTTP request, not necessarily the work. A report Callable may keep running on its executor thread after the client has received the 503. For expensive work, the code should check for interruption or a cancellation flag, or, better, the design should move to an asynchronous job: POST returns 202 with a job id, and the client polls or is notified.

Java
// 16 s report with a 15 s timeout:
// GET /reports/9 -> 503 Service Unavailable
// {"type":"about:blank","title":"Service Unavailable","status":503,"instance":"/reports/9"} (ProblemDetail enabled)

6Filters and Interceptors on the Async Dispatch

Because the result is written on a second dispatch, the request passes through the filter chain and DispatcherServlet twice. Filters registered for async dispatches run again, which is why OncePerRequestFilter skips async dispatches by default. Interceptors that implement AsyncHandlerInterceptor get afterConcurrentHandlingStarted on the first thread, instead of postHandle and afterCompletion, and the full callbacks run on the async dispatch when the result is written. Code that relies on ThreadLocal values, such as the logging MDC, must propagate them to the executor thread, for example with a TaskDecorator on the executor.

7Follow-up questions

How does SseEmitter or ResponseBodyEmitter fit this model?

They use the same servlet async machinery, but instead of one result they send many. The controller returns an SseEmitter, the worker thread is released, and any thread can call emitter.send(...) repeatedly; each call writes and flushes a chunk, or an event for server-sent events, to the open response. emitter.complete() ends the response, and completeWithError ends it with an error. The same timeout applies, set per emitter in its constructor or by the global async timeout, so long-lived streams need a long or disabled timeout and a heartbeat.

When would you choose virtual threads instead?

If the service runs on Java 21 or later with spring.threads.virtual.enabled=true, the blocking version no longer ties up a scarce platform thread, so for simple cases the plain controller is enough. We would still want a limit on concurrent report generation, now as a semaphore or bulkhead, because the report itself consumes CPU and database connections.

Why not return CompletableFuture instead?

That works too, and Spring treats it like a DeferredResult. It is convenient when the service layer already returns futures. The same rules apply: run it on a bounded executor rather than the common pool, and make sure every path completes the future.

8Conclusion

In this answer, we replaced a controller that held a worker thread for 10 seconds with a Callable, which Spring runs on its async executor, and a DeferredResult, which our own code completes. We configured a bounded ThreadPoolTaskExecutor and a 15 second timeout in configureAsyncSupport, or with spring.mvc.async.request-timeout, and noted that the default executor depends on the version. On timeout the client receives 503 from AsyncRequestTimeoutException unless a timeout result is set, and the background work may continue, so long jobs are better modelled as asynchronous jobs.

What to say in the interviewAbout 90 seconds aloud

Open with

The goal is to free the Tomcat worker thread during those 10 seconds. The simplest way is returning Callable<Report>: Spring starts servlet async processing, runs the Callable on its async task executor, releases the worker thread, and when the Callable returns it dispatches the request again and writes the JSON.

Then, if they want more

The alternative is DeferredResult<Report>, where Spring runs nothing; my own code, a callback or a listener, calls setResult later, and it must also call setErrorResult on failure or the request hangs until the timeout.

I'd configure it in a WebMvcConfigurer, in configureAsyncSupport: setTaskExecutor with a bounded ThreadPoolTaskExecutor, say eight threads and a queue of fifty, and setDefaultTimeout of fifteen seconds; in Boot the timeout can also be spring.mvc.async.request-timeout. I'd always set the executor, because the default depends on the version.

Recent Boot uses the application task executor, but plain Spring used SimpleAsyncTaskExecutor, which creates a thread per task. On timeout, Spring throws AsyncRequestTimeoutException, which maps to 503 Service Unavailable by default, or a ProblemDetail body if that's on; with DeferredResult I can pass a timeout result instead, like a NOT_READY status.

I'd mention that the work may keep running after the timeout, so for long reports a 202 with a job id is often better. Also, the async dispatch runs filters and interceptors again, and AsyncHandlerInterceptor gets afterConcurrentHandlingStarted on the first thread. SseEmitter uses the same mechanism, just sending many chunks before complete.

About this answer

Last updated
12 November 2026
Versions it names
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 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 "Write a Spring MVC endpoint that returns a report generated in about 10 seconds without...": https://scrivio-interview-library.netlify.app/spring-boot/mvc-architecture/23c18f1f03/