Scrivio Interview library
InternalsIntermediate6 min read · updated 12 November 2026

How does asynchronous request processing work in the Servlet API, and how does Spring MVC use it with DeferredResult?

In the Servlet API, a request calls request.startAsync() to get an AsyncContext; the container thread then returns to its pool while the connection stays open, and another thread later writes the response and calls complete() or dispatch(). Spring MVC builds on this: when a controller returns DeferredResult or Callable, Spring starts async processing, and when the result is set it dispatches the request back into the container to write the response. Every filter and servlet in the chain must be marked asyncSupported, and timeouts must be handled.

Why this question is asked

A classic servlet container holds one thread for each request from start to finish. If the request waits five seconds for a slow downstream call or a long poll, that thread does nothing useful for five seconds, and with a pool of 200 threads we run out quickly. Asynchronous request processing, added in Servlet 3.0, lets the request wait without holding a container thread. Interviewers ask about it because DeferredResult and Callable appear in many Spring codebases and the mechanics explain odd behaviour such as filters running twice. In this answer, we will recap the thread-per-request model, follow startAsync step by step, see what asyncSupported means, and then look at how Spring MVC uses this for DeferredResult and Callable, including timeouts.

1A Quick Recap of Thread-per-Request

In the classic model, the container takes a thread from its request pool (Tomcat's default maximum is 200), calls our servlet's service() method on that thread, and when service() returns it sends the response and returns the thread to the pool. The thread is busy for the whole request, even while our code is only waiting.

Async processing breaks that link. The request and its connection can stay open after service() returns, and the response can be finished later by any thread.

2How startAsync() Works

Inside the servlet we call request.startAsync(). It returns an AsyncContext, an object that represents the request and response which are now in async mode. We hand the AsyncContext to some other component and return from service(). The reason this helps is that the container sees async mode is on, so it does not complete the response; it simply returns its thread to the pool.

Later, another thread, perhaps from our own executor or a callback from a message listener, writes to the response and calls asyncContext.complete(), which finishes the response and closes the request. Alternatively it calls asyncContext.dispatch(), which sends the request back into the container to be processed again on a container thread, typically to render a view or let a framework write the result.

Java
@WebServlet(urlPatterns = "/report", asyncSupported = true)
public class ReportServlet extends HttpServlet {
private final ExecutorService pool = Executors.newFixedThreadPool(10);
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
AsyncContext ctx = req.startAsync();
ctx.setTimeout(10_000); // 10 seconds
pool.submit(() -> {
String body = slowService.build(); // runs on pool thread
ctx.getResponse().getWriter().write(body);
ctx.complete(); // response sent now
});
} // container thread freed here
}

Notice that the container thread is back in the pool before slowService.build() even starts. The open connection still uses a socket and some memory, but not a thread from the request pool.

3Why the Whole Chain Must Be asyncSupported

A request passes through every filter before it reaches the servlet. If any filter or the servlet is not marked asyncSupported, the container refuses startAsync() and throws IllegalStateException. The reason is safety: an older filter may do work after chain.doFilter() returns, such as closing a resource or committing a transaction, assuming the response is finished. In async mode the response is not finished at that point, so that filter would break.

Spring Boot registers its own filters and the DispatcherServlet with async support on. Custom filters registered through FilterRegistrationBean or @WebFilter must opt in, and they should be written to cope with a later async dispatch, which is why Spring's OncePerRequestFilter has a shouldNotFilterAsyncDispatch() hook.

4How Spring MVC Uses It for DeferredResult and Callable

In Spring MVC we rarely call startAsync() ourselves. If a controller returns a Callable, Spring calls startAsync(), submits the Callable to an AsyncTaskExecutor, and releases the container thread. When the Callable returns, Spring stores the value and calls dispatch(). The request re-enters the DispatcherServlet on a container thread, and Spring handles the stored value as if the controller had returned it directly: it converts it to JSON or renders a view.

DeferredResult is for results produced by some other thread we do not control, such as a message listener or a long-poll notification. The controller returns an empty DeferredResult and keeps a reference. When the result arrives, some code calls setResult(), and Spring dispatches back in the same way.

