BE·48
Spring Web — MVC and WebFlux
Inside Spring MVC: the DispatcherServlet pipeline, controllers and request mapping, argument resolution and validation, exception handling with @ControllerAdvice and ProblemDetail, filters versus interceptors, message converters, Jackson serialisation, content negotiation, and HTTP clients (RestClient and declarative @HttpExchange interfaces). Then WebFlux and reactive programming from first principles: Reactive Streams, Publisher/Subscriber, backpressure, the event loop, Mono/Flux composition, and when reactive is worth it versus virtual threads. Compared with Kotlin Flow and coroutines, RxJava, Rust streams, .NET IAsyncEnumerable and Akka Streams.
Start here: a REST API the Spring way
From hand-written routing to annotations
Chapter 44 parsed paths with matches("/orders/\\d+"), extracted JSON fields with regular expressions and chose status codes in if chains. Spring MVC does all of that from annotations on a plain class: it routes requests to methods, converts path segments, query parameters and JSON bodies into typed arguments, converts return values into JSON, and maps exceptions to error responses. The same model exists in ASP.NET Core ([ApiController]), NestJS (@Controller), FastAPI (decorators), JAX-RS/Quarkus and Micronaut.
public record CreateOrder(String dish, Integer qty) {}
public record Order(long id, String dish, int qty, String status) {}
@RestController @RequestMapping("/api/orders")
static class OrderController {
@PostMapping ResponseEntity<Order> create(@RequestBody CreateOrder req) {
… validate, collecting every field error …
if (!errors.isEmpty()) throw new InvalidOrder(errors);
var o = new Order(seq.incrementAndGet(), req.dish(), req.qty(), "NEW"); store.put(o.id(), o);
return ResponseEntity.created(URI.create("/api/orders/" + o.id())).body(o);
}
@GetMapping("/{id}") Order get(@PathVariable long id) { … throw new OrderNotFound(id) if missing … }
@GetMapping List<Order> list(@RequestParam(defaultValue = "NEW") String status, @RequestParam(defaultValue = "20") int limit) { … }
}
@RestControllermarks a class whose methods handle HTTP requests and whose return values become response bodies.@GetMapping("/{id}"),@PostMapping: route by method and path;@RequestMappingon the class sets the common prefix.@PathVariable long id,@RequestParam: typed values from the URL, with defaults. A non-number id is rejected with 400 before your code runs.@RequestBody CreateOrder req: the JSON body, deserialised by Jackson into a record.ResponseEntity: when you need to control the status and headers (201 withLocation); otherwise return the object and get 200.
Errors in one place
@RestControllerAdvice
static class Errors {
@ExceptionHandler(OrderNotFound.class) ProblemDetail notFound(OrderNotFound e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage()); }
@ExceptionHandler(InvalidOrder.class) ProblemDetail invalid(InvalidOrder e) {
var p = ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, "the order has invalid fields");
p.setTitle("Invalid order"); p.setProperty("errors", e.errors); return p; }
}
Controllers throw domain exceptions; one advice class turns them into RFC 9457 Problem Details (Spring's ProblemDetail type), so every endpoint reports errors the same way. In a full application, @Valid with Bean Validation annotations on the record (@NotBlank String dish, @Min(1) @Max(20) Integer qty) replaces the hand-written checks and produces the same field-error map.
The results
$ curl -i -X POST localhost:8098/api/orders -H 'Content-Type: application/json' -d '{"dish":"Masala dosa","qty":2}'
HTTP/1.1 201
X-Request-Id: 9f12848d
Location: /api/orders/101
{"id":101,"dish":"Masala dosa","qty":2,"status":"NEW"}
$ curl localhost:8098/api/orders/999
HTTP/1.1 404 Content-Type: application/problem+json
{"detail":"order 999 not found","instance":"/api/orders/999","status":404,"title":"Not Found"}
$ curl -X POST localhost:8098/api/orders -H 'Content-Type: application/json' -d '{"dish":"","qty":50}'
HTTP/1.1 422 Content-Type: application/problem+json
{"detail":"the order has invalid fields","instance":"/api/orders","status":422,"title":"Invalid order",
"errors":{"dish":"must not be blank","qty":"must be between 1 and 20"}}
$ curl -X POST localhost:8098/api/orders -H 'Content-Type: application/json' -d '{"dish": "Idli", qty: }'
HTTP/1.1 400 Content-Type: application/json
{"timestamp":"2026-10-29T14:37:37.384Z","status":400,"error":"Bad Request","path":"/api/orders"}
Notice the last one: malformed JSON never reached the controller, so the advice didn't see it, and Boot's older default error format came back instead of Problem Details. One property fixes that inconsistency (lab experiment 1).
Filters, interceptors and advice
Three hooks run around controllers, at different layers:
@Component static class RequestIdFilter implements Filter { … sets X-Request-Id, then chain.doFilter(req, res) … }
@Component static class Timing implements HandlerInterceptor, WebMvcConfigurer {
public boolean preHandle(…) { r.setAttribute("t0", System.nanoTime()); return true; }
public void afterCompletion(…, Object handler, Exception ex) { … log method, path, status, handler name, ms … }
}
POST /api/orders -> 201 (create) 68.9 ms
GET /api/orders/101 -> 200 (get) 7.4 ms
GET /api/orders/999 -> 404 (get) 20.1 ms
POST /api/orders -> 422 (create) 3.9 ms
GET /api/nothing -> 404 (no handler) 3.4 ms
A servlet filter sees every request, even ones Spring MVC never handles (static files, other servlets), and works with raw requests: request ids, CORS, security (Spring Security is a chain of filters, chapter 50), compression. An interceptor runs inside Spring MVC and knows which controller method was chosen (create, get), so it suits per-endpoint timing, auditing and tenant checks. Advice handles exceptions and cross-cutting response concerns. The first request took 69 ms and later ones 3–7 ms: warm-up again.
Calling other services
@Bean RestClient kitchenClient() { return RestClient.builder().baseUrl("http://localhost:8098").build(); }
kitchen.get().uri("/api/orders?status=NEW").retrieve().body(List.class);
RestClient is Spring's fluent, synchronous HTTP client: the right default for MVC applications, especially on virtual threads. It has no read timeout unless you configure one (lab experiment 3). The reactive WebClient belongs to WebFlux, Spring's non-blocking web stack built on Project Reactor, covered in the second half of this chapter along with when reactive programming is worth its complexity.
How deep to go in Spring Web
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Write REST controllers with mappings, path variables, parameters and bodies |
| L2 | Add validation, ProblemDetail error handling, filters, interceptors and RestClient calls |
| L3 | Explain DispatcherServlet's flow, message converters, content negotiation, Reactor and WebFlux's event loop, and when reactive beats virtual threads |
| L4 | Diagnose thread-pool limits, missing timeouts, inconsistent errors and blocking calls on event loops |
| L5 | Set API-layer conventions (errors, versioning, clients, observability) for many services |
| L6 | Choose web stacks (MVC, WebFlux, others) for an organisation's workloads |
Spring MVC
The DispatcherServlet
Spring MVC is a front controller design. One servlet, the DispatcherServlet, receives every request and delegates to pluggable strategies:
The strategy interfaces are where you customise: HandlerMapping (annotation or functional routes), HandlerAdapter, HandlerMethodArgumentResolver (custom parameter types such as @CurrentUser User), HandlerMethodReturnValueHandler, HttpMessageConverter (body serialisation), HandlerExceptionResolver, HandlerInterceptor, LocaleResolver, and ViewResolver (for server-side templates such as Thymeleaf). Most customisation goes through a WebMvcConfigurer bean:
@Configuration
class WebConfig implements WebMvcConfigurer {
@Override public void addInterceptors(InterceptorRegistry r) { r.addInterceptor(new TenantInterceptor()).addPathPatterns("/api/**"); }
@Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> rs) { rs.add(new CurrentUserResolver()); }
@Override public void addCorsMappings(CorsRegistry r) { r.addMapping("/api/**").allowedOrigins("https://shop.example.com"); }
@Override public void configureApiVersioning(ApiVersionConfigurer c) { c.useRequestHeader("API-Version"); } // Spring 7
}
Controllers and request mapping
@RestController // = @Controller + @ResponseBody on every method
@RequestMapping(path = "/api/orders", produces = MediaType.APPLICATION_JSON_VALUE)
class OrderController {
private final OrderService orders;
OrderController(OrderService orders) { this.orders = orders; }
@GetMapping
PagedResponse<OrderSummary> list(@RequestParam(defaultValue = "PAID") Set<Status> status,
@RequestParam(required = false) String cursor,
@RequestParam(defaultValue = "50") @Max(200) int limit) {
return orders.list(status, cursor, limit);
}
@GetMapping("/{id}")
OrderDto get(@PathVariable OrderId id) { return orders.find(id); } // custom type via a Converter
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
OrderDto create(@Valid @RequestBody CreateOrder cmd,
@RequestHeader("Idempotency-Key") UUID key,
@AuthenticationPrincipal Jwt jwt) { // resolved from the security context
return orders.create(cmd, key, jwt.getSubject());
}
@PatchMapping(path = "/{id}", consumes = "application/merge-patch+json")
OrderDto patch(@PathVariable OrderId id, @RequestBody JsonNode patch) { return orders.patch(id, patch); }
@DeleteMapping("/{id}")
ResponseEntity<Void> cancel(@PathVariable OrderId id) { // ResponseEntity = full control
orders.cancel(id);
return ResponseEntity.noContent().build();
}
@GetMapping(path = "/export", produces = "text/csv")
ResponseEntity<StreamingResponseBody> export() { // stream large responses
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=orders.csv")
.body(out -> orders.writeCsv(out));
}
}
Handler method arguments Spring resolves automatically include @PathVariable, @RequestParam (with type conversion and binding of List, Set and Map), @RequestHeader, @CookieValue, @RequestBody (through message converters), @ModelAttribute (form and query binding to objects), HttpServletRequest/Response, Principal/@AuthenticationPrincipal, Locale, UriComponentsBuilder, Pageable/Sort (Spring Data web support), @RequestAttribute, @SessionAttribute and Errors/BindingResult.
Return types include: a POJO or record (serialised), ResponseEntity<T>, ProblemDetail, StreamingResponseBody, ResponseBodyEmitter/SseEmitter (server-sent events), Callable/DeferredResult/CompletableFuture (async servlet processing; much less needed with virtual threads), and even Mono/Flux (adapted).
The functional endpoints alternative (WebMvc.fn) uses explicit routing functions with no annotations:
@Bean
RouterFunction<ServerResponse> routes(OrderHandler h) {
return route()
.path("/api/orders", b -> b
.GET("/{id}", h::get)
.POST(contentType(MediaType.APPLICATION_JSON), h::create))
.filter(new LoggingFilter())
.build();
}
Validation in MVC
@Valid @RequestBody CreateOrder cmd: Bean Validation on the body. Failures raiseMethodArgumentNotValidException(status 400).- Constraints directly on
@RequestParamand@PathVariableparameters (@Max(200) int limit): Spring 6.1+ has built-in method validation for controllers, raisingHandlerMethodValidationException. @Validatedon a service class enables AOP-based method validation for other beans (ConstraintViolationException).- Validation groups (
@Validated(OnCreate.class)) for different rules on create versus update. They're rarely worth their complexity; separate command records (CreateOrder,UpdateOrder) are clearer. - Custom constraints:
@Constraint(validatedBy = SkuValidator.class)with an annotation and aConstraintValidator.
Exception handling and ProblemDetail
Centralise HTTP error mapping in a @RestControllerAdvice:
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler { // handles Spring MVC's own exceptions as ProblemDetail
@ExceptionHandler(OrderNotFound.class)
ProblemDetail notFound(OrderNotFound e, HttpServletRequest req) {
var pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
pd.setType(URI.create("https://api.shop.example/problems/order-not-found"));
pd.setTitle("Order not found");
pd.setInstance(URI.create(req.getRequestURI()));
return pd;
}
@ExceptionHandler(InsufficientStock.class)
ProblemDetail stock(InsufficientStock e) {
var pd = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
pd.setType(URI.create("https://api.shop.example/problems/insufficient-stock"));
pd.setProperty("sku", e.sku()); // extension members
pd.setProperty("available", e.available());
return pd;
}
@ExceptionHandler(OptimisticLockingFailureException.class)
ProblemDetail conflict() {
return ProblemDetail.forStatusAndDetail(HttpStatus.PRECONDITION_FAILED, "The order was modified concurrently");
}
@Override // reshape validation errors with field pointers
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
var pd = ex.getBody(); // already a ProblemDetail
pd.setProperty("errors", ex.getFieldErrors().stream()
.map(fe -> Map.of("pointer", "/" + fe.getField().replace('.', '/'), "detail", fe.getDefaultMessage()))
.toList());
return ResponseEntity.status(status).headers(headers).body(pd);
}
@ExceptionHandler(Exception.class) // last resort: never leak internals
ProblemDetail unexpected(Exception e) {
log.error("unhandled", e);
return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
}
}
spring.mvc.problemdetails.enabled=truemakes Spring's built-in exceptions (404 no handler, 405, 415, type mismatch) render as Problem Details without the subclass.- Exceptions can carry their HTTP mapping themselves by implementing
ErrorResponseor extendingErrorResponseException. That's convenient, but it couples domain exceptions to HTTP. Mapping in the advice keeps the domain clean (chapter 44). - Message localisation: Problem Detail
titleanddetailcan be resolved fromMessageSourcekeys (problemDetail.title.com.shop.OrderNotFound). - Errors raised inside filters (before the DispatcherServlet) don't reach
@ControllerAdvice. Spring Security handles them with its ownAuthenticationEntryPointandAccessDeniedHandler(chapter 50).
Filters versus interceptors versus advice
| Mechanism | Level | Sees | Use for |
|---|---|---|---|
Servlet Filter (OncePerRequestFilter) |
Servlet container, before the DispatcherServlet | Raw request and response; runs for all requests, including static resources and errors | Security (Spring Security is a filter chain), tracing, request IDs, CORS, compression, request logging, body caching |
HandlerInterceptor |
Inside MVC, after handler mapping | The chosen handler (controller method and its annotations); preHandle can reject; postHandle; afterCompletion (with any exception) |
Per-route concerns that need handler metadata: tenant resolution, custom annotation checks, timing per handler |
@ControllerAdvice |
Around controller invocation | Exceptions (@ExceptionHandler), model attributes, @InitBinder; ResponseBodyAdvice/RequestBodyAdvice |
Error mapping, body wrapping and transformation |
| AOP aspects | Around bean methods | Method calls on any bean | Business-level cross-cutting concerns (chapter 46) |
Message converters, serialisation and content negotiation
HttpMessageConverters turn request bodies into objects and objects into response bodies, chosen by Content-Type/Accept and the Java type: Jackson JSON (and XML, CBOR, Smile, YAML), String, byte arrays and Resource, form data, protobuf, and Kotlin Serialization (Boot 4). Content negotiation uses the Accept header by default. Path extensions are no longer supported, and a query parameter strategy is opt-in.
Jackson 3 (the default in Boot 4) changed packages for the core databind API to tools.jackson.databind (annotations stay in com.fasterxml.jackson.annotation), made ObjectMapper immutable and builder-configured (JsonMapper.builder()), and switched exceptions to unchecked. Boot configures it from properties and customiser beans:
spring:
jackson:
default-property-inclusion: non_null
deserialization:
fail-on-unknown-properties: false
serialization:
write-dates-as-timestamps: false # ISO-8601 strings for java.time
time-zone: UTC
@Bean
JsonMapperBuilderCustomizer jsonCustomizer() { // Boot 4 / Jackson 3 customiser
return builder -> builder.addModule(new MoneyModule())
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
}
// Per-type control: @JsonProperty, @JsonIgnore, @JsonInclude, @JsonFormat, @JsonCreator,
// @JsonTypeInfo(use = NAME) + @JsonSubTypes for sealed hierarchies (never CLASS-based typing).
// @JsonView for different projections of one type (often a DTO per view is clearer).
HTTP clients: RestClient and @HttpExchange
Spring offers three clients: RestClient (synchronous with a fluent API, Spring 6.1+, the recommended choice for MVC and virtual-thread apps), WebClient (reactive, non-blocking), and RestTemplate (the older synchronous template, now in maintenance mode). Spring Framework 7 also adds HTTP service client interfaces with Boot auto-configuration:
// 1. Fluent RestClient
@Bean
RestClient paymentsRestClient(RestClient.Builder builder, PaymentsProperties p) {
var http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build(); // JDK HttpClient
var factory = new JdkClientHttpRequestFactory(http);
factory.setReadTimeout(p.timeout()); // ALWAYS set timeouts (chapter 52)
return builder
.baseUrl(p.baseUrl().toString())
.requestFactory(factory)
.defaultHeader("X-Api-Key", p.apiKey())
.defaultStatusHandler(HttpStatusCode::is5xxServerError,
(req, res) -> { throw new PaymentsUnavailable(res.getStatusCode()); })
.build();
}
PaymentResult charge(ChargeRequest r, String idemKey) {
return client.post().uri("/v1/charges")
.header("Idempotency-Key", idemKey)
.body(r)
.retrieve()
.onStatus(s -> s.value() == 402, (req, res) -> { throw new PaymentDeclined(); })
.body(PaymentResult.class);
}
// 2. Declarative HTTP service interface (implementation generated at run time; Boot 4 auto-configures groups)
@HttpExchange("/v1")
interface PaymentsApi {
@PostExchange("/charges")
PaymentResult charge(@RequestBody ChargeRequest r, @RequestHeader("Idempotency-Key") String key);
@GetExchange("/charges/{id}")
PaymentResult get(@PathVariable String id);
}
Equivalents elsewhere: Feign/OpenFeign (Spring Cloud) and Retrofit (Java/Android) for declarative clients; Go net/http.Client (set Timeout; the default has none) plus generated clients (ogen, oapi-codegen); Rust reqwest; .NET HttpClient via IHttpClientFactory plus Refit or Kiota for declarative clients; Python httpx. Client concerns are the same everywhere: timeouts, connection pooling, retries with backoff for idempotent calls, circuit breakers, tracing propagation, and mapping errors (chapter 52).
Reactive programming and WebFlux
Why reactive programming exists
In a thread-per-request server with platform threads, each request blocked on I/O holds an expensive OS thread (chapter 38). The reactive answer (Reactor, RxJava, Akka Streams, Vert.x) is to never block. I/O operations return immediately with a publisher of the future result, a small number of event-loop threads process completions, and your logic is expressed as a pipeline of transformations applied as data arrives.
Reactive programming adds a second idea beyond non-blocking I/O: streams with backpressure. A fast producer (a database cursor, a Kafka topic, a file) mustn't overwhelm a slow consumer (a client on a slow network), so demand flows upstream.
Reactive Streams: Publisher, Subscriber and backpressure
Reactive Streams (2015; adopted into the JDK as java.util.concurrent.Flow in Java 9) is a tiny specification of four interfaces that interoperating libraries share:
public interface Publisher<T> { void subscribe(Subscriber<? super T> s); }
public interface Subscriber<T> { void onSubscribe(Subscription s); void onNext(T t); void onError(Throwable t); void onComplete(); }
public interface Subscription { void request(long n); void cancel(); } // ← demand signalling = backpressure
public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {}
- Demand-driven: the publisher may emit at most as many
onNextsignals as requested. That's backpressure, propagated hop by hop through the whole pipeline: the HTTP connection's write buffer, the operators, the R2DBC driver, the database cursor. - Asynchronous and non-blocking: signals can arrive on any thread, but never concurrently for one subscriber.
- Terminal signals: exactly one
onCompleteoronError, after which nothing more arrives. - Lazy (cold): nothing happens until someone subscribes. Assembling a pipeline is just building a recipe.
You almost never implement these interfaces yourself. Libraries such as Project Reactor (Spring's choice), RxJava, Mutiny (Quarkus), Akka/Pekko Streams and the JDK HTTP client's body publishers implement them and interoperate through them.
Reactor: Mono and Flux
Reactor provides two publisher types:
Mono<T>: 0 or 1 item (like an asyncOptionalorCompletableFuture).Flux<T>: 0..N items (an async stream).
// WebFlux controller (annotation style works the same as MVC, but returns publishers)
@RestController
@RequestMapping("/api/orders")
class ReactiveOrderController {
private final OrderRepository orders; // ReactiveCrudRepository (R2DBC)
private final WebClient pricing;
@GetMapping("/{id}")
Mono<OrderDto> get(@PathVariable String id) {
return orders.findById(id) // Mono<Order>
.switchIfEmpty(Mono.error(new OrderNotFound(id))) // empty → 404 via advice
.flatMap(o -> pricing.get().uri("/quotes/{id}", id) // async call, flattened
.retrieve().bodyToMono(Quote.class)
.timeout(Duration.ofMillis(800))
.onErrorResume(e -> Mono.just(Quote.unavailable())) // graceful degradation
.map(q -> OrderDto.from(o, q)));
}
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE) // server-sent events
Flux<OrderEvent> stream() {
return events.asFlux()
.filter(e -> e.type() != Type.INTERNAL)
.limitRate(100); // request in batches of 100 upstream
}
@PostMapping("/import")
Mono<ImportResult> importOrders(@RequestBody Flux<CreateOrder> body) { // streaming request body
return body
.buffer(500) // batch inserts
.concatMap(batch -> orders.saveAll(batch.stream().map(Order::from).toList()).count(), 1)
.reduce(0L, Long::sum)
.map(ImportResult::new);
}
}
Core operators and their analogies:
| Operator | Meaning | Analogy |
|---|---|---|
map |
Synchronous transform | Stream.map |
flatMap |
Async transform, interleaved, concurrent (default concurrency 256) | thenCompose, but for many items concurrently |
concatMap |
Async transform, sequential, order preserved | One at a time |
flatMapSequential |
Concurrent but emits in source order | — |
filter, take, skip, distinct, buffer, window, groupBy |
Stream shaping | Streams and collectors |
zip, zipWith, Mono.zip(a, b, c) |
Combine latest results pairwise | thenCombine, allOf |
merge, concat |
Combine streams | — |
timeout, retryWhen(Retry.backoff(3, 100ms).jitter(0.5)), onErrorResume, onErrorReturn, onErrorMap |
Resilience | Chapter 52 |
subscribeOn, publishOn |
Choose which scheduler runs the subscription and the downstream signals | Executors |
doOnNext, doOnError, doFinally, log |
Side effects and debugging | peek |
contextWrite / deferContextual |
Reactor Context: request-scoped data that flows upstream through the subscription (security, tracing) instead of ThreadLocal |
ScopedValue |
The golden rules of reactive code:
- Nothing happens until you subscribe. In WebFlux, the framework subscribes to what your controller returns. Calling
.subscribe()yourself inside a handler fires and forgets, outside the request's lifecycle and error handling. - Never block in a reactive pipeline. No
.block(), JDBC,Thread.sleep, blocking file I/O or synchronous HTTP insidemap/flatMapon an event-loop thread. One blocking call stalls every request on that thread. BlockHound detects blocking calls in tests. If you must call blocking code, isolate it:Mono.fromCallable(blocking).subscribeOn(Schedulers.boundedElastic()). - Use the reactive stack end to end: R2DBC instead of JDBC,
WebClientinstead ofRestTemplate, reactive Redis, Mongo and Kafka drivers. A single blocking dependency undermines the model. - Errors are signals: handle them with operators, not try/catch around the assembly code.
- Context, not ThreadLocal: execution hops threads, so MDC and security context need Reactor
Contextplus Micrometer's context-propagation library (Boot configures it withspring.reactor.context-propagation=auto).
The event loop
Reactor Netty (WebFlux's default server) runs a small number of event-loop threads (about one per core). Each loop owns many connections, waits for readiness events from the OS (epoll, kqueue, io_uring), and runs the callbacks for whichever connections are ready. This is the same model as Node.js, Nginx and Vert.x (Vol. 1 ch. 9):
- Pros: tens of thousands of concurrent connections with few threads and little memory; natural support for streaming, SSE, WebSockets and long polling; end-to-end backpressure.
- Cons: every callback must be short and non-blocking. CPU-heavy work must be offloaded (
publishOn(Schedulers.parallel())). Stack traces show operator internals instead of your call path (useHooks.onOperatorDebug()orcheckpoint()in development, or the ReactorDebugAgent in production). Debugging, testing (StepVerifier) and onboarding cost more.
When reactive is worth it, and when virtual threads are simpler
Since JDK 21, virtual threads give imperative, blocking-style code the main scalability benefit that reactive provided, many concurrent waiting requests on few OS threads, without changing the programming model:
| Situation | Better fit |
|---|---|
| Typical CRUD/REST service calling a DB and a few services | Spring MVC + virtual threads: simple code, readable stack traces, JDBC/JPA, the whole ecosystem |
| Streaming large or unbounded data with backpressure (exports, event feeds, proxying streams) | WebFlux/Reactor (or MVC with StreamingResponseBody/SSE for simpler cases) |
| Many long-lived connections: WebSockets, SSE fan-out, chat, live dashboards | WebFlux (or MVC with virtual threads for moderate scale) |
| Complex async composition: fan-out/fan-in, racing replicas, timeouts per branch, streaming merges | Reactor's operators are powerful. Structured concurrency covers fan-out and fan-in imperatively |
| API gateways and proxies (Spring Cloud Gateway), high-throughput edge services | Reactive/Netty, built for it |
| Team unfamiliar with reactive; heavy use of blocking libraries (JDBC, JPA, legacy SDKs) | MVC + virtual threads |
| Need for ThreadLocal-based libraries (some security and tracing integrations) | MVC |
Reactive still has a place: streams and backpressure are a genuine programming model, not just a scalability trick. But for request/response services, the industry has largely concluded that virtual threads (or Go's goroutines) give the same throughput with far simpler code. Spring supports both: Spring MVC on virtual threads (spring.threads.virtual.enabled=true), and WebFlux/Reactor where streaming semantics are the point.
Reactive and async streams in other languages
// Kotlin: suspend functions for single values, Flow for cold streams (backpressure by suspension)
@GetMapping("/{id}")
suspend fun get(@PathVariable id: String): OrderDto { // Spring WebFlux supports suspend controllers
val order = orders.findById(id) ?: throw OrderNotFound(id)
val quote = pricing.quote(id) // suspending HTTP call
return OrderDto.from(order, quote)
}
@GetMapping("/events", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun events(): Flow<OrderEvent> = eventBus.events()
.filter { it.type != Type.INTERNAL }
.buffer(100) // decouple producer and consumer
// Flow's backpressure is natural: emit() suspends until the collector is ready.
// Rust: async/await + the Stream trait (futures crate); backpressure via poll-based pulling
use futures::{Stream, StreamExt};
async fn export(pool: PgPool) -> impl IntoResponse {
let rows = sqlx::query_as::<_, OrderRow>("SELECT * FROM orders ORDER BY id").fetch(&pool); // Stream<Item = Result<Row>>
let body = rows.map(|r| r.map(|o| format!("{},{},{}\n", o.id, o.status, o.total)));
([(header::CONTENT_TYPE, "text/csv")], Body::from_stream(body)) // pulled as the socket can accept bytes
}
// Futures and streams are POLLED: nothing runs unless polled, so demand-driven behaviour is built in.
// .NET: IAsyncEnumerable<T> for async streams; Rx.NET (System.Reactive) for push-based event streams
app.MapGet("/orders/export", (OrderDb db, CancellationToken ct) => StreamOrders(db, ct));
static async IAsyncEnumerable<OrderDto> StreamOrders(OrderDb db, [EnumeratorCancellation] CancellationToken ct)
{
await foreach (var o in db.Orders.AsNoTracking().OrderBy(o => o.Id).AsAsyncEnumerable().WithCancellation(ct))
yield return OrderDto.From(o); // serialised as a streaming JSON array
}
// System.Threading.Channels: bounded channels give backpressure between producers and consumers.
// Go: channels give natural backpressure (an unbuffered or bounded channel blocks the sender)
func export(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(r.Context(), "SELECT id, status, total FROM orders ORDER BY id")
if err != nil { http.Error(w, "db", 500); return }
defer rows.Close()
w.Header().Set("Content-Type", "text/csv")
bw := bufio.NewWriter(w)
for rows.Next() { // pull one row at a time; Write blocks if the client is slow
var o Order
if err := rows.Scan(&o.ID, &o.Status, &o.Total); err != nil { return }
fmt.Fprintf(bw, "%s,%s,%s\n", o.ID, o.Status, o.Total)
}
bw.Flush()
}
// Blocking I/O in goroutines IS the scalable model, so reactive libraries are rare in Go.
# Elixir: GenStage/Flow/Broadway implement demand-driven pipelines between processes
Repo.transaction(fn ->
Order
|> Repo.stream(max_rows: 500) # a DB cursor as a lazy Stream
|> Stream.map(&to_csv_line/1)
|> Enum.into(File.stream!("orders.csv"))
end)
# Broadway: Kafka/SQS consumers with demand-based backpressure and batching
The deeper pattern: pull-based models (Rust futures and streams, Go blocking reads and writes, Kotlin Flow, IAsyncEnumerable, Java virtual threads with blocking I/O) get backpressure "for free", because the consumer drives progress. Push-based models (callbacks, Rx, event emitters) need an explicit demand protocol, which is exactly what Reactive Streams' request(n) adds.
Lab: Spring MVC and Reactor under pressure
Spring Boot 4.1.1 (Spring MVC 7.0.9, Tomcat 11.0.24) and Reactor 3.8.7 on JDK 21, 2 cores; the OrdersApp from Start here plus three test endpoints (/api/slow sleeps 100 ms, /api/hang sleeps 20 s, /api/call-hang calls /api/hang with RestClient). Load comes from a Java client firing 400 concurrent requests on the same machine.
Experiment 1: making every error a Problem Detail
With spring.mvc.problemdetails.enabled=true:
$ curl -X POST localhost:8098/api/orders -H 'Content-Type: application/json' -d '{"dish": "Idli", qty: }'
{"detail":"Failed to read request","instance":"/api/orders","status":400,"title":"Bad Request"}
$ curl localhost:8098/api/nothing
{"detail":"No static resource api/nothing.","instance":"/api/nothing","status":404,"title":"Not Found"}
Before, these two came back in Boot's older {"timestamp", "status", "error", "path"} shape while the application's own errors used Problem Details: two formats for clients to parse. The property registers Spring's ResponseEntityExceptionHandler, which maps the framework's own exceptions (unreadable bodies, type mismatches, missing parameters, unsupported media types, unknown routes, validation failures) to ProblemDetail. Extend that class in your advice to customise them. Note what the 400 doesn't say: Jackson's parse error (line, column, the offending token) is deliberately hidden from the client.
Experiment 2: Tomcat's thread pool versus virtual threads
The pool is cut to 20 threads (server.tomcat.threads.max=20; the default is 200) to make the limit visible with 400 concurrent requests to a 100 ms endpoint:
platform threads, max 20: 400 requests: total 2128 ms | 188 req/s | p50 1100 ms | p99 1993 ms
{"thread":"Thread[#48,http-nio-8098-exec-19,5,main]"}
virtual threads: 400 requests: total 860 ms | 465 req/s | p50 566 ms | p99 822 ms
{"thread":"VirtualThread[#1234,tomcat-handler-1201]/runnable@ForkJoinPool-1-worker-1"}
With 20 platform threads, Little's law caps throughput at 20 ÷ 0.1 s = 200 requests per second, and the measurement (188) sits right under it, with the median request queuing for over a second. spring.threads.virtual.enabled=true makes Tomcat run each request on a new virtual thread, removing that cap; throughput rose 2.5× and the remaining time is CPU (Spring, Tomcat and the load generator sharing two cores), not waiting. The same property switches @Async, scheduling and several other executors to virtual threads. With them, the limit moves to downstream resources, so keep connection-pool sizes and add concurrency limits (@ConcurrencyLimit in Spring Framework 7, chapter 52) where a dependency can't take unlimited load.
Experiment 3: RestClient without a timeout
$ curl 'localhost:8098/api/call-hang' → {"ms":20098,"result":"ok"}
$ curl 'localhost:8098/api/call-hang?timeoutMs=500' → {"ms":563,"result":"ResourceAccessException"}
var f = new JdkClientHttpRequestFactory(); f.setReadTimeout(Duration.ofMillis(500));
RestClient c = RestClient.builder().baseUrl(…).requestFactory(f).build();
Without a read timeout the call waited the full 20 seconds for the slow service, holding the caller's request (and on platform threads, a pool thread) the whole time. With 500 ms it failed fast with ResourceAccessException, which an advice can map to 503 or 504, or a resilience layer can turn into a fallback. In Boot 4, set defaults for every auto-configured client with spring.http.clients.connect-timeout and spring.http.clients.read-timeout (backed by HttpClientSettings), and override them per HTTP service client group with spring.http.serviceclient.<group>.*.
Experiment 4: Reactor's rules
Mono<String> order = Mono.fromCallable(() -> { calls.incrementAndGet(); return "order 101"; });
Flux.range(1, 1000).doOnRequest(n -> log(n)).limitRate(100).take(250).blockLast();
Mono.zip(menu(300 ms), stock(300 ms), offers(5 s).timeout(500 ms).onErrorReturn("no offers"));
Flux.range(1, 20).flatMap(i -> Mono.fromCallable(() -> { sleep(100); return i; }).subscribeOn(scheduler));
1) Mono built: database calls so far = 0
after two subscribe() calls: database calls = 2
2) take(250) with limitRate(100): upstream was asked for 100 75 75 75
3) zip of three calls (one slow, with timeout and fallback): menu+stock+no offers in 533 ms
4) 20 blocking 100 ms calls on a 2-thread event-loop scheduler: 1012 ms
4) 20 blocking 100 ms calls on boundedElastic: 106 ms
Four rules of reactive code, each visible here. Nothing happens until subscription, and each subscription repeats the work (two subscribes, two "database calls"; use cache() to share one result). Backpressure: the consumer requests items in batches (100, then 75 at a time as 75% are consumed) instead of being flooded, which is what Reactive Streams adds over plain callbacks. Composition: three calls ran concurrently, the slow one was cut off at 500 ms with a fallback, all declared in one expression. And never block an event loop: a blocking call on a scheduler with two threads serialised twenty 100 ms calls into ten rounds (1 s), and in WebFlux those two threads would be serving every request. Blocking work must move to boundedElastic (or not be blocking). Since virtual threads make blocking code scale, new MVC code gets most of the throughput benefit without these rules; reactive remains the better fit for streaming, backpressure-sensitive pipelines and fan-out with complex timing.
Try it yourself
- Add
@Validand Bean Validation annotations toCreateOrder(withspring-boot-starter-validation) and compare the automatic 400 response'serrorswith the hand-built 422. - Repeat experiment 2 with the default 200 platform threads and 1,000 requests. Where does the knee in p99 appear?
- Rewrite
OrdersApp's list endpoint for WebFlux returningFlux<Order>, and call it withAccept: application/x-ndjsonto stream results. - Write experiment 4's
zipwithStructuredTaskScopeon virtual threads (JDK 25 preview) and compare readability.
Revision sheet: Spring Web, MVC and WebFlux
Key ideas
- DispatcherServlet flow: filters → handler mapping → interceptors'
preHandle→ argument resolvers and message converters → controller → return-value handlers → exception resolvers (advice) →afterCompletion; errors otherwise forwarded to/error. - Controllers:
@RestController, mapping annotations,@PathVariable,@RequestParam,@RequestHeader,@RequestBody,ResponseEntity; API versioning support in Spring 7. - Validation and errors:
@Validwith Bean Validation;@RestControllerAdvice;ProblemDetailandErrorResponse;spring.mvc.problemdetails.enabled. - Hooks: servlet filters (everything, raw),
HandlerInterceptor(handler-aware), advice (exceptions, bodies). - Serialisation:
HttpMessageConverters, content negotiation byAccept, Jackson 3 withJsonMappercustomisers. - Clients:
RestClient(sync, fluent), HTTP service interfaces (@HttpExchange),WebClient(reactive),RestTemplate(maintenance); timeouts via request factories. - Reactive: Reactive Streams (publisher, subscriber, subscription, backpressure); Reactor
Mono/Flux, operators, schedulers; WebFlux on Netty's event loop; never block the loop; virtual threads as the simpler alternative for blocking stacks. - Elsewhere: ASP.NET Core controllers and minimal APIs, NestJS, FastAPI, JAX-RS/Quarkus, Ktor, Express/Fastify; reactive equivalents in RxJS, Kotlin Flow, Akka Streams, Rust async streams.
Numbers to remember
- Lab: 20 Tomcat threads capped a 100 ms endpoint at 188 req/s (Little's law: 200); virtual threads reached 465 req/s on 2 cores; a RestClient with no timeout waited 20 s, with 500 ms it failed in 563 ms; 20 blocking calls on a 2-thread event loop took 1,012 ms vs 106 ms on boundedElastic.
- Tomcat default max threads 200; Reactor
limitRate(n)replenishes at 75%.
Pitfalls
- Two error formats (framework errors not mapped to ProblemDetail).
- Business logic in controllers; entities exposed directly as request/response bodies.
- HTTP clients without connect and read timeouts.
- Blocking calls (JDBC,
RestClient,Thread.sleep) inside WebFlux handlers. - Subscribing twice to a cold publisher and repeating side effects.
- Platform-thread pools sized without Little's law; virtual threads without downstream limits.
Glossary
- Handler: the controller method chosen for a request.
- Message converter: converts between HTTP bodies and objects.
- Interceptor: hook around handler execution inside Spring MVC.
- Backpressure: consumers signalling how much they can take.
- Cold publisher: one that starts work anew for each subscriber.
- Event loop: a few threads multiplexing many connections with non-blocking I/O.