WebFlux vs Spring MVC

MVC
Model-View-Controller

Mid-level Always asked 7 min

On this page

The question

When would you choose WebFlux over Spring MVC?

30-second answer

Choose WebFlux for streaming with backpressure, or for very many connections mostly waiting on I/O, as long as the whole path is non-blocking. Otherwise start with MVC: it is simpler, it debugs better, and JDBC (Java Database Connectivity) and JPA (Jakarta Persistence API) just work. Since Java 21, virtual threads solve cheap waiting for MVC too, which leaves streaming as WebFlux's clearest advantage.

Understand it

MVC, WebFlux or MVC with virtual threads?

Compare

Each of 200 threads parks for 500 ms, so the pool finishes 400 requests per second. At 1,000 per second, the queue grows, and the median nears 2 s.

View as text

A bar shows the median latency of 1,000 requests per second, each calling a service that takes 500 ms. Four rows compare threads, code, drivers and streaming.

MVC: Each of 200 threads parks for 500 ms, so the pool finishes 400 requests per second. At 1,000 per second, the queue grows, and the median nears 2 s. Threads: 200, all parked. Code: Plain and blocking. Drivers: JDBC, JPA, anything. Streaming: Possible, blocking writes.

WebFlux: Waiting holds no thread, so requests only take the 500 ms the call needs. In exchange, the whole path must be non-blocking, and the code is a chain of operators. Threads: One per core, never parked. Code: Chained operators. Drivers: Non-blocking only. Streaming: Non-blocking, end to end.

MVC + virtual threads: The same blocking code, with one setting. A waiting virtual thread frees its carrier, so requests take about 500 ms, level with WebFlux here. Streaming remains the strength of WebFlux. Threads: One virtual per request. Code: Plain and blocking. Drivers: JDBC, JPA, anything. Streaming: Possible, blocking writes.

A bar shows the median latency of 1,000 requests per second, each calling a service that takes 500 ms. Four rows compare threads, code, drivers and streaming.

MVC: Each of 200 threads parks for 500 ms, so the pool finishes 400 requests per second. At 1,000 per second, the queue grows, and the median nears 2 s. Threads: 200, all parked. Code: Plain and blocking. Drivers: JDBC, JPA, anything. Streaming: Possible, blocking writes.

WebFlux: Waiting holds no thread, so requests only take the 500 ms the call needs. In exchange, the whole path must be non-blocking, and the code is a chain of operators. Threads: One per core, never parked. Code: Chained operators. Drivers: Non-blocking only. Streaming: Non-blocking, end to end.

MVC + virtual threads: The same blocking code, with one setting. A waiting virtual thread frees its carrier, so requests take about 500 ms, level with WebFlux here. Streaming remains the strength of WebFlux. Threads: One virtual per request. Code: Plain and blocking. Drivers: JDBC, JPA, anything. Streaming: Possible, blocking writes.

Takeaway: Under slow I/O, plain MVC runs out of threads. WebFlux and virtual threads both wait cheaply, so virtual threads keep simple code, and WebFlux adds non-blocking streaming.

Choose the stack for four services

Build

Four services need a stack. Put the stack that fits on each one. Each piece says why it fits.

Drag a piece, or select it and then select a place.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
View as text

Four rows, one per service, each with an empty slot for a stack. Four services need a stack. Put the stack that fits on each one. Each piece says why it fits.

The answers are: An internal admin app on JPA, with modest traffic: Spring MVC: simple, and JPA just works. A live feed pushed to thousands of connected clients, each reading at its own speed: WebFlux: streaming and backpressure end to end. High traffic, slow downstream calls, and every driver and library is blocking: MVC + virtual threads: blocking code, cheap waiting. An existing MVC service where one endpoint must call three APIs in parallel: MVC + WebClient: keep the app, add parallel calls.

Start from MVC. Add virtual threads for cheap waiting, WebClient for a few parallel calls, and choose WebFlux when you really stream.

Four rows, one per service, each with an empty slot for a stack. Four services need a stack. Put the stack that fits on each one. Each piece says why it fits.

The answers are: An internal admin app on JPA, with modest traffic: Spring MVC: simple, and JPA just works. A live feed pushed to thousands of connected clients, each reading at its own speed: WebFlux: streaming and backpressure end to end. High traffic, slow downstream calls, and every driver and library is blocking: MVC + virtual threads: blocking code, cheap waiting. An existing MVC service where one endpoint must call three APIs in parallel: MVC + WebClient: keep the app, add parallel calls.

Start from MVC. Add virtual threads for cheap waiting, WebClient for a few parallel calls, and choose WebFlux when you really stream.

Takeaway: Default to MVC. Virtual threads fix waiting while code stays blocking, WebClient adds parallel calls to an MVC app, and WebFlux earns its cost for streaming and backpressure.

