Spring WebFlux: reactive REST APIs
Spring WebFlux runs your controllers on a few Netty event-loop threads instead of one thread per request. That changes what a handler may do and how it returns data. This page explains the model, then runs complete Spring Boot 4.1 applications: annotated and functional endpoints, streaming, error handling, what blocking costs, and testing.
Contents
How WebFlux handles a request Annotated controllers returning Mono and Flux Functional endpoints with RouterFunction Streaming with server-sent events and NDJSON Error handling: empty results, status codes and ProblemDetail The blocking trap Testing with WebTestClient Choosing between Spring MVC and WebFlux
How WebFlux handles a request
Spring MVC, the classic web stack, gives each request its own thread from a pool. The thread runs the controller, waits for the database or any remote call, writes the response, and only then returns to the pool. A server with 200 threads can therefore serve at most 200 requests that are waiting at the same moment.
Spring WebFlux takes a different approach. It runs on a non-blocking server, Reactor Netty by default, with a small, fixed number of event-loop threads. A handler does not return the result itself. It returns a MonoFlux
- Event loops: Reactor Netty starts
of them. Every connection is assigned to one, and that thread does all its I/O.max(CPU cores, 4) - Non-blocking all the way: the model only pays off when every call in the chain is non-blocking, such as
, R2DBC or reactive MongoDB. A single blocking call holds an event loop and every connection on it.WebClient - Backpressure: a
response is written as the client reads it, so a slow client slows the producer instead of filling memory.Flux
| Spring MVC | Spring WebFlux | |
|---|---|---|
| Spring Boot starter | spring-boot-starter-webmvc-web | spring-boot-starter-webflux |
| Default server | Tomcat | Reactor Netty |
| Threads | One per request, platform or virtual | A few event loops, plus schedulers for blocking work |
| Handler returns | The value | MonoFlux |
| Programming styles | @RestController | @RestController |
| Request data | ThreadLocal | Reactor Context |
| Test client | MockMvcRestTestClient | WebTestClient |
Every example on this page is a complete Spring Boot 4.1 application (Spring Framework 7.0) that starts Netty on a random port, calls itself with the JDK HttpClientspring-boot-starter-webfluxspring.main.web-application-type=reactive-parameters@PathVariable int id
Annotated controllers returning Mono and Flux
The annotation model is the same as in Spring MVC: @RestController@GetMapping@PathVariable@RequestBodyFluxMonoMono
package demo.annotated;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class AnnotatedController {
record Book(int id, String title) { }
record NewBook(String title) { }
@RestController
@RequestMapping("/books")
static class BookController {
private final Map<Integer, Book> books = new ConcurrentHashMap<>(Map.of(
1, new Book(1, "Dune"), 2, new Book(2, "Emma")));
private final AtomicInteger nextId = new AtomicInteger(3);
@GetMapping
Flux<Book> all() {
return Flux.fromIterable(books.values()).sort((a, b) -> a.id() - b.id());
}
@GetMapping("/{id}")
Mono<Book> one(@PathVariable int id) {
log("GET /books/" + id);
// a slow lookup that does not hold the thread while it waits
return Mono.justOrEmpty(books.get(id)).delayElement(Duration.ofMillis(50));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Mono<Book> add(@RequestBody Mono<NewBook> body) {
return body.map(b -> new Book(nextId.getAndIncrement(), b.title()))
.doOnNext(b -> books.put(b.id(), b));
}
private static void log(String what) {
String thread = Thread.currentThread().getName().replaceAll("-\\d+$", "-N");
System.out.println(" [server] " + what + " handled on " + thread);
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(AnnotatedController.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
System.out.println("Server type: "
+ context.getClass().getSimpleName());
call(HttpRequest.newBuilder(URI.create(base + "/books")).build());
call(HttpRequest.newBuilder(URI.create(base + "/books/2")).build());
call(HttpRequest.newBuilder(URI.create(base + "/books/9")).build());
call(HttpRequest.newBuilder(URI.create(base + "/books"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"title\":\"Ulysses\"}"))
.build());
call(HttpRequest.newBuilder(URI.create(base + "/books")).build());
}
}
static void call(HttpRequest request) throws Exception {
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(request.method() + " " + request.uri().getPath() + " -> "
+ response.statusCode() + " " + response.body());
}
}
}
Server type: AnnotationConfigReactiveWebServerApplicationContext
GET /books -> 200 [{"id":1,"title":"Dune"},{"id":2,"title":"Emma"}]
[server] GET /books/2 handled on reactor-http-epoll-N
GET /books/2 -> 200 {"id":2,"title":"Emma"}
[server] GET /books/9 handled on reactor-http-epoll-N
GET /books/9 -> 200
POST /books -> 201 {"id":3,"title":"Ulysses"}
GET /books -> 200 [{"id":1,"title":"Dune"},{"id":2,"title":"Emma"},{"id":3,"title":"Ulysses"}]
- The context class is
. Spring Boot found WebFlux and Netty on the classpath and started a reactive server.AnnotationConfigReactiveWebServerApplicationContext - The
was written as one JSON array. ForFlux<Book> , WebFlux collects the values and encodes them as an array.application/json was handled onGET /books/2 , a Netty event loop. On Linux Netty uses epoll; on macOS the name containsreactor-http-epoll-N ornio instead. The 50 mskqueue did not hold that thread: the delay runs on a timer.delayElement found nothing, so theGET /books/9 was empty, and WebFlux answered 200 with an empty body. That is rarely what an API wants; the error section below fixes it.Mono- The POST returned 201, set by
, with the generated id 3, and the list now holds three books.@ResponseStatus
The request body is read from a separate NewBookBooktools.jacksoncom.fasterxml.jackson
Functional endpoints with RouterFunction
WebFlux also offers a functional style: routes are declared in code as a RouterFunctionServerRequestMono<ServerResponse>
package demo.functional;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class FunctionalRoutes {
record Product(String sku, String name, int price) { }
static class ProductHandler {
private final List<Product> products = List.of(
new Product("A1", "kettle", 30), new Product("B2", "toaster", 45));
Mono<ServerResponse> list(ServerRequest request) {
int max = request.queryParam("maxPrice").map(Integer::parseInt)
.orElse(Integer.MAX_VALUE);
return ServerResponse.ok().bodyValue(
products.stream().filter(p -> p.price() <= max).toList());
}
Mono<ServerResponse> one(ServerRequest request) {
String sku = request.pathVariable("sku");
return products.stream().filter(p -> p.sku().equals(sku)).findFirst()
.map(p -> ServerResponse.ok().bodyValue(p))
.orElseGet(() -> ServerResponse.notFound().build());
}
}
@Bean
RouterFunction<ServerResponse> routes() {
ProductHandler handler = new ProductHandler();
return RouterFunctions.route()
.nest(path("/api/products"), builder -> builder
.GET("", handler::list)
.GET("/{sku}", handler::one))
.before(request -> {
System.out.println(" [filter] " + request.method() + " "
+ request.path());
return request;
})
.filter((request, next) -> request.headers().firstHeader("X-Api-Key") == null
? ServerResponse.status(HttpStatus.UNAUTHORIZED).build()
: next.handle(request))
.build();
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(FunctionalRoutes.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
get(base, "/api/products", true);
get(base, "/api/products?maxPrice=40", true);
get(base, "/api/products/B2", true);
get(base, "/api/products/Z9", true);
get(base, "/api/products", false);
}
}
static void get(String base, String path, boolean withKey) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
if (withKey) {
request.header("X-Api-Key", "secret");
}
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(request.build(),
HttpResponse.BodyHandlers.ofString());
System.out.println("GET " + path + (withKey ? "" : " (no key)") + " -> "
+ response.statusCode() + " " + response.body());
}
}
}
[filter] GET /api/products
GET /api/products -> 200 [{"sku":"A1","name":"kettle","price":30},{"sku":"B2","name":"toaster","price":45}]
[filter] GET /api/products
GET /api/products?maxPrice=40 -> 200 [{"sku":"A1","name":"kettle","price":30}]
[filter] GET /api/products/B2
GET /api/products/B2 -> 200 {"sku":"B2","name":"toaster","price":45}
[filter] GET /api/products/Z9
GET /api/products/Z9 -> 404
[filter] GET /api/products
GET /api/products (no key) -> 401
grouped two routes under one prefix: the list and the lookup by SKU.nest(path("/api/products"), ...) was read with?maxPrice=40 , which returns anrequest.queryParam , and kept only the kettle.Optional- The unknown SKU returned 404 from
. In the functional style, the handler builds the response status itself.ServerResponse.notFound() - The
step logged every request, and thebefore rejected the call without anfilter header with 401, before the handler ran.X-Api-Key
Both styles can live in the same application. Annotated controllers suit most CRUD APIs; functional routes suit applications that build routes dynamically or want the routing table in one place.
Streaming with server-sent events and NDJSON
A Flux
package demo.streaming;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@SpringBootApplication
public class StreamingResponses {
record Price(String symbol, int cents) { }
static final AtomicBoolean NDJSON_CANCELLED = new AtomicBoolean();
@RestController
static class PriceController {
// one price every 200 ms; the stream never ends on its own
private Flux<Price> prices() {
return Flux.interval(Duration.ofMillis(200))
.onBackpressureBuffer(100) // a timer cannot wait for a slow write
.map(i -> new Price("ACME", 1000 + (int) (i * 5)));
}
@GetMapping(value = "/prices", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ServerSentEvent<Price>> sse() {
return prices().map(p -> ServerSentEvent.builder(p)
.event("price").id(String.valueOf(p.cents())).build());
}
@GetMapping(value = "/prices.ndjson", produces = MediaType.APPLICATION_NDJSON_VALUE)
Flux<Price> ndjson() {
return prices().doOnCancel(() -> NDJSON_CANCELLED.set(true));
}
@GetMapping("/prices.json")
Flux<Price> json() {
return prices().take(3);
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(StreamingResponses.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args);
HttpClient client = HttpClient.newHttpClient()) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
System.out.println("text/event-stream, first 7 lines:");
HttpResponse<Stream<String>> sse = client.send(
HttpRequest.newBuilder(URI.create(base + "/prices")).build(),
HttpResponse.BodyHandlers.ofLines());
try (var lines = sse.body()) {
lines.limit(7).forEach(line -> System.out.println(" |" + line));
}
System.out.println("application/x-ndjson, first 3 lines:");
HttpResponse<Stream<String>> nd = client.send(
HttpRequest.newBuilder(URI.create(base + "/prices.ndjson")).build(),
HttpResponse.BodyHandlers.ofLines());
try (var lines = nd.body()) {
lines.limit(3).forEach(line -> System.out.println(" |" + line));
}
System.out.println("application/json, a finite Flux:");
HttpResponse<String> json = client.send(
HttpRequest.newBuilder(URI.create(base + "/prices.json")).build(),
HttpResponse.BodyHandlers.ofString());
System.out.println(" " + json.headers().firstValue("Content-Type").orElse("")
+ " " + json.body());
Thread.sleep(300); // give the server a moment to notice the closed stream
System.out.println("Server saw the ndjson client cancel: " + NDJSON_CANCELLED.get());
}
}
}
text/event-stream, first 7 lines:
|id:1000
|event:price
|data:{"symbol":"ACME","cents":1000}
|
|id:1005
|event:price
|data:{"symbol":"ACME","cents":1005}
application/x-ndjson, first 3 lines:
|{"symbol":"ACME","cents":1000}
|{"symbol":"ACME","cents":1005}
|{"symbol":"ACME","cents":1010}
application/json, a finite Flux:
application/json [{"symbol":"ACME","cents":1000},{"symbol":"ACME","cents":1005},{"symbol":"ACME","cents":1010}]
Server saw the ndjson client cancel: true
produced the server-sent events format: antext/event-stream , anid: and aevent: line per event, followed by a blank line. Browsers read it withdata: , which reconnects on its own and sends the lastEventSource back in aid header.Last-Event-ID- The
afteronBackpressureBuffer(100) matters. WebFlux requests one element at a time while it writes, and a timer cannot wait. Without the buffer, an early tick that arrived while the first write was still in progress (class loading makes the first write slow) failed the stream withFlux.interval in one of the test runs for this page, after the 200 status had already been sent.OverflowException: Could not emit tick 1 wrote one JSON object per line, which suits service-to-service streams.application/x-ndjson- When the client stopped reading after 3 lines and closed the stream, the server saw a cancel signal, as the last line shows. The interval stopped; nothing kept producing prices for a client that had gone.
- The plain
endpoint had to wait for the wholeapplication/json to complete before it could close the array. UsingFlux made it finite. An endlesstake(3) withFlux would never finish the response.application/json
Error handling: empty results, status codes and ProblemDetail
Errors in WebFlux travel as error signals in the MonoFlux@ExceptionHandler@RestControllerAdvicespring.webflux.problemdetails.enabled=true
package demo.errors;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
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.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class WebFluxErrors {
record Account(String id, int balance) { }
static class AccountLocked extends RuntimeException {
AccountLocked(String id) {
super("account " + id + " is locked");
}
}
@RestController
static class AccountController {
private Mono<Account> find(String id) {
return switch (id) {
case "a1" -> Mono.just(new Account("a1", 100));
case "locked" -> Mono.error(new AccountLocked(id));
default -> Mono.empty();
};
}
@GetMapping("/v1/accounts/{id}")
Mono<Account> naive(@PathVariable String id) {
return find(id);
}
@GetMapping("/v2/accounts/{id}")
Mono<Account> checked(@PathVariable String id) {
return find(id).switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND, "no account " + id)));
}
@GetMapping("/v2/crash")
Mono<Account> crash() {
return Mono.fromCallable(() -> {
throw new IllegalStateException("database password is hunter2");
});
}
}
@RestControllerAdvice
static class Handlers {
@ExceptionHandler
ProblemDetail locked(AccountLocked e) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
e.getMessage());
problem.setTitle("Account locked");
return problem;
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(WebFluxErrors.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "OFF",
"spring.webflux.problemdetails.enabled", "true"));
try (var context = app.run(args)) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
for (String path : new String[] {"/v1/accounts/a1", "/v1/accounts/zz",
"/v2/accounts/zz", "/v2/accounts/locked", "/v2/crash"}) {
get(base, path);
}
}
}
static void get(String base, String path) throws Exception {
try (HttpClient client = HttpClient.newHttpClient()) {
HttpResponse<String> response = client.send(
HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.ofString());
// drop the fields that change on every run
String body = response.body()
.replaceAll(",?\"(requestId|timestamp)\":\"[^\"]*\"", "")
.replace("{,", "{");
System.out.println("GET " + path + " -> " + response.statusCode()
+ (body.isEmpty() ? " (empty body)" : "\n " + body));
}
}
}
GET /v1/accounts/a1 -> 200
{"id":"a1","balance":100}
GET /v1/accounts/zz -> 200 (empty body)
GET /v2/accounts/zz -> 404
{"detail":"no account zz","instance":"/v2/accounts/zz","status":404,"title":"Not Found"}
GET /v2/accounts/locked -> 409
{"detail":"account locked is locked","instance":"/v2/accounts/locked","status":409,"title":"Account locked"}
GET /v2/crash -> 500
{"path":"/v2/crash","status":500,"error":"Internal Server Error"}
returned 200 with an empty body, because the lookup produced an empty/v1/accounts/zz and nothing turned it into an error.Mono adds/v2 , so the same lookup returned 404 with a problem detail body naming the account.switchIfEmpty(Mono.error(new ResponseStatusException(NOT_FOUND, ...)))- The
error reached theAccountLocked in the advice class, which returned a@ExceptionHandler with status 409 and a custom title.ProblemDetail - The unexpected
became a 500 from Spring Boot's default error handler. Its message, which contains a password here, was not sent to the client: Boot leaves the message out unless you configure it otherwise.IllegalStateException
The program prints the bodies without the timestamprequestId
The blocking trap
A blocking call on an event loop does not fail. It quietly holds the thread, and every other connection assigned to that loop waits. This program makes it visible: one endpoint calls block()Schedulers.boundedElastic()
package demo.blocking;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
@SpringBootApplication
public class BlockingTrap {
static String slowLegacyCall() {
try {
Thread.sleep(300); // a JDBC query or a blocking SDK call
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "done";
}
@RestController
static class SlowController {
@GetMapping("/block")
Mono<String> callsBlock() {
try {
String value = Mono.delay(Duration.ofMillis(10)).thenReturn("x").block();
return Mono.just(value);
} catch (IllegalStateException e) {
return Mono.just(e.getMessage().replaceAll("-\\d+$", "-N"));
}
}
@GetMapping("/sleep-on-event-loop")
Mono<String> sleepsOnEventLoop() {
return Mono.just(slowLegacyCall());
}
@GetMapping("/sleep-offloaded")
Mono<String> offloaded() {
return Mono.fromCallable(BlockingTrap::slowLegacyCall)
.subscribeOn(Schedulers.boundedElastic());
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(BlockingTrap.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "OFF"));
try (var context = app.run(args);
HttpClient client = HttpClient.newHttpClient()) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
HttpResponse<String> blocked = client.send(
HttpRequest.newBuilder(URI.create(base + "/block")).build(),
HttpResponse.BodyHandlers.ofString());
System.out.println("GET /block -> " + blocked.statusCode() + " " + blocked.body());
int requests = 16;
System.out.println(requests + " concurrent requests, each with a 300 ms blocking call"
+ " (rough comparison, best of 3, " + Runtime.getRuntime()
.availableProcessors() + "-core container):");
for (String path : List.of("/sleep-on-event-loop", "/sleep-offloaded")) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
best = Math.min(best, timeConcurrent(base + path, requests));
}
System.out.printf(" %-22s about %d ms%n", path,
Math.round(best / 100.0) * 100);
}
}
}
static long timeConcurrent(String url, int count) {
long start = System.nanoTime();
List<CompletableFuture<?>> futures = new ArrayList<>();
for (int i = 0; i < count; i++) {
// a separate client per request, so each one gets its own connection
HttpClient client = HttpClient.newHttpClient();
futures.add(client.sendAsync(HttpRequest.newBuilder(URI.create(url)).build(),
HttpResponse.BodyHandlers.ofString()).whenComplete((r, e) -> client.close()));
}
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
return (System.nanoTime() - start) / 1000000;
}
}
GET /block -> 200 block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-epoll-N
16 concurrent requests, each with a 300 ms blocking call (rough comparison, best of 3, 2-core container):
/sleep-on-event-loop about 1300 ms
/sleep-offloaded about 400 ms
- Calling
on an event-loop thread threwblock() . Reactor refuses because waiting there could deadlock the server. The handler caught it and returned the message, which names the thread.IllegalStateException is not detected. With 4 event loops on this 2-core container and 16 requests, the requests queued behind each other in groups of 4, so the batch took at least four times 300 ms.Thread.sleep- Moving the call to
, which can grow to 20 threads here, let all 16 calls wait in parallel. The batch took well under half the time, close to a single call plus the cost of 16 new connections.boundedElastic()
The measurements are a rough comparison, best of 3 runs on a 2-core Linux container, rounded to 100 ms. The ratio is the point: the cost of blocking grows with the number of concurrent requests. Wrap unavoidable blocking calls such as JDBC in Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic())publishOnsubscribeOn
Testing with WebTestClient
WebTestClientspring-test@SpringBootTest
package demo.testing;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
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.server.ResponseStatusException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class WebTestClientDemo {
record City(String code, String name) { }
@RestController
static class CityController {
private final List<City> cities = List.of(new City("PAR", "Paris"),
new City("ROM", "Rome"));
@GetMapping("/cities")
Flux<City> all() {
return Flux.fromIterable(cities);
}
@GetMapping("/cities/{code}")
Mono<City> one(@PathVariable String code) {
return Flux.fromIterable(cities).filter(c -> c.code().equals(code)).next()
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
}
public static void main(String[] args) {
// No server and no port: requests go straight into the WebFlux handler chain
WebTestClient client = WebTestClient.bindToController(new CityController()).build();
client.get().uri("/cities").accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBodyList(City.class).hasSize(2).contains(new City("ROM", "Rome"));
System.out.println("GET /cities: 200 with 2 cities, Rome included");
client.get().uri("/cities/PAR").exchange()
.expectStatus().isOk()
.expectBody().jsonPath("$.name").isEqualTo("Paris");
System.out.println("GET /cities/PAR: name is Paris");
client.get().uri("/cities/XXX").exchange().expectStatus().isNotFound();
System.out.println("GET /cities/XXX: 404");
try {
client.get().uri("/cities/ROM").exchange()
.expectBody().jsonPath("$.name").isEqualTo("Roma");
} catch (AssertionError e) {
System.out.println("Failed check: " + e.getMessage());
}
}
}
GET /cities: 200 with 2 cities, Rome included
GET /cities/PAR: name is Paris
GET /cities/XXX: 404
Failed check: JSON path "$.name" expected:<Roma> but was:<Rome>
decoded the JSON array and checked its size and one element.expectBodyList(City.class) checked a single field without a target class.jsonPath("$.name")- The 404 came from the
in the handler, handled by the same exception handling as in a real server.ResponseStatusException - The deliberately wrong check threw an
naming the path, the expected value and the actual one, which is what a test runner reports.AssertionError
For handlers that return long or infinite streams, take the body as a FluxreturnResult(City.class).getResponseBody()StepVerifier@WebFluxTest
Choosing between Spring MVC and WebFlux
| Situation | Better fit | Why |
|---|---|---|
| CRUD API over JDBC or JPA | Spring MVC | The data access is blocking; WebFlux would only add scheduler hops |
| Many slow remote calls per request, high concurrency | WebFlux, or MVC with virtual threads | Neither ties up a platform thread while waiting |
| Streaming to clients: SSE, NDJSON, long-lived connections | WebFlux | Backpressure and cancellation are built in |
| Gateway or proxy that mostly forwards traffic | WebFlux | Fully non-blocking I/O end to end |
| Team new to reactive programming | Spring MVC | Stack traces, debugging and ThreadLocal |
| Calling reactive APIs from an MVC application | Spring MVC plus WebClientRestClient | MVC controllers may return MonoFlux |
Since Java 21, virtual threads make the thread-per-request model cheap for blocking code, which removes WebFlux's main advantage for typical database-backed services. WebFlux remains the better tool for streaming, for fan-out to many services and for applications that are reactive end to end. To call other services from either stack, see