Sub topic 6
How WebFlux runs requests: the event loop and Netty
This chapter explains what happens between a socket receiving bytes and your controller method returning a Mono. It assumes you know Java lambdas and generics, basic Spring Boot (beans, @RestController), HTTP and REST, and the thread-per-request model. You should also have met Mono and Flux in earlier chapters.
By the end you should be able to say how many threads WebFlux uses, which thread runs your code, and why one blocking call can hurt the whole server.
The thread-per-request model, briefly
Spring MVC on a servlet container such as Tomcat assigns one worker thread to each request. That thread reads the request, runs your controller, waits for the database or a remote service, and writes the response. While it waits, it holds its stack memory and does no useful work.
Under heavy load with slow dependencies, the worker pool fills up. Tomcat's default maximum is 200 threads, so the 201st concurrent request waits in a queue even if the CPU is nearly idle.
WebFlux changes the unit of work. A request is no longer tied to one thread for its whole life. Instead, a small, fixed set of threads runs short pieces of work, and a piece never waits for I/O.
The event loop
An event loop is a thread that repeatedly checks a set of connections for events (new data arrived, a socket is writable, a connection closed) and runs a handler for each event. The handler must finish quickly. Then the loop moves to the next event.
Each event-loop thread can serve many connections because a connection that is waiting costs only a small object in memory, not a blocked thread.
The key rule follows from this picture: a handler must never block. If a handler sleeps for 500 ms, every connection assigned to that thread is frozen for 500 ms.
Netty as the default server
Spring Boot's spring-boot-starter-webflux includes Netty, an asynchronous network framework that implements the event loop. Reactor Netty is the Project Reactor wrapper that exposes Netty through Mono and Flux. WebFlux uses it by default.
Netty has these main parts:
- A boss group accepts new connections.
- A worker group (also called the event-loop group) handles reads, writes, and your pipeline.
- Each connection is bound to one event-loop thread for its lifetime. That thread performs all I/O on it, so connection state needs no locks.
Reactor Netty sizes the worker group at the number of available CPU cores, with a minimum of 4. You can see this in thread names such as reactor-http-nio-1. The nio part means Java NIO selectors drive the loop.
Because there are only a few of these threads, every one is precious. This is the main design constraint of WebFlux.
Other supported servers
WebFlux is not tied to Netty. It also runs on Undertow, Tomcat, and Jetty through Servlet 3.1+ non-blocking I/O. Netty is the default because it was designed for this model and needs no servlet layer. If you swap servers, thread names and thread counts change, but the rule about never blocking stays the same.
Following one request
Take this endpoint:
@GetMapping("/{id}")
public Mono<Book> get(@PathVariable String id) {
return repository.findById(id);
}The steps are:
- Netty accepts the TCP connection and binds it to an event-loop thread, say
reactor-http-nio-2. - That thread reads bytes and decodes the HTTP request.
- WebFlux's
DispatcherHandlerpicks the handler method, much asDispatcherServletdoes in MVC. - Your method runs on the same thread. It builds a
Monoand returns it quickly. Nothing has fetched the book yet. - WebFlux subscribes to the
Mono. The reactive driver sends the query over a non-blocking socket and registers interest in the reply. The thread is now free. - Other requests run on that thread while the database works.
- When the reply arrives, an event fires. A thread (often the driver's or the same event loop) pushes the
Bookthrough the pipeline, the encoder writes JSON, and Netty sends it.
Step 4 is the most common source of confusion. Your controller method returns almost immediately. The work happens later, when the subscriber requests data. Code you write directly in the method body, outside the pipeline, runs on the event loop at assembly time.
Which thread runs your code?
By default, Reactor does not create threads. The thread that triggers a signal runs the downstream operators. For a database call, that is usually a thread owned by the driver's client, or the event loop if the driver reuses it.
You can check this:
@GetMapping("/where")
public Mono<String> where() {
String assembly = Thread.currentThread().getName();
return Mono.fromSupplier(() -> {
String execution = Thread.currentThread().getName();
return "assembly=" + assembly + ", execution=" + execution;
});
}With Netty, both values will normally be a reactor-http-nio-N name. This shows that even your lambda runs on the event loop unless you move it.
Two consequences follow:
- Operators like
mapandfilterrun on whatever thread delivered the signal. Keep them short and CPU-light. - Do not store per-request data in
ThreadLocalvariables. The same request may be handled by different threads at different steps. Reactor'sContextcarries request-scoped data instead.
What happens when you block
Suppose a handler calls a legacy client that takes one second:
@GetMapping("/bad")
public Mono<String> bad() {
String result = legacyClient.slowCall(); // blocks the event loop
return Mono.just(result);
}With 8 event-loop threads, 8 concurrent calls to /bad freeze the whole server for a second. Health checks time out, and unrelated endpoints stop answering. CPU use stays low, so ordinary monitoring may show nothing wrong.
Common sources of hidden blocking:
- JDBC, JPA, and other blocking database drivers
Thread.sleep, blocking file I/O,InputStream.readon slow sources- Calling
.block(),.toFuture().get(), or.blockFirst()inside a pipeline - Synchronized sections under contention
- Heavy CPU work such as large JSON transforms or password hashing
Reactor helps you catch some of these. Reactor's block() throws IllegalStateException ("block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2") when called on a non-blocking thread. The library BlockHound can detect many other blocking calls in tests.
Mono<String> good = Mono
.fromCallable(() -> legacyClient.slowCall())
.subscribeOn(Schedulers.boundedElastic());subscribeOn(Schedulers.boundedElastic()) moves the blocking work to a separate thread pool made for it. The event loop stays free. Later chapters cover schedulers in detail.
Setting a different thread model
You rarely need to tune Netty, but you can. Two common cases:
- Changing the worker thread count with a system property, set before the application starts:
-Dreactor.netty.ioWorkerCount=16. - Customizing the server in code:
@Configuration
public class NettyConfig {
@Bean
NettyReactiveWebServerFactory nettyFactory() {
NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory();
factory.addServerCustomizers(server -> server.accessLog(true));
return factory;
}
}Adding more event-loop threads does not fix blocking. It only delays the point where all threads are stuck.
Trade-offs
WebFlux does not make requests faster. A single request often takes the same time, or slightly longer, because of the extra machinery. The benefit is that the server holds many concurrent, slow, I/O-bound requests with few threads and little memory.
| Situation | Better fit |
|---|---|
| Many concurrent connections, slow downstream calls, streaming | WebFlux |
| Blocking JDBC or JPA throughout | Spring MVC |
| CPU-heavy work per request | Either, with work offloaded to a separate pool |
| Team new to reactive, modest traffic | Spring MVC |
Modern Java versions with virtual threads (Java 21+) also reduce the cost of blocking in MVC. This narrows WebFlux's advantage for plain request-response APIs. WebFlux remains strong for streaming and backpressure-aware pipelines.
Common errors
- Calling
.block()in a controller or service. It throws on Netty threads, or silently stalls on others. Return theMonoinstead. - Doing blocking work in
map.mapruns on the signal's thread. Wrap blocking calls infromCallableplussubscribeOn. - Expecting the method body to run the query. Without a subscriber, nothing runs. The framework subscribes for you only when you return the publisher.
- Using
ThreadLocal. Values set on one thread are missing on the next. - Adding
spring-boot-starter-webalongside the WebFlux starter. Spring Boot then starts the servlet stack (MVC) and WebFlux is not used for serving. Pick one server stack.
Exercise
An endpoint calls a blocking JDBC repository inside a map operator. Under 50 concurrent requests the server stops responding, although CPU use is about 5%. Explain why, and show one way to fix the call.
Show answer
The map operator runs on the event-loop thread that delivered the signal. The JDBC call blocks that thread, and there are only a few event-loop threads (the CPU core count, minimum 4). Once all are blocked, no other request can be read or answered, while the CPU stays idle. Fix it by moving the blocking call off the event loop: use Mono.fromCallable(() -> jdbcRepository.find(id)).subscribeOn(Schedulers.boundedElastic()), and chain the rest of the pipeline from there. A longer-term fix is a reactive driver such as R2DBC.
Exercise
A controller method contains Thread.currentThread().getName() outside any lambda and returns a Mono. On which thread does that line run, and when?
Show answer
It runs on the event-loop thread (for example reactor-http-nio-3) at assembly time, when the controller method is called, before anything subscribes to the returned Mono.