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

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 Mono or a Flux that describes how the result will be produced, and returns at once. While the result is pending, the event loop serves other connections. When the data arrives, Netty writes it to the socket, on whichever event loop owns that connection.

  • Event loops: Reactor Netty starts max(CPU cores, 4) of them. Every connection is assigned to one, and that thread does all its I/O.
  • Non-blocking all the way: the model only pays off when every call in the chain is non-blocking, such as WebClient, R2DBC or reactive MongoDB. A single blocking call holds an event loop and every connection on it.
  • Backpressure: a Flux response is written as the client reads it, so a slow client slows the producer instead of filling memory.
Spring's two web stacks
Spring MVCSpring WebFlux
Spring Boot starterspring-boot-starter-webmvc (-web in Boot 3)spring-boot-starter-webflux
Default serverTomcatReactor Netty
ThreadsOne per request, platform or virtualA few event loops, plus schedulers for blocking work
Handler returnsThe valueMono or Flux
Programming styles@RestController, functional routes@RestController, functional routes
Request dataThreadLocal worksReactor Context
Test clientMockMvc, RestTestClientWebTestClient

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 HttpClient, prints each request and response, and shuts down. The classpath holds only spring-boot-starter-webflux. If both the MVC and WebFlux starters are present, Boot starts MVC, so add WebFlux on its own or set spring.main.web-application-type=reactive. The programs are compiled with -parameters, as the Spring Boot Maven and Gradle plugins do, so that @PathVariable int id finds its name.

Annotated controllers returning Mono and Flux

The annotation model is the same as in Spring MVC: @RestController, @GetMapping, @PathVariable, @RequestBody. Only the return types change. This book service returns a Flux for the list, a Mono for one book with a simulated 50 ms lookup, and reads the POST body as a Mono:

Java
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());
        }
    }
}
Output
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 AnnotationConfigReactiveWebServerApplicationContext. Spring Boot found WebFlux and Netty on the classpath and started a reactive server.
  • The Flux<Book> was written as one JSON array. For application/json, WebFlux collects the values and encodes them as an array.
  • GET /books/2 was handled on reactor-http-epoll-N, a Netty event loop. On Linux Netty uses epoll; on macOS the name contains nio or kqueue instead. The 50 ms delayElement did not hold that thread: the delay runs on a timer.
  • GET /books/9 found nothing, so the Mono was empty, and WebFlux answered 200 with an empty body. That is rarely what an API wants; the error section below fixes it.
  • The POST returned 201, set by @ResponseStatus, with the generated id 3, and the list now holds three books.

The request body is read from a separate NewBook record that has only a title. Accepting the full Book record would let clients choose their own ids. Spring Boot 4 serializes JSON with Jackson 3, whose packages start with tools.jackson instead of com.fasterxml.jackson.

Functional endpoints with RouterFunction

WebFlux also offers a functional style: routes are declared in code as a RouterFunction bean, and each route points to a handler function that takes a ServerRequest and returns a Mono<ServerResponse>. Everything is explicit, with no annotation scanning, which makes routes easy to compose and filter. This product API checks for an API key in a filter:

Java
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());
        }
    }
}
Output
[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
  • nest(path("/api/products"), ...) grouped two routes under one prefix: the list and the lookup by SKU.
  • ?maxPrice=40 was read with request.queryParam, which returns an Optional, and kept only the kettle.
  • The unknown SKU returned 404 from ServerResponse.notFound(). In the functional style, the handler builds the response status itself.
  • The before step logged every request, and the filter rejected the call without an X-Api-Key header with 401, before the handler ran.

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 does not have to end. When the response media type is a streaming type, WebFlux writes each element as soon as it is emitted and keeps the connection open. The price feed below emits one price every 200 ms, forever:

Java
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());
        }
    }
}
Output
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
  • text/event-stream produced the server-sent events format: an id:, an event: and a data: line per event, followed by a blank line. Browsers read it with EventSource, which reconnects on its own and sends the last id back in a Last-Event-ID header.
  • The onBackpressureBuffer(100) after Flux.interval 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 with OverflowException: Could not emit tick 1 in one of the test runs for this page, after the 200 status had already been sent.
  • application/x-ndjson wrote one JSON object per line, which suits service-to-service streams.
  • 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 application/json endpoint had to wait for the whole Flux to complete before it could close the array. Using take(3) made it finite. An endless Flux with application/json would never finish the response.

Error handling: empty results, status codes and ProblemDetail

Errors in WebFlux travel as error signals in the Mono or Flux, and the same @ExceptionHandler and @RestControllerAdvice mechanisms as in MVC turn them into responses. This account API shows the common cases, with RFC 9457 problem details switched on by spring.webflux.problemdetails.enabled=true:

Java
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));
        }
    }
}
Output
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"}
  • /v1/accounts/zz returned 200 with an empty body, because the lookup produced an empty Mono and nothing turned it into an error.
  • /v2 adds switchIfEmpty(Mono.error(new ResponseStatusException(NOT_FOUND, ...))), so the same lookup returned 404 with a problem detail body naming the account.
  • The AccountLocked error reached the @ExceptionHandler in the advice class, which returned a ProblemDetail with status 409 and a custom title.
  • The unexpected IllegalStateException 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.

The program prints the bodies without the timestamp and requestId fields of the default error response, because those change on every run. Exception handling for the servlet stack is covered on the exception handling page; the annotations behave the same way here.

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(), and two others make the same 300 ms blocking call, one directly and one moved to Schedulers.boundedElastic(). Sixteen requests are sent at once to each:

Java
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;
    }
}
Output
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 block() on an event-loop thread threw IllegalStateException. Reactor refuses because waiting there could deadlock the server. The handler caught it and returned the message, which names the thread.
  • Thread.sleep 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.
  • Moving the call to boundedElastic(), 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.

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()). If most of an application's calls are blocking, Spring MVC with virtual threads is the simpler choice. The Reactor operators page explains publishOn, subscribeOn and the scheduler sizes.

Testing with WebTestClient

WebTestClient, from spring-test, sends requests to WebFlux handlers and checks the responses with a fluent API. Bound to a controller, it needs no server and no port: requests go straight into the WebFlux handler chain. In a @SpringBootTest it can also call a running server.

Java
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());
        }
    }
}
Output
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>
  • expectBodyList(City.class) decoded the JSON array and checked its size and one element.
  • jsonPath("$.name") checked a single field without a target class.
  • The 404 came from the ResponseStatusException in the handler, handled by the same exception handling as in a real server.
  • The deliberately wrong check threw an AssertionError naming the path, the expected value and the actual one, which is what a test runner reports.

For handlers that return long or infinite streams, take the body as a Flux with returnResult(City.class).getResponseBody() and check it with StepVerifier. The Spring testing page covers test slices such as @WebFluxTest.

Choosing between Spring MVC and WebFlux

When each stack fits
SituationBetter fitWhy
CRUD API over JDBC or JPASpring MVCThe data access is blocking; WebFlux would only add scheduler hops
Many slow remote calls per request, high concurrencyWebFlux, or MVC with virtual threadsNeither ties up a platform thread while waiting
Streaming to clients: SSE, NDJSON, long-lived connectionsWebFluxBackpressure and cancellation are built in
Gateway or proxy that mostly forwards trafficWebFluxFully non-blocking I/O end to end
Team new to reactive programmingSpring MVCStack traces, debugging and ThreadLocal work as usual
Calling reactive APIs from an MVC applicationSpring MVC plus WebClient or RestClientMVC controllers may return Mono and Flux too

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 Spring WebClient; for a reactive database, Spring Data R2DBC; for the servlet stack, building REST controllers with Spring MVC.