Java
@GetMapping("/orders/{id}/status")
public DeferredResult<String> waitForStatus(@PathVariable long id) {
DeferredResult<String> result = new DeferredResult<>(30_000L); // 30 s timeout
result.onTimeout(() -> result.setErrorResult(
ResponseEntity.status(HttpStatus.NO_CONTENT).build()));
waiters.put(id, result); // controller returns, thread freed
return result;
}
// Later, on a Kafka listener thread:
void onStatusChange(long id, String status) {
DeferredResult<String> r = waiters.remove(id);
if (r != null) r.setResult(status); // Spring dispatches; client gets "SHIPPED"
}
Step throughDeferredResult lifecycle
ClientContainer threadDispatcherServletListener thread
GET /orders/7/status
dispatch to controller
controller returns DeferredResult; startAsync()
return; thread back to pool
setResult("SHIPPED")
asyncContext.dispatch()
second pass writes "SHIPPED"
200 OK SHIPPED

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

The request passes through the DispatcherServlet twice, on two different container threads.

5Handling Timeouts

An async request that is never completed would hang forever, so the container applies a timeout. In Spring Boot the default can be set with spring.mvc.async.request-timeout, and each DeferredResult can have its own. When the timeout fires, Spring calls the onTimeout callback; if we set a result there, that is what the client receives. If we do nothing, Spring raises AsyncRequestTimeoutException, which by default becomes a 503 Service Unavailable response.

We must also clean up. In the example above, the waiters map would hold timed-out entries forever, so onTimeout and onCompletion should remove the entry. And the Callable executor needs its own sized thread pool; Spring Boot provides a task executor, but relying on a simple default executor in production is a common mistake.

6Follow-up questions

Why does my filter run twice for an async request?

Because the request goes through the filter chain once for the original request and again for the async dispatch. Filters see DispatcherType.ASYNC on the second pass. OncePerRequestFilter skips the async dispatch by default, but plain filters registered for ASYNC will run again.

Does async processing make a single request faster?

No. It does not speed up the work; it frees the container thread while the request waits. The benefit is capacity: many slow or long-held requests no longer exhaust the request thread pool.

What is the difference between Callable and DeferredResult?

With a Callable, Spring runs our code on its own executor thread, so it suits blocking work we want to move off the container thread. With DeferredResult, Spring runs nothing; the result is supplied later by some other thread, so it suits event-driven cases such as long polling or waiting for a message.

7Conclusion

In this answer, we saw that startAsync() gives an AsyncContext and lets the container thread return to the pool while the connection stays open, and that another thread later finishes with complete() or dispatch(). Every filter and servlet must be asyncSupported because they must cope with a response that is not finished when the chain returns. Spring MVC wraps all of this in Callable and DeferredResult, dispatching back into the DispatcherServlet when the value is ready, and timeouts need explicit handling and cleanup.

What to say in the interviewAbout 80 seconds aloud

Open with

In the Servlet API, async processing starts when the code calls request.startAsync(). That returns an AsyncContext and puts the request in async mode, so when the servlet returns, the container does not send the response; it just gives its thread back to the pool while the connection stays open.

Then, if they want more

Later another thread writes the response and calls complete(), or calls dispatch() to send the request back into the container for a second pass. For that to be allowed, every filter and the servlet in the chain must be marked asyncSupported, because older filters may assume the response is done when doFilter returns. Spring MVC hides this.

If a controller returns a Callable, Spring calls startAsync, runs the Callable on its task executor, then dispatches back and handles the value normally. If it returns a DeferredResult, Spring waits until some other thread, say a Kafka listener, calls setResult, and then dispatches.

I always set a timeout and an onTimeout handler, otherwise the client gets a 503 from AsyncRequestTimeoutException, and I clean up any map of waiting results in onCompletion. The point of all this is capacity, not speed: slow requests stop holding request threads.

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.
Official documentation
Jakarta EE specifications
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 "How does asynchronous request processing work in the Servlet API, and how does Spring...": https://scrivio-interview-library.netlify.app/java/servlets/2ecb6d2613/