Sub topic 2
How WebFlux Runs Requests: The Event Loop and Netty
Assume Java, Spring Boot, HTTP, dependency injection, and thread-per-request servers. WebFlux uses Project Reactor and Netty to handle many requests with a small number of threads.
The Event Loop and Netty
Netty is the network server used by WebFlux by default. Its event-loop threads watch sockets for events, such as incoming data or a completed connection. A thread starts work, registers asynchronous operations, and handles callbacks instead of waiting for each operation to finish.
This model works when request code stays non-blocking. A database driver or HTTP client must return a publisher rather than make the event-loop thread wait.
Annotated Controllers
An annotated controller can return Mono, which represents zero or one result, or Flux, which represents zero or many results. WebFlux subscribes to the returned publisher and writes its signals to the HTTP response.
@RestController
@RequestMapping("/books")
class BookController {
private final BookRepository repository;
BookController(BookRepository repository) {
this.repository = repository;
}
@GetMapping
Flux<Book> list() {
return repository.findAll();
}
@GetMapping("/{id}")
Mono<Book> get(@PathVariable String id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
}The method does not fetch data before returning. It builds a pipeline that runs when WebFlux subscribes.
Functional Endpoints
Functional endpoints separate routing from request handling. A RouterFunction matches a request, and a handler returns Mono<ServerResponse>.
@Bean
RouterFunction<ServerResponse> routes(BookHandler handler) {
return RouterFunctions.route()
.GET("/books/{id}", handler::get)
.build();
}Use this style when explicit routing and small, composable handlers are more useful than annotations.
Reactive Repositories and Errors
Reactive repositories return Mono and Flux, so the data-access operation remains part of the pipeline. Operators such as flatMap compose dependent asynchronous work. Use onErrorResume for a controlled fallback, and map expected failures to suitable HTTP status responses. Do not hide every error as an empty result, because that can turn a server failure into a misleading 404.
Exercise
Why can a blocking repository call harm unrelated WebFlux requests?
Show answer
It occupies an event-loop thread while waiting, preventing that thread from processing other connections.