How does Spring MVC (servlet stack) run a Kotlin suspend or Flow-returning controller method, and does it scale like WebFlux?
answer
- still the servlet stack
- Mono under the hood
- unconfined: caller's thread first
- bridged to a DeferredResult
- Flow collected unless streaming type
basics
~20 sSpring MVC invokes a suspend handler as a Mono on an unconfined dispatcher and treats it as a DeferredResult async request, freeing the servlet thread only while the coroutine is truly suspended; blocking calls inside still hold a thread.
solid answer
~50 sSpring MVC supports `suspend` and `Flow` handlers when `kotlinx-coroutines-reactor` is on the classpath. `InvocableHandlerMethod` detects the suspending function and calls `CoroutinesUtils.invokeSuspendingFunction`, which wraps it in a `Mono` on `Dispatchers.Unconfined` (a `Flux` when it returns a `Flow`). MVC then handles that like any reactive return value: for an ordinary JSON response, `ReactiveTypeHandler` subscribes, bridges it to a `DeferredResult` and starts async processing through `WebAsyncManager`. Because the dispatcher is unconfined, the body runs on the servlet thread until its first real suspension, and afterwards on whichever thread resumes it. So the servlet thread is freed only while a genuinely non-blocking call is in flight; a blocking `RestClient` or JDBC call still pins a thread, possibly the HTTP client's I/O thread. A `Flow` of objects is collected into a list unless the client asks for a streaming type. It is not WebFlux: any gain depends on the calls being non-blocking.
code
kotlin · 26 linesimport org.springframework.jdbc.core.simple.JdbcClient
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.awaitBody
data class Price(val amount: Long)
data class Order(val id: Long, val sku: String)
data class OrderView(val order: Order, val price: Price)
@RestController
class OrderController(private val webClient: WebClient, private val jdbcClient: JdbcClient) {
@GetMapping("/orders/{id}")
suspend fun order(@PathVariable id: Long): OrderView {
// Runs on the servlet thread until this call really suspends.
val price = webClient.get().uri("/prices/{id}", id).retrieve().awaitBody<Price>()
// Typically resumed on the HTTP client's I/O thread: this blocking JDBC call now blocks it.
val order = jdbcClient.sql("select id, sku from orders where id = ?")
.param(id)
.query(Order::class.java)
.single()
return OrderView(order, price)
}
}go deeper
Recall that Spring MVC accepts suspend controller methods and Flow return values, and that it is still the servlet stack, not WebFlux.
Explain the path: the suspend call becomes a Mono on an unconfined dispatcher, MVC bridges it to a DeferredResult async request, and the servlet thread is freed only during a real suspension.
Spot the production trap: blocking JDBC after a non-blocking await runs on the client's I/O thread. Show how you would find and move such calls, and when async adds no capacity at all.
Frame the choice as one stack decision: plain blocking MVC, possibly on virtual threads, versus coroutines with a truly non-blocking path, and what each costs the team to keep correct.
## What Spring MVC actually supports **Spring MVC** is the servlet-based web stack: each request arrives on a thread from the servlet container's pool (Tomcat or Jetty, for example). Since Spring added Kotlin coroutine support, an annotated `@Controller` method in Spring MVC may be declared `suspend`, may return a Kotlin `Flow<T>`, or may return a `Deferred<T>`. The reference documentation lists "suspending function support in Spring MVC and WebFlux annotated `@Controller`", and coroutine support is enabled when both `kotlinx-coroutines-core` and `kotlinx-coroutines-reactor` are on the classpath. A **suspend function** is a Kotlin function that can pause at a suspension point (for example while awaiting a network response) without blocking the thread it runs on, and resume later. The key word is *can*: it only releases its thread when it calls something that genuinely suspends. The important point for an interview is that the request still goes through the servlet pipeline. Nothing about the server becomes reactive; Spring MVC simply adapts the coroutine onto the async request processing it already has. ## How the call is dispatched 1. `InvocableHandlerMethod` checks whether the method is a Kotlin suspending function and, if so, calls `CoroutinesUtils.invokeSuspendingFunction`. 2. That utility wraps the call in a cold `Mono` using the `mono` builder from `kotlinx-coroutines-reactor`, on `Dispatchers.Unconfined` (augmented with a context-propagation element when Reactor's automatic context propagation is enabled). A `suspend` function whose return type is a `Flow` becomes a `Flux` instead. 3. The handler's actual return value is now a `Mono` or `Flux`, so the reactive return-value handler takes it and delegates to `ReactiveTypeHandler`. 4. For a non-streaming response, `ReactiveTypeHandler` creates a `DeferredResult`, subscribes to the publisher, and then calls `WebAsyncManager.startDeferredResultProcessing`, which starts servlet async processing so the container thread can return to the pool. 5. When the coroutine finishes, the subscriber sets the `DeferredResult`, and the request is dispatched back into the container to write the response through the normal message converters. ## Which thread runs your code The order of steps 4 and 5 matters, because the coroutine runs on an **unconfined dispatcher**: it starts in the caller's thread and, after a suspension, continues in whichever thread resumed it. - **Before the first real suspension** the body runs on the servlet thread, inside the `subscribe` call, before async processing has even started. - **During a genuine suspension** (a non-blocking call in flight) the subscribe call returns, async processing starts, and the servlet thread is freed. This is the only window in which the endpoint saves a container thread. - **After resumption** the body runs on the thread that completed the awaited operation, typically one of a non-blocking HTTP client's I/O threads. - **If the body never suspends**, it completes on the servlet thread, the `DeferredResult` is already set when async processing starts, and the request is dispatched straight back: async overhead with no gain. - **No executor is involved** on the non-streaming path. Unlike a returned `Callable`, nothing is submitted to the MVC async task executor; the coroutine's own suspensions decide where it runs. ## The scenario: a slow HTTP API plus JDBC A Kotlin team adds `suspend` to an MVC endpoint that calls a slow HTTP API and a JDBC repository, expecting WebFlux-style scalability. What they get depends on each call: | Call inside the suspend body | What happens to threads | |---|---| | Blocking `RestClient` call | Never suspends; holds the servlet thread for the whole wait, as plain MVC would | | `WebClient` with the `awaitBody` extension | Truly suspends; the servlet thread is released while the response is in flight | | JDBC query before any suspension | Holds the servlet thread | | JDBC query after a `WebClient` suspension | Typically runs on the client's I/O thread and blocks it, stalling other connections sharing that thread | The last row is the trap: the endpoint becomes *less* healthy than plain MVC, because a blocking driver call now sits on a thread that was meant never to block. JDBC is a blocking API; marking the caller `suspend` changes nothing about that. ## Flow return values When a handler returns a `Flow<T>`, the decision is made mainly by the requested media type, and partly by the element type: - With an ordinary type such as `application/json`, the elements are **collected into a list** and written as one JSON array once the `Flow` completes. - With `text/event-stream` or newline-delimited JSON, the elements are **streamed** through an emitter as they are produced (the streaming mechanics belong to the SSE topic). - A `Flow` of `CharSequence` elements is streamed as `text/plain` even without a streaming media type. ## What to do instead - If the dependencies are blocking, keep plain blocking MVC (optionally on virtual threads with `spring.threads.virtual.enabled`) rather than adding `suspend` for appearance. - If you keep `suspend`, make the slow call genuinely non-blocking and move every blocking call off the resuming thread with an explicit context switch to a bounded pool. - If you need WebFlux-style scaling, the whole path must be non-blocking: WebFlux plus a reactive driver such as R2DBC.
- Why can a blocking call placed after the first suspension be worse than one placed before it?Under the unconfined dispatcher Spring MVC uses, the coroutine resumes on whatever thread completed the awaited operation. With a non-blocking HTTP client that is usually one of its few I/O threads, so a JDBC call there stalls every connection sharing that thread. A blocking call before the first suspension only holds the servlet thread, which plain MVC would have held anyway.
- Does a Spring MVC suspend handler use the same async task executor that a returned Callable uses?Not for an ordinary response. `ReactiveTypeHandler` subscribes to the coroutine's `Mono` and bridges it to a `DeferredResult`, so nothing is submitted to the MVC async executor; the coroutine runs on the servlet thread and then on whichever threads resume it. A `TaskExecutor` is used only on the streaming path, to send emitted items.
- What would you advise the team whose endpoint calls a slow HTTP API and a JDBC repository?Decide per dependency. If both stay blocking, drop `suspend` and run plain MVC, perhaps on virtual threads. If they keep `suspend`, call the HTTP API with a non-blocking client that truly suspends and move the JDBC call explicitly onto a bounded pool. WebFlux-style scaling needs a non-blocking path end to end, such as WebFlux with R2DBC.
- Adding suspend to an MVC handler makes its blocking JDBC calls non-blocking.
- Spring MVC runs suspend handlers on Dispatchers.IO, so blocking inside them is safe.
- Suspend controller methods work only in WebFlux, never in Spring MVC.
- The servlet thread is freed the instant a suspend handler is invoked.
- Returning a Flow from an MVC controller always streams elements to the client.
- Spring MVC wraps every suspend handler in runBlocking on the servlet thread.