Which stack? Start from what you needA simple service at modest load fits Spring MVC. Slow calls with blocking libraries fit MVC with virtual threads. A few parallel calls in an MVC application fit WebClient. Streaming with backpressure, on a non-blocking path, fits WebFlux.What does theservice need?Simple, modest load:Spring MVCBlocking code,cheapwaits: virtual threadsParallel calls in MVC:WebClientBackpressure:WebFlux
Which stack? Start from what you needA simple service at modest load fits Spring MVC. Slow calls with blocking libraries fit MVC with virtual threads. A few parallel calls in an MVC application fit WebClient. Streaming with backpressure, on a non-blocking path, fits WebFlux.What does theservice need?Simple, modest load:Spring MVCBlocking code,cheapwaits: virtual threadsParallel calls in MVC:WebClientBackpressure:WebFlux
Which stack? Start from what you need

In code

@RestController
class MvcOrders {
    @GetMapping("/orders/{id}")
    Order order(@PathVariable String id) {
        return client.get().uri("/orders/{id}", id).retrieve().body(Order.class);  // RestClient
    }
}

@RestController
class WebFluxOrders {
    @GetMapping("/orders/{id}")
    Mono<Order> order(@PathVariable String id) {
        return client.get().uri("/orders/{id}", id).retrieve().bodyToMono(Order.class);  // WebClient
    }
}
The same endpoint in both stacks
@GetMapping("/dashboard/{id}")
Dashboard dashboard(@PathVariable String id) {
    return Mono.zip(findUser(id), findOrders(id), findPoints(id))
            .map(all -> new Dashboard(all.getT1(), all.getT2(), all.getT3()))
            .block();    // allowed here: this is a Tomcat thread
}
WebClient in an MVC application: parallel calls
spring.threads.virtual.enabled=true
MVC on virtual threads, with Java 21 or later
What a request travels throughSpring MVC runs on a servlet container such as Tomcat, with a thread per request and DispatcherServlet. WebFlux runs on a non-blocking server such as Netty, with an event loop and DispatcherHandler. With both starters on the classpath, Spring Boot chooses MVC.spring-webmvcTomcat: one threadper requestDispatcherServletspring-webfluxNetty: event loop,a few threadsDispatcherHandler
What a request travels throughSpring MVC runs on a servlet container such as Tomcat, with a thread per request and DispatcherServlet. WebFlux runs on a non-blocking server such as Netty, with an event loop and DispatcherHandler. With both starters on the classpath, Spring Boot chooses MVC.spring-webmvcTomcat: one threadper requestDispatcherServletspring-webfluxNetty: event loop,a few threadsDispatcherHandler
What a request travels through

Solve it

Pick the stack for live prices pushed to 20,000 browsers

A new service streams price updates over Server-Sent Events to about 20,000 connected browsers. Updates come from a reactive Kafka consumer. Each connection is open for hours and idle most of the time. Choose MVC or WebFlux.

  1. Describe the load. Many long-lived, mostly idle connections, with data pushed out. That is concurrency, not CPU.
  2. Price MVC. With platform threads each open connection holds a thread: 20,000 threads is too many. Virtual threads remove that limit, so MVC with SseEmitter becomes possible.
  3. Price WebFlux. A few event loop threads hold every connection. The source is already a Flux, and backpressure decides what a slow client receives.
  4. Decide. The source is reactive and the endpoint is a stream, so WebFlux fits with no adapter code. Pick MVC when the rest of the stack blocks.
  5. Check. Load-test 20,000 connections: thread count stays near the core count and memory stays flat.
@GetMapping(value = "/prices", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ServerSentEvent<Price>> prices() {
    return priceFeed.updates()                           // a hot Flux shared by every client
        .onBackpressureLatest()                          // no backlog: only the newest price waits
        .map(price -> ServerSentEvent.builder(price).event("price").build());
}
One shared stream, and a slow client gets the latest price

How to answer

  • In a test with 1,000 requests per second and a 500 ms downstream, MVC's median was 2 s.
  • WebFlux and MVC with virtual threads both stayed near 500 ms.
  • A blocking driver undoes WebFlux, unless moved to boundedElastic.
  • WebFlux is not faster per request; it uses fewer threads while waiting.

Common mistakes

  • Choosing WebFlux because it is "faster" or "more modern".
  • Using WebFlux with JPA, which blocks an event loop thread on every query.

Follow-up questions

What is the difference between WebClient, RestTemplate and RestClient?

RestTemplate is the original blocking client with a template API, now in maintenance mode. RestClient, from Spring Framework 6.1, is its blocking replacement with a fluent API, and the natural choice for MVC. WebClient is the non-blocking client returning Mono and Flux, required in WebFlux, and also useful in MVC for parallel calls or streaming.

  • In WebFlux, never use RestTemplate or RestClient on the event loop.
  • RestClient on virtual threads gives cheap waiting with plain code.
  • Mono.zip with WebClient makes parallel calls easy.

See it in the infographic: MVC, WebFlux or MVC with virtual threads?

What is R2DBC (Reactive Relational Database Connectivity), and why not use JPA with WebFlux?

R2DBC is a non-blocking database driver specification, the reactive counterpart of JDBC. JDBC, and so JPA and Hibernate, block the calling thread, which on an event loop stalls every request. Spring Data R2DBC gives reactive repositories returning Mono and Flux. It is deliberately simpler than JPA: no lazy loading, no persistence context, and relationships are your job.

  • It needs a driver for your database.
  • Reactive transactions use R2dbcTransactionManager, with @Transactional or TransactionalOperator.
  • If you must keep JDBC, wrap calls with subscribeOn(boundedElastic).
  • Giving up JPA features is often the real cost of WebFlux.

See it in the infographic: Choose the stack for four services

Do virtual threads replace WebFlux?

For cheap waiting, largely yes: spring.threads.virtual.enabled=true gives MVC one virtual thread per request, and in a test its latency matched WebFlux with no code changes. They do not replace streaming, backpressure or operator composition. So plain request and response services can usually stay blocking, and real stream processing still fits reactive.

  • Virtual threads need Java 21 or later.
  • A connection pool still limits you, so virtual threads can overwhelm a database.
  • Blocking code keeps normal stack traces and ThreadLocals.
  • Do not rewrite a working WebFlux service just for this.

See it in the infographic: MVC, WebFlux or MVC with virtual threads? See it in the infographic: Choose the stack for four services

How does WebFlux differ from MVC internally?

MVC is built on the Servlet API: DispatcherServlet runs on a container such as Tomcat, with one thread per request by default. WebFlux has DispatcherHandler on a non-blocking server, Netty by default, and handlers return Mono or Flux, which the framework subscribes to. The annotations look the same, as with @RestController, but the filter types and the threading differ.

  • WebFlux uses WebFilter, not servlet Filter.
  • WebFlux also offers functional routes, through RouterFunction.
  • An event loop thread is named like reactor-http-nio-1, and a Tomcat one like http-nio-8080-exec-1.

See it in the infographic: MVC, WebFlux or MVC with virtual threads?

Your MVC service is saturating under slow downstream calls. What would you try before rewriting it in WebFlux?

First measure: confirm that threads are waiting, not computing. Add timeouts, because a slow dependency should not hold threads forever. Then enable virtual threads, a one-line change if libraries cooperate. Use WebClient with Mono.zip for parallel calls. A pool increase is a short-term option. Rewrite only if you need streaming, since the rewrite touches every layer, including the database driver.

  • A full pool at 500 ms latency finishes 400 per second, so check the arithmetic.
  • A rewrite only helps if every call on the path becomes non-blocking.
  • Check a thread dump to see what the threads are doing.

See it in the infographic: MVC, WebFlux or MVC with virtual threads?

What happens if both the MVC and WebFlux starters are on the classpath?

Spring Boot chooses MVC, running on Tomcat. It was observed with both on the classpath: a servlet context and a Tomcat server. This lets an MVC application use WebClient without becoming reactive. To force WebFlux, set spring.main.web-application-type=reactive.

Can a Spring MVC controller return a Mono or a Flux?

Yes. MVC subscribes and uses servlet async to write the response, so a Flux with text/event-stream really streams. The server is still Tomcat, and writes to the response still block, on a separate thread. It helps with mixed code, and it does not make the application reactive.

Check yourself

1. A Spring Boot application has both spring-boot-starter-web and spring-boot-starter-webflux on the classpath. What does it run?
Show answers
  • Spring MVC on Tomcat: Correct. Boot prefers the servlet stack when both are present, so WebClient can be used in MVC.
  • WebFlux on Netty: Incorrect. That needs the web starter removed, or spring.main.web-application-type=reactive.
  • It fails at startup.: Incorrect. Nothing conflicts. It is a common, supported setup.
2. A team has heavy traffic and slow downstream calls, and all its libraries are blocking. Which change costs the least?
Show answers
  • Turn on virtual threads in MVC.: Correct. The blocking code stays as it is, and waiting becomes cheap, with one setting.
  • Rewrite the service in WebFlux.: Incorrect. Blocking libraries would stall the event loop, so every call needs replacing too.
  • Rewrite every call with CompletableFuture.: Incorrect. The blocking calls still hold threads, now in another pool.
3. Where may you call block() on a Mono from WebClient?
Show answers
  • On an MVC request thread: Correct. Tomcat threads are allowed to block, so it works, as block() is checked per thread.
  • Inside a WebFlux handler: Incorrect. On an event loop thread, it throws IllegalStateException.
  • Inside a map on Schedulers.parallel: Incorrect. Parallel threads are non-blocking, so it throws IllegalStateException there too.