Skip to content

    System Design

    Blocking vs Reactive: Spring MVC and WebFlux

    Learn how Spring MVC and WebFlux spend threads, why a blocking call on an event-loop thread stalls every request, and how to choose between them, with a lab.

    By Published 17 min read

    Share

    Flagship lessonintermediateSpring Boot labBackend System Design

    Before this: Thread Pools, Executors and CompletableFuture, Virtual Threads (Project Loom)

    What you'll learn: By the end of this lesson you will be able to explain how Spring MVC and Spring WebFlux spend threads while a request waits for a downstream call, say what "reactive" and "non-blocking" mean and what they do not promise, show why one blocking call on an event-loop thread delays every other request, move a blocking call off that thread with subscribeOn, choose between MVC, WebFlux and MVC on virtual threads for a given service, and use a Java lab that counts parked threads instead of timing anything.

    Picture a call centre where every agent, once they phone the supplier, stays on hold until someone picks up. Twenty agents can have twenty calls in progress, and the twenty-first customer waits however quiet the floor otherwise is. Now picture a second centre where an agent logs the question, hangs up, and takes the next customer; when the supplier calls back, whichever agent is free finishes the job. The second centre serves far more customers with the same staff, but only if nobody there ever stays on hold. One agent who does is a whole desk lost, and with a handful of desks it is the whole floor.

    The first centre is Spring MVC with its thread-per-request model, the second is Spring WebFlux. The thread pool lesson covered bounding threads that wait, and the virtual threads lesson showed a third way to make waiting cheap. This lesson places all three in a web framework and ends with a decision you can defend.

    Verified with the Spring Framework 7.1 reference (WebFlux overview), the Apache Tomcat 11.0 connector documentation, the Reactor reference (schedulers and FAQ), the Spring Boot reference, and a lab compiled for Java 25 (--release 25) and run on JDK 27.0.1.1 with Spring Boot 4.1.2, on 2026-12-01.

    The core idea

    Spring MVC assumes a request may block its thread, so it gives each request a thread from a large pool; Spring WebFlux assumes nothing blocks, so it serves all requests from a few event-loop threads and uses callbacks, expressed as Mono and Flux, to continue when data arrives. The Spring reference states both assumptions: in MVC, "it is assumed that applications can block the current thread, (for example, for remote calls)" and servlet containers "use a large thread pool to absorb potential blocking"; in WebFlux, "it is assumed that applications do not block", so non-blocking servers "use a small, fixed-size thread pool (event loop workers)".

    Three illustrations run through the lesson, each labelled:

    • Minimal example: eight requests to a hung downstream service, served by four platform threads, by one virtual thread per request and by one event-loop thread, in the Java lab.
    • Realistic example: a ShopStream product-page aggregator that only calls other services, in "In practice".
    • Failure example: one blocking call inside a WebFlux handler that stops a health check, then the same call moved off the event loop.

    The reference is blunt about what the choice buys. "Reactive and non-blocking generally do not make applications run faster." The benefit it names is "the ability to scale with a small, fixed number of threads and less memory". Nothing in the model makes a single request quicker; it changes what a waiting request costs.

    Two ways to spend a thread

    A request that calls a slow service spends most of its life waiting. The two frameworks differ in what is held during that wait.

    sequenceDiagram accTitle: A blocking handler holds a thread while a reactive handler holds none accDescr: In the Spring MVC lane, a request thread calls the price service and stays parked until the reply, so it cannot serve anything else. In the WebFlux lane, the event-loop thread starts the call, registers what to do with the reply and moves on to the next request; when the reply arrives, an event-loop thread finishes the response. participant C as Client participant T as MVC request thread participant E as WebFlux event-loop thread participant P as Price service C->>T: request A T->>P: call Note over T: parked until the reply P-->>T: reply T-->>C: response A C->>E: request B E->>P: start call, register callback Note over E: free at once C->>E: request C E->>E: handles C meanwhile P-->>E: reply for B E-->>C: response B

    Figure 1. What each model holds during the wait. How to read this: in the top half the thread belongs to request A from the first byte to the last, including the wait. In the bottom half the thread belongs to nobody while the price service thinks; the waiting state lives in a small object, not in a stack.

    The MVC model: a thread per request

    On a servlet container the request thread runs the controller, the service code and the JDBC call in one straight line, and the stack records where it is. That is why blocking code is easy to write, read and debug. The cost is the pool. Tomcat's connector documentation says maxThreads is "the maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled", and "if not specified, this attribute is set to 200". A threshold of 200 simultaneous requests is a limit you meet as soon as a downstream slows down, as the thread pool lesson showed with Little's law: slow calls mean more threads busy for the same arrival rate. The same documentation page describes acceptCount, the operating-system queue for connection requests, whose default is 100: beyond the pool there is one more line, and then refusals or time-outs.

    The WebFlux model: few threads, callbacks

    WebFlux runs on non-blocking servers, and the reference says to "expect one thread for the server and several others for request processing (typically as many as the number of CPU cores)" on a plain WebFlux server. Servlet containers can also host it through non-blocking servlet I/O, but the event-loop idea is the same: few threads, none of which may wait. The programming model follows from that. A handler cannot return the answer, because it does not have it yet; it returns a description of the answer, a Mono<T> for zero or one value or a Flux<T> for many, and the framework subscribes to it, writes the response when it completes, and releases the thread in between.

    The reference defines the word "reactive" this way: "The term, 'reactive,' refers to programming models that are built around reacting to change", and "non-blocking is reactive, because, instead of being blocked, we are now in the mode of reacting to notifications as operations complete or data becomes available." So reactive here is about reacting instead of waiting; it is not a promise of speed.

    Backpressure: the other half of reactive

    Non-blocking code has a hazard of its own. If a producer can emit faster than a consumer can take, something must give. The reference puts it plainly: "In non-blocking code, it becomes important to control the rate of events so that a fast producer does not overwhelm its destination." The Reactive Streams contract answers by letting the consumer ask: "The main purpose of Reactive Streams is to let the subscriber control how quickly or how slowly the publisher produces data." And when a publisher cannot slow down, "it has to decide whether to buffer, drop, or fail."

    That is the same decision as a full queue in front of a thread pool (buffer, reject or slow the sender), carried through the type system instead of left to a RejectedExecutionException. The backpressure lesson treats the general idea. For a request and response that carry one value each, backpressure rarely matters, which is why much of the gain of reactive stacks shows up in streaming responses, such as server-sent events, and fan-out calls, not in simple CRUD handlers. The planned lessons on WebSockets, server-sent events and long polling cover that streaming side.

    The one rule: never block an event-loop thread

    Because few threads serve everything, a thread that waits is not one agent lost; it is a large share of the floor. With one event-loop thread, as in the lab, a single blocking call stops every request.

    Thread-per-request pool versus a small event-loop poolRequests to Servlet pool (thread each); Requests to Event loop (shared); Servlet pool to Slow downstream (waits on it); Event loop to Slow downstream (callback)Requests: many at onceRequestsmany at onceServlet pool: large, each parksServlet poollarge, each parksEvent loop: few, never parkEvent loopfew, never parkSlow downstream: answers laterSlowdownstreamanswers laterthread eachsharedwaits on itcallback

    Figure 2. The same wait, two costs. How to read this: the servlet pool puts a parked thread on every in-flight call to the slow service, so its size is its concurrency limit. The event loop starts the call and gets on with other work; its dashed arrow is a registered callback, not a waiting thread.

    sequenceDiagram accTitle: A blocking call on the only event-loop thread stops a health check accDescr: Request A reaches a handler that calls a blocking method on the event-loop thread. The thread parks. A health request arrives and waits in the loop's queue because the one thread is busy. When the downstream finally answers, A finishes and only then does the health request run. participant A as Request A (/bad) participant L as Event-loop thread participant D as Slow downstream participant H as Health check A->>L: handler runs L->>D: blocking call Note over L: parked, no other request can start H->>L: GET /health queues behind A D-->>L: reply L-->>A: response A L-->>H: response health

    Figure 3. One parked thread, every request waits. How to read this: the health request does no downstream work at all, yet it cannot start, because the thread that would run it is inside request A's blocking call. Nothing is deadlocked; the delay lasts as long as the slow call does.

    Reactor even enforces the rule where it can. Its reference says that calling block(), blockFirst() or blockLast() inside the default single and parallel schedulers throws an IllegalStateException, and that custom schedulers can be marked "non blocking only". The Spring reference also warns against mixing the two worlds: "mixing blocking I/O and non-blocking I/O in the same context will cause runtime issues."

    The escape hatch and its price

    If you must call a blocking library, Spring says "Both Reactor and RxJava provide the publishOn operator to continue processing on a different thread. That means there is an easy escape hatch. Keep in mind, however, that blocking APIs are not a good fit for this concurrency model." Reactor's recipe for a blocking call is Mono.fromCallable(...) followed by subscribeOn(Schedulers.boundedElastic()). The bounded-elastic scheduler "has a cap on the number of backing threads it can create (default is number of CPU cores x 10)" and queues tasks beyond that, up to 100,000. Read that as: the blocking call gets a thread pool of its own, and the thread-pool lesson's questions come back (how many, how long a queue, what on overflow). subscribeOn "changes the Thread from which the whole chain of operators subscribes", and the Reactor FAQ advises placing it directly after the source.

    The escape hatch does not make blocking free. It moves the wait from the scarce event-loop threads to a pool you must size and watch, and it gives up the memory advantage for that call. The Spring reference draws the conclusion: with JDBC or JPA, "Spring MVC is the best choice for common architectures at least", because running blocking calls on a separate thread means "you would not be making the most of a non-blocking web stack."

    Where virtual threads fit

    Virtual threads attack the same cost from the other side. Instead of removing the wait, they make the waiting thread cheap, so blocking code, with its readable stack traces and its JDBC drivers, can scale in thread count. Spring Boot's reference describes spring.threads.virtual.enabled as switching the application's task executor and task scheduler to virtual-thread versions on Java 21 and later; the page does not say anything about request threads, so check the documentation of your container before relying on that. The Spring WebFlux "Applicability" section, in the version read for this lesson, does not mention virtual threads at all, so the comparison below is the lab's, not the reference's.

    What does not change: a virtual thread per request means an unbounded number of calls in flight to whatever the request calls. The virtual threads lesson names the fix, a limit on the scarce resource itself, and the bulkhead and resilience lessons show how. A database connection pool is that limit for a database (a separate lesson covers HikariCP).

    Build it: eight requests, three models

    This is the minimal example. The lab uses real Spring code (Spring MVC through MockMvc, Spring WebFlux through the HttpHandler that a server would call) and starts no server, so the threads that stand in for a servlet container or an event loop are named as stand-ins. It prints counters read after events, never timings.

    Goal. See how many calls to a hung service can be in flight in each model, how many threads are parked, and what a blocking call does to the only event-loop thread.

    Setup. From the repository's examples/spring-labs folder:

    ./gradlew :labs:blocking-vs-reactive:test
    ./gradlew :labs:blocking-vs-reactive:test -PwriteGolden

    The first command runs 6 tests: 4 on behaviour and 2 on the golden file. The second rewrites the golden file from a real run. The code is in examples/spring-labs/labs/blocking-vs-reactive/src/main/java/buildingai/labs/reactive/ and the report in the test sources.

    How it works. HungDependency is a fake price service that answers only when the lab releases it, in two styles: callBlocking() parks the calling thread on a latch, and callReactive() returns a Mono completed by a future, so nothing waits. The MVC controller calls the blocking style. The WebFlux controller has three price endpoints that differ only in how they wait:

    @GetMapping("/bad/{id}/price")
    public Mono<String> badPrice(@PathVariable String id) {
        return Mono.just(prices.callBlocking());
    }
    
    @GetMapping("/offloaded/{id}/price")
    public Mono<String> offloadedPrice(@PathVariable String id) {
        return Mono.fromCallable(prices::callBlocking).subscribeOn(Schedulers.boundedElastic());
    }

    In the first, the blocking call runs inside the handler method, on the thread that invoked it; in the second, it is wrapped and subscribed on boundedElastic. The lab drives WebFlux from one thread made with Schedulers.newSingle("event-loop", true), standing in for one event-loop worker.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25 language level, JDK 27.0.1.1):

    Blocking vs reactive lab: Spring MVC through MockMvc, Spring WebFlux through its HttpHandler.
    No server is started. Every number is a counter read after an event; no timings are printed.
    
    1. Eight requests arrive while the price service hangs
      MVC, 4 platform request threads: calls started=4, threads parked=4, requests queued=4
      after the service answers: statuses [200, 200, 200, 200, 200, 200, 200, 200], threads that served calls=4
      MVC, one virtual thread per request: calls started=8, of them on virtual threads=8
      after the service answers: statuses [200, 200, 200, 200, 200, 200, 200, 200], threads that served calls=8
      WebFlux, one event-loop thread: calls started=8, threads that started them=1, threads parked=0
      after the service answers: 8 of 8 responses are 200 with the price
    
    2. One event-loop thread, a request that blocks, and a /health request behind it
      blocking call inside the handler method (/bad):
        /health finished while the price call hangs? false
        after release: price status 200, health status 200 body up
      blocking call moved to boundedElastic with subscribeOn (/offloaded):
        /health finished while the price call hangs? true
        after release: price status 200, health status 200 body up
    
    3. Reactor refuses block() on a non-blocking scheduler thread
      exception class: IllegalStateException
      message starts with the block()/blockFirst()/blockLast() refusal text: true

    What the output shows. Part 1 is the call-centre story in numbers. Four platform threads hold four parked calls and leave four requests in the queue. One virtual thread per request starts all eight calls at once, and every one of them runs on a virtual thread. One WebFlux thread starts all eight calls with no thread parked. This is a model: a real Tomcat has its own pool size and queues, and a real Netty event loop has several workers. The shape is what carries over. Part 2 is Figure 3 as a test: the /health request cannot finish while the blocking call sits on the loop, and finishes at once when the same call is offloaded. Part 3 shows Reactor's guard rail.

    Break it. In ReactiveProductController, change /offloaded/{id}/price to return Mono.just(prices.callBlocking()) and run the tests: the offloading test fails, because /health can no longer finish. Put the code back and run the tests again.

    Stretch. Add a second event-loop thread to the lab and send two blocking requests: the loop is gone again. Then replace the single thread with Schedulers.parallel() and count how many blocking calls it takes to park every worker. What the lab leaves out: real network I/O, a real server's thread counts, memory per thread and the cost of reactive code.

    Choosing: the trade-offs

    Decide first what the request path calls, then how much concurrency you need while it waits, and then what your team can read at 2 a.m.

    Option Gain Cost Wrong when
    Spring MVC, platform threads Simple code, plain stack traces, any blocking library Concurrency is capped by the pool; slow calls hold threads Many long-lived or slow calls per request at high rate
    Spring MVC, virtual threads Blocking code with high concurrency The limit on downstream calls must come from elsewhere Work is CPU-bound
    WebFlux, non-blocking end to end A small fixed thread count; backpressure; streaming A new programming model; every library on the path must be non-blocking The path calls JDBC or other blocking APIs
    WebFlux with blocking offloaded Lets a few blocking calls coexist A second pool to size; the memory gain is lost for those calls Blocking is the common case
    WebClient inside Spring MVC Parallel remote calls without leaving MVC Reactive types in an imperative app The team will only ever call one service at a time

    The Spring reference lists exactly this last option: "If you have a Spring MVC application with calls to remote services, try the reactive WebClient. You can return reactive types ... directly from Spring MVC controller methods." And its first rule: "If you have a Spring MVC application that works fine, there is no need to change."

    flowchart TD accTitle: Choosing between Spring MVC, MVC with virtual threads and WebFlux accDescr: A decision flow. If the service has a working MVC application and no scaling problem, keep it. If the request path uses blocking persistence such as JDBC or JPA, prefer MVC, with virtual threads if concurrency of waiting calls is the problem. If the path is mostly remote calls or streaming and the team can work non-blocking, WebFlux is a fit. Otherwise stay on MVC. S[New or changing service] --> A{MVC app works and meets load?} A -->|yes| K[Keep MVC] A -->|no| B{Request path uses JDBC or JPA?} B -->|yes| M[MVC; add virtual threads if waiting calls are the limit] B -->|no| C{Mostly remote calls or streaming?} C -->|yes| D{Team can write non-blocking code?} D -->|yes| W[WebFlux, no blocking on the loop] D -->|no| M2[MVC with WebClient or virtual threads] C -->|no| K2[Stay on MVC]

    Figure 4. A decision path. How to read this: start at the top and answer from the code you have, not the framework you like. The branch on blocking persistence is the strong one, because a blocking call on an event-loop thread is the failure in Figure 3. Each leaf is a starting point to measure, not a final answer.

    In practice: ShopStream's product page aggregator

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Numbers other than ShopStream's shared peak (about 2,300 browsing requests per second across the platform) are illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's product page needs a price, a stock level and a review summary. A small service, the aggregator, receives the page request and calls three other services over HTTP. It has no database of its own. At peak the platform serves about 2,300 browsing requests per second across all instances; for illustration, assume one aggregator instance sees 200 per second, and each page needs the three calls in parallel at about 50 ms. By Little's law, from the thread pool lesson, that is about 10 threads busy on average on a thread-per-request design, and many more the moment one downstream slows down.

    Starting architecture

    Product page aggregator before the changeAPI gateway to Aggregator (page request); Aggregator to Price service; Aggregator to Stock service; Aggregator to Review serviceAPI gatewayAPI gatewayAggregator: MVC, 200 threadsAggregatorMVC, 200 threadsPrice servicePrice serviceStock serviceStock serviceReview serviceReview servicepage request

    Figure 5. One thread per page request, three blocking calls each. How to read this: each page request parks one aggregator thread while the three calls run. The thread count caps how many pages can be in progress, whatever the downstream capacity.

    Options considered

    Option Behaviour Risk
    A. Keep MVC, raise the pool More parked threads Memory per thread; a slow downstream still fills the pool
    B. MVC on virtual threads, a Semaphore per downstream Blocking code, high concurrency, explicit limits Limits must be chosen and watched; other blocking spots may pin
    C. WebFlux and WebClient for the aggregator only Few threads, parallel calls without a thread each A new programming model for this service; any blocking call becomes a hazard

    The decision

    Option C for the aggregator, because its whole path is remote calls with no JDBC, which is the case the Spring reference names as a fit, and the catalogue and orders services stay on MVC because they use JDBC. The Spring reference supports mixing: "In a microservice architecture, you can have a mix of applications with either Spring MVC or Spring WebFlux controllers". The team writes one rule into the service's README: no blocking call on the event loop, and any unavoidable one goes through a single helper that wraps it in Mono.fromCallable with subscribeOn(Schedulers.boundedElastic()). Option B is the fallback if the team decides the programming model costs more than it returns.

    Rollout and verification

    The team ships the aggregator behind a flag to one instance. The lab's tests are the model for the checks that matter: hang each downstream in a test and assert that the handler starts every call and that /health still answers, as the lab's offloadedPrice test does, and keep a test that fails if a handler blocks. Production signals: in-flight requests, downstream latency per call, and event-loop thread state in a thread dump.

    The 2 a.m. failure

    The page reads: pages time out, and then pods restart repeatedly. A developer added a feature-flag lookup that uses a blocking JDBC call directly inside a handler. When the flag database slowed, every event-loop thread parked inside the driver, the health endpoint (served by the same threads) stopped answering, and the orchestrator restarted pods that were healthy except for that one call. The checks: a thread dump showing event-loop threads parked in a driver call, then the flag database's latency. The mitigation is to wrap the lookup in the blocking helper above, or roll the change back. The lasting fixes are a test that fails when a handler blocks, a bounded pool with an alert for blocking work, a timeout on the call, and a health check that does not share fate with the work it checks.

    Architect's notes

    • Choose by the call, not the fashion. If the request path calls JDBC or JPA, start from MVC; if it only calls remote services or streams, consider WebFlux.
    • One blocking call is a defect. Treat it like a failing test, and gate it with a test or a build-time check.
    • Size the escape hatch. A boundedElastic pool is a pool: bound, queue and alert on it.
    • Do not count on reactive for latency. The reference says it does not generally make applications faster; it changes the cost of waiting.
    • Mix services, not styles inside one handler. The reference supports MVC and WebFlux services side by side.

    Common mistakes

    • Returning Mono.just(blockingCall()). The blocking call runs when the handler runs, before any Mono exists.
    • Calling block() in a handler. Reactor refuses it on non-blocking scheduler threads, and where it is not refused it still parks a thread.
    • Moving to WebFlux while keeping JDBC on the request path and calling the result reactive.
    • Treating subscribeOn as free. It moves the wait to a pool that has a cap and a queue.
    • Adding a servlet filter to a WebFlux application. The reference advises against it.
    • Ignoring backpressure in streaming endpoints. A fast producer needs a rule for buffer, drop or fail.

    Key takeaways

    • MVC spends a thread per in-flight request and expects calls to block; WebFlux spends a few event-loop threads and expects nothing to block.
    • Reactive and non-blocking do not make a request faster; they make waiting cheap in threads and memory.
    • A blocking call on an event-loop thread delays every request that shares the thread, including health checks.
    • Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) is the documented escape hatch, and it brings a bounded pool to size.
    • With blocking persistence APIs, the Spring reference recommends MVC; virtual threads make blocking code scale in thread count but add no downstream limit.
    • Mixing MVC and WebFlux services is supported; mixing blocking and non-blocking on one request path is the trap.

    Practice exercises

    Exercise 1 (20 min). Using Little's law, compute the average parked threads for 300 requests per second at 80 ms and at 600 ms per call. State what the second number does to a pool of 200.

    Exercise 2 (45 min). Run the lab. In BlockingReport, change the MVC pool to 8 threads and predict the first line of Part 1 before you run it.

    Exercise 3 (1 hour). Run "Break it". Explain with Figure 3 why /health cannot finish, and why a longer wait on the downstream makes it worse.

    Exercise 4 (2 hours). For ShopStream's checkout service (JDBC, a payment call and a fraud call), pick a model from the table and justify it. Say which call, if any, needs a bound.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments