Sub topic 1
Why reactive? Blocking vs non-blocking request handling
This chapter explains the problem that Spring WebFlux solves. You will see how a traditional server spends its threads, why that becomes costly under load, and how a non-blocking server handles the same work with far fewer threads. You will also learn when WebFlux is the wrong choice.
Prerequisites
This chapter assumes you already know the following:
- Java fundamentals, including lambdas and generics.
- Basic Spring Boot: beans, dependency injection, and
@RestController. - HTTP and REST concepts such as methods, status codes, and request and response bodies.
- What a thread is, and the thread-per-request model in a servlet container such as Tomcat.
You do not need any prior knowledge of Reactor or reactive programming. Later chapters introduce those.
The thread-per-request model
Spring MVC runs on a servlet container. Tomcat takes each incoming request and assigns it to one thread from a pool. By default Spring Boot sets that pool to 200 threads (server.tomcat.threads.max). The thread runs your controller, calls your services, and writes the response. It is not released until the request finishes.
This model is easy to reason about:
- Code reads top to bottom.
- A stack trace shows the whole call path.
- Thread-bound features such as
ThreadLocal, transaction context, and the security context work without extra effort.
The model works well while threads spend their time computing. The trouble starts when they spend it waiting.
Where a request spends its time
A typical request does little CPU work. It parses a path, calls a database, calls another service, and serializes JSON. Most of the elapsed time is I/O wait, where the thread sits idle until bytes come back.
Suppose a handler takes 500 ms, and 480 ms of that is waiting on a downstream HTTP call. A blocking thread holds its stack, its scheduler slot, and its place in the pool for the whole 500 ms, yet it does useful work for about 20 ms.
You can estimate the ceiling with a simple relationship: maximum throughput is roughly the number of threads divided by the time each request holds a thread.
| Threads | Time per request | Maximum throughput |
|---|---|---|
| 200 | 500 ms | 400 requests per second |
| 200 | 50 ms | 4,000 requests per second |
| 200 | 5 s (slow downstream) | 40 requests per second |
The last row shows the failure mode. When a downstream service slows down, each request holds its thread longer. The pool fills, new requests queue, and latency rises for every endpoint on the server, including endpoints that do not use the slow service.
Adding threads helps only to a point. Each platform thread reserves stack memory (commonly around 1 MB of address space), and the operating system pays a cost to switch between thousands of them.
The non-blocking model
A non-blocking server separates "waiting for I/O" from "holding a thread". When your code starts an I/O operation, it registers what should happen when the result arrives and returns immediately. The thread is free to serve other requests. When the data arrives, a thread picks up the continuation and runs it.
WebFlux runs on this model. By default it uses Reactor Netty, which has a small fixed set of event-loop threads, typically about one per CPU core. Each event-loop thread handles many connections by reacting to I/O events as they occur.
The cost of this model is in how you write code. You cannot write User user = callService(); and expect the result on the next line, because the result does not exist yet. Instead, the call returns a placeholder for a future value, and you describe what to do with it. In Reactor, that placeholder is a Mono (zero or one value) or a Flux (zero to many values). Later chapters cover both in detail.
A side-by-side example
Both controllers below return a user fetched from another service. The first is the blocking version in Spring MVC. The second is the non-blocking version in WebFlux. They belong to two separate applications, because one application runs on one stack.
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.client.RestTemplate;
record User(String id, String name) {}
@RestController
public class BlockingUserController {
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping("/users/{id}")
public User get(@PathVariable String id) {
// The calling thread is parked here until the response arrives.
return restTemplate.getForObject(
"https://api.example.com/users/{id}", User.class, id);
}
}import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
record User(String id, String name) {}
@RestController
public class ReactiveUserController {
private final WebClient client = WebClient.create("https://api.example.com");
@GetMapping("/users/{id}")
public Mono<User> get(@PathVariable String id) {
// Returns immediately with a description of the work.
// The framework subscribes to it and writes the response when the value arrives.
return client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class);
}
}Compare the two method signatures. The blocking method returns a User, so it must have the value before it returns. The reactive method returns a Mono<User>, so it can return before the value exists. The method does not perform the call. It builds a description of the call, and the framework runs it.
What you gain and what you pay
Non-blocking handling changes the resource profile of a service, and it also changes how you work.
| Aspect | Blocking (Spring MVC) | Non-blocking (WebFlux) |
|---|---|---|
| Threads under load | Grows with concurrent requests, up to the pool limit | Stays small and roughly constant |
| Memory per waiting request | A full thread stack | A small object on the heap |
| Slow downstream service | Pool fills, queue builds | Pending requests cost little, so concurrency can keep growing |
| Code style | Sequential, easy to step through | Declarative pipelines |
| Debugging | Stack traces show the full path | Stack traces are fragmented across operators |
| `ThreadLocal` and similar context | Works as expected | Unreliable, because work can move between threads |
| Blocking libraries (JDBC, many SDKs) | Natural fit | Must be isolated, or they stall the event loop |
The last row is the most important gotcha. An event loop with eight threads can stall when eight requests each call a blocking method. A blocking call on an event-loop thread is worse than a blocking call on a Tomcat thread, because the loop serves many other connections. A later chapter shows how to find and isolate such calls.
When WebFlux is a good fit
WebFlux pays off when these conditions hold:
- The service is I/O-bound and spends most of its time waiting on other services, with high concurrency.
- Much of the work is fan-out: one request calls several services and combines the results.
- You stream data, such as Server-Sent Events, or you handle many long-lived connections.
- The whole call chain, including the data store, has a non-blocking driver (for example reactive drivers for MongoDB, Redis, Cassandra, or R2DBC for relational databases).
When it is not a good fit
Choose Spring MVC when these conditions hold:
- The service is CPU-bound. Non-blocking I/O does not make computation faster.
- Your main data access uses JDBC or JPA. They block, so a reactive web layer on top gains little.
- Traffic is modest. A pool of 200 threads handles a lot of requests, and the team's familiarity with imperative code has real value.
- The team has no experience with reactive code. Debugging it is harder.
Java 21 also offers virtual threads, and Spring Boot 3.2 and later can run MVC on them (spring.threads.virtual.enabled=true). Virtual threads let you keep sequential blocking code while parking cheaply during I/O. They remove much of the thread-cost argument for WebFlux. WebFlux still has advantages that virtual threads do not give you: stream composition, backpressure, and a streaming-first API. Decide on the actual need, not on fashion.
Common errors at this stage
- Expecting WebFlux to make a single request faster. It improves how many requests you can hold at once. One request still waits as long as the downstream call takes.
- Mixing a blocking driver into a reactive stack without isolation. The service passes light tests and then stalls under load.
- Assuming
Monomeans "runs in another thread". AMonodescribes work. Which thread runs it depends on the operators and Schedulers involved. - Adding both
spring-boot-starter-webandspring-boot-starter-webflux. Spring Boot then configures Spring MVC and ignores the reactive server. If you want a reactive server, keep only the WebFlux starter.
Exercise
A Spring MVC service has 200 request threads. Every request calls a downstream service that takes 400 ms, and the rest of the handler takes about 10 ms. Roughly what is the maximum throughput, and what happens to it if the downstream service slows to 2 seconds? Name one situation where moving to WebFlux would not help.
Show answer
Each request holds a thread for about 410 ms, so the ceiling is about 200 / 0.41, or roughly 490 requests per second. If the downstream call takes 2 seconds, each request holds a thread for about 2.01 s, so the ceiling drops to about 100 requests per second, and queued requests see rising latency. WebFlux would not help if the service is CPU-bound, or if it depends mainly on blocking JDBC or JPA access that has no reactive driver, because the blocking calls would still occupy threads (and on an event loop they would stall it).