Spring WebFlux Server Styles & Async Results
In this article
Spring WebFlux supports two server styles — Reactor Netty (the default) and Servlet 3.1+ containers like Tomcat or Jetty — and both handle async results through a reactive pipeline that returns Mono or Flux types. You choose a style based on your existing infrastructure and performance needs, and WebFlux abstracts the async handling so your controller code stays the same regardless of the server.
Background: Reactive Programming and WebFlux
Spring WebFlux is the reactive-stack web framework introduced in Spring 5. It is built on Project Reactor, which provides Mono (0 or 1 item) and Flux (0 to N items) as the core asynchronous types. Unlike the traditional Spring MVC, which uses one thread per request and blocks on I/O, WebFlux is designed to handle many concurrent connections with a small number of threads by using non-blocking I/O and event loops.
This model is especially useful for applications that need to handle long-lived connections (like Server-Sent Events or WebSockets) or that integrate with other reactive data sources (such as MongoDB, Cassandra, or reactive Redis). It also works well for building microservices that call downstream APIs asynchronously.
It’s important to note that WebFlux does not make your code automatically faster; it changes the concurrency model. For CPU-bound tasks, the reactive model offers little benefit and can even add overhead. For I/O-bound tasks, it can dramatically reduce the number of threads needed.
How WebFlux Handles Async Results
In a WebFlux controller, you return a Mono<T> or Flux<T> instead of a plain object. The framework subscribes to that reactive type and pushes the result to the HTTP response when it becomes available. This is fundamentally different from Spring MVC’s DeferredResult or CompletableFuture, which are one-shot async mechanisms. WebFlux is fully reactive end-to-end.
For example, a simple controller method looks like:
@GetMapping("/user/{id}")
public Mono<User> getUser(@PathVariable String id) {
return userRepository.findById(id);
}
Here, userRepository.findById returns a Mono<User> (assuming a reactive repository). WebFlux subscribes to it and writes the resulting JSON to the response. If the Mono emits an error, the framework maps it to an HTTP error response using the configured WebExceptionHandler.
For multiple items, you return a Flux<T>. The framework streams each item as it arrives, which is ideal for large datasets or real-time feeds. You can also use operators like map, flatMap, filter, and zip to transform the data before it reaches the client.
Choosing Between Reactor Netty and Servlet Containers
WebFlux can run on two types of servers:
- Reactor Netty – the default, fully non-blocking, built on Netty. It supports both HTTP and TCP, and is ideal for high-concurrency, low-latency applications.
- Servlet 3.1+ containers (Tomcat, Jetty, Undertow) – these support the Servlet API but can run WebFlux in a non-blocking mode using
AsyncContext. This is useful when you must deploy to an existing servlet container or need to mix WebFlux with other servlet-based components.
How do you choose? Consider the following:
- Deployment environment: If you need to deploy to an existing Tomcat or Jetty instance (e.g., a corporate standard), use the servlet container. If you are building a new microservice with a self-contained jar, Reactor Netty is simpler and more consistent.
- Performance: Reactor Netty generally has lower overhead and better throughput for high connection counts because it is designed for non-blocking I/O from the ground up. Servlet containers, even in async mode, have some legacy blocking infrastructure.
- Compatibility: If you need to use servlet-specific features (like filters that rely on blocking APIs), you may be forced to use a servlet container. But be aware that mixing blocking and non-blocking can negate the benefits.
- Ease of use: Reactor Netty is the default and requires zero configuration. To use Tomcat, you just add the dependency and Spring Boot will configure it automatically.
In practice, most new projects choose Reactor Netty because it aligns with the reactive model and avoids the baggage of the servlet API. But if you have a mandate to use a particular servlet container, WebFlux still works well.
Common Problems and Misconceptions
One common misconception is that WebFlux makes your database calls asynchronous automatically. It does not. If you use a blocking JDBC driver, your thread will still block, and you lose the benefits of non-blocking I/O. You need a reactive database driver (like R2DBC for relational databases, or the reactive drivers for MongoDB, Cassandra, etc.) to get true end-to-end reactivity.
Another issue is error handling. Because reactive streams are asynchronous, exceptions thrown inside a Mono or Flux are not caught by a traditional @ExceptionHandler unless you use onErrorResume or a global error handler. You must explicitly handle errors in the reactive pipeline or provide a WebExceptionHandler bean.
Threading is also a source of confusion. By default, WebFlux uses a small number of event loop threads (typically the number of CPU cores). Long-running CPU-bound operations will block these threads and hurt performance. For such tasks, you should offload them to a separate thread pool using subscribeOn or publishOn with a bounded elastic scheduler.
Comparison: WebFlux vs Spring MVC
Spring MVC is the traditional blocking framework. It uses a thread-per-request model, which is simple and well-understood. WebFlux is reactive and non-blocking. Here’s a quick comparison:
- Concurrency: MVC can handle a few thousand concurrent connections with a large thread pool; WebFlux can handle tens of thousands with a handful of threads.
- Latency: For I/O-bound operations, WebFlux can reduce latency under high load because it doesn’t waste threads waiting. For simple operations, the difference is negligible.
- Code style: MVC is imperative and easier for many developers. WebFlux is functional and has a learning curve.
- Database: MVC works with any JDBC driver. WebFlux needs reactive drivers for full benefit.
- Testing: Both have good testing support, but WebFlux tests often use
WebTestClientwhich is reactive.
You don’t have to choose one for the whole application. You can mix WebFlux and MVC in the same application, but it’s not recommended because they use different servlet contexts. In practice, pick one per application.
Costs and Trade-offs
Adopting WebFlux comes with costs. The reactive programming model has a steeper learning curve. Debugging is harder because stack traces are less linear. You may need to learn Reactor operators and understand backpressure.
Also, many libraries are still blocking. If your team relies on blocking JDBC, JPA, or other synchronous APIs, you’ll either have to wrap them (which defeats the purpose) or use alternative reactive drivers. This can increase migration effort.
On the positive side, WebFlux can reduce infrastructure costs by using fewer threads and less memory. For applications with high I/O concurrency, the savings can be significant. But for typical CRUD apps with low concurrency, the benefits may not justify the complexity.
Frequently Asked Questions
Can I use WebFlux with a traditional JDBC database?
Yes, but you will lose the non-blocking benefits. If you call a blocking JDBC repository inside a reactive pipeline, the thread will block, and you’ll need to offload it to a separate thread pool to avoid blocking event loop threads. This is possible but not ideal; a reactive driver like R2DBC is the proper solution.
How do I choose between Mono and Flux?
Use Mono when you expect at most one result (like a single entity or a count). Use Flux when you expect zero to many results (like a list or a stream). If you have a collection, you can also return Flux and let WebFlux stream the elements, or wrap it in a Mono<List<T>> if you want the whole list at once.
Does WebFlux work with Spring Security?
Yes, Spring Security has full reactive support. You can use @EnableWebFluxSecurity and define a SecurityWebFilterChain bean. Reactive security works similarly to MVC security, but you use Mono-based methods like hasAuthority.
What is backpressure and why does it matter?
Backpressure is the ability of the consumer to signal how much data it can handle. In WebFlux, if a client is slow, the server can slow down production of data to avoid overwhelming the client. This is built into Reactor. It matters because it prevents memory exhaustion and improves stability.
Can I use WebFlux with WebSockets?
Yes, WebFlux supports WebSockets natively. You can handle WebSocket sessions with a WebSocketHandler and return a Mono<Void> that completes when the session ends. This is a common use case for reactive apps.
Is WebFlux faster than Spring MVC?
Not necessarily. For low concurrency, the difference is negligible. For high concurrency with I/O-bound work, WebFlux can handle more requests with fewer resources, making it more efficient. But for CPU-bound tasks, MVC might be simpler and just as fast.