Video in progress

Strong Middle 🌱 Spring

When do you use DeferredResult, Callable and SseEmitter in Spring MVC for long-running requests?

They work in servlet async mode: after the controller method returns, the Tomcat thread is freed and the response is written later from another thread. Callable hands the work to a Spring executor, DeferredResult has its result filled in by an external event, and SseEmitter streams several events one after another.

📖 Answer

In classic MVC the Tomcat thread is busy until the request finishes. With long-polling or a 30-second report, those threads run out fast.

@GetMapping("/api/payments/{id}/status")
DeferredResult<PaymentStatus> waitStatus(@PathVariable String id) {
    DeferredResult<PaymentStatus> result = new DeferredResult<>(25_000L, PaymentStatus.PENDING);
    waiters.register(id, result);   // setResult is called when the webhook arrives from the payment provider
    return result;                  // the Tomcat thread is freed immediately
}

@GetMapping(path = "/api/import/{id}/progress", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
SseEmitter progress(@PathVariable long id) {
    SseEmitter emitter = new SseEmitter(0L); // no timeout: be careful
    importService.subscribe(id, emitter);    // emitter.send(...) at every 5%
    return emitter;
}

What to choose when:

  • Callable: moving heavy computation to another pool. But it doesn't save resources, it only relocates them; configure the executor yourself (spring.mvc.async and AsyncTaskExecutor), otherwise Boot warns you.
  • DeferredResult: the result comes from an external event: a Kafka message, a webhook, another request.
  • SseEmitter: progress bars, notifications; the browser receives them with EventSource.

Practical traps:

  • in async, ThreadLocal (MDC, SecurityContext) doesn't carry over to the new thread. Spring Security handles this for async, but you pass MDC yourself;
  • if you don't clean up the subscription in the onTimeout, onCompletion and onError callbacks, you get a memory leak;
  • a reverse proxy (nginx) may buffer SSE, so you'll need X-Accel-Buffering: no.

If Java 21 virtual threads are enabled, ordinary blocking code is enough in many cases, and you can keep async only for real push or long-polling.