Why reactive: blocking vs non-blocking
Mid-level Always asked 7 min
On this page
The question
What is the difference between the thread-per-request model and an event loop?
30-second answer
In thread-per-request, each request holds one thread until it finishes, parked through every I/O wait. In an event loop, a few threads, one per core by default, run short callbacks. A waiting request holds no thread, and a callback continues it when data arrives. So an event loop handles many slow requests with few threads, but one blocking call stalls every request on it.
Understand it
Thread per request or event loop?
CompareEach request holds one thread from start to end, even while it only waits on I/O. With a pool of four, the fifth request queues although no CPU is busy.
View as text
Six requests each wait on a slow call. Bars show what each thread does, and three rows compare what happens while waiting, how the code reads and what a blocking call costs.
Thread per request: Each request holds one thread from start to end, even while it only waits on I/O. With a pool of four, the fifth request queues although no CPU is busy. While waiting: Holds its thread. Code reads: Top to bottom. Blocking call: Costs one thread.
Event loop: A few threads, one per core by default, run short callbacks. A waiting request holds no thread; when its data arrives, a callback continues it. One blocking call stalls everyone. While waiting: Holds no thread. Code reads: Chained operators. Blocking call: Stalls the loop.
Six requests each wait on a slow call. Bars show what each thread does, and three rows compare what happens while waiting, how the code reads and what a blocking call costs.
Thread per request: Each request holds one thread from start to end, even while it only waits on I/O. With a pool of four, the fifth request queues although no CPU is busy. While waiting: Holds its thread. Code reads: Top to bottom. Blocking call: Costs one thread.
Event loop: A few threads, one per core by default, run short callbacks. A waiting request holds no thread; when its data arrives, a callback continues it. One blocking call stalls everyone. While waiting: Holds no thread. Code reads: Chained operators. Blocking call: Stalls the loop.
Takeaway: Thread-per-request keeps a thread parked through every wait, so slow I/O uses up threads. An event loop waits with no thread, but one blocking call stalls every request on it.
How latency uses up threads
Explore300/s at 100 ms keeps only 30 threads busy. A thread pool handles this easily, so reactive adds complexity and gains little.
View as text
A grid of 20 cells stands for a pool of 200 threads, each cell for 10 threads, filling as threads get busy. A line below says how many threads the load needs, and a small row of event loop threads never changes. A mark says whether the pool copes.
500/s at 10 ms keeps only 5 threads busy. A thread pool handles this easily, so reactive adds complexity and gains little.
300/s at 100 ms keeps only 30 threads busy. A thread pool handles this easily, so reactive adds complexity and gains little.
400/s at 500 ms keeps 200 of 200 threads busy, each parked on I/O. It works, with less room for a spike.
1000/s at 500 ms would need 500 threads. The pool finishes only 400/s, so the queue grows. An event loop only waits on sockets.
A grid of 20 cells stands for a pool of 200 threads, each cell for 10 threads, filling as threads get busy. A line below says how many threads the load needs, and a small row of event loop threads never changes. A mark says whether the pool copes.
500/s at 10 ms keeps only 5 threads busy. A thread pool handles this easily, so reactive adds complexity and gains little.
300/s at 100 ms keeps only 30 threads busy. A thread pool handles this easily, so reactive adds complexity and gains little.
400/s at 500 ms keeps 200 of 200 threads busy, each parked on I/O. It works, with less room for a spike.
1000/s at 500 ms would need 500 threads. The pool finishes only 400/s, so the queue grows. An event loop only waits on sockets.
Takeaway: Thread-per-request needs rate times latency threads, so slow I/O is what exhausts a pool. Event loop threads stay constant, which is the case where reactive pays off.
In code
@GetMapping("/orders/{id}")
OrderView order(@PathVariable String id) {
Order order = orders.findById(id); // thread parked
Customer customer = customers.get(order.customer()); // parked again
return new OrderView(order, customer);
}@GetMapping("/orders/{id}")
Mono<OrderView> order(@PathVariable String id) {
return orders.findById(id)
.flatMap(order -> customers.get(order.customer())
.map(customer -> new OrderView(order, customer)));
}int requestsPerSecond = 2_000;
double secondsWaiting = 0.200; // a slow downstream call
int blockedThreads = (int) Math.ceil(requestsPerSecond * secondsWaiting); // 400 threads parked on I/O
int eventLoopThreads = Runtime.getRuntime().availableProcessors(); // reactive: about one per coreSolve it
Should this service move to WebFlux?
A Spring MVC (Model-View-Controller) service handles 300 requests per second. Each request calls three downstream APIs one after another, about 150 ms each, then writes to PostgreSQL with JPA. p99 latency is 600 ms. The team knows MVC well and runs Java 21.
- Find where the time goes. Requests wait on I/O, not on the CPU: 450 ms of every request is three sequential calls.
- Size the threads. Little’s law: 300 requests per second times about 0.5 s is about 150 requests in flight. Tomcat’s 200 threads cover it, so threads are not the bottleneck.
- Fix the real problem. The three calls are independent. Running them in parallel cuts 450 ms to about 150 ms in either stack.
- Count the migration cost. JPA blocks. WebFlux would need R2DBC (Reactive Relational Database Connectivity) or wrapped calls, and a team new to reactive code. Virtual threads keep the MVC code and lift the thread limit.
- Decide and check. Stay on MVC, parallelize, enable virtual threads, then load-test p99. Reactive pays off for thousands of long waits, streaming and backpressure.
@GetMapping("/products/{id}/page")
ProductPage page(@PathVariable long id) throws Exception {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Price> price = executor.submit(() -> prices.get(id));
Future<Stock> stock = executor.submit(() -> stocks.get(id));
Future<List<Review>> reviews = executor.submit(() -> reviewClient.get(id));
return new ProductPage(price.get(), stock.get(), reviews.get()); // about 150 ms instead of 450 ms
}
}How to answer
- Tomcat's default pool is 200 threads; Reactor Netty's loop has one per core, at least 4.
- Threads needed in thread-per-request are the request rate times the latency.
- The gain is in waiting, and neither model makes the I/O itself any faster.
- Thread-per-request is simpler to write, read and debug.
Common mistakes
- Saying reactive is faster. It saves threads under concurrency; a single request is no quicker.
- Saying an event loop has only one thread. It has one per core by default.
Follow-up questions
When does reactive programming pay off, and when does it not?
It pays off when many concurrent requests mostly wait on I/O, as in gateways and services fanning out to slow APIs, and when you stream data and need backpressure. It does not pay off for CPU-heavy work, for simple CRUD (create, read, update, delete) at modest load, or when your drivers block, because a blocking call on the loop stalls everything.
- Run the numbers first, as 500 requests per second at 10 ms is only 5 busy threads.
- The whole path must be non-blocking, including the database driver.
- Costs include harder debugging, stack traces and onboarding.
- Consider virtual threads when you only need cheap waiting.
What does the Reactive Manifesto say?
It describes what reactive systems are: responsive, resilient, elastic and message-driven. Responsive is the goal, meaning timely answers. Resilient means staying responsive during failure, elastic means staying responsive under varying load, and message-driven communication is how both are achieved. It describes system architecture, not a library, so it is broader than Reactor or Reactive Streams.
- Reactive systems are an architecture; reactive programming is a code technique.
- Reactive Streams is a separate specification, about async streams with backpressure.
- A Reactor app with one fragile database is not a reactive system.
See it in the infographic: Thread per request or event loop?
A service gets 1,000 requests per second, and each waits 500 ms on a downstream call. How many threads does thread-per-request need?
About 500, by Little's law: requests in flight equal the arrival rate times the time in the system, so 1,000 times 0.5. With Tomcat's default 200 threads, the pool finishes only 400 per second, and the queue grows until requests time out. You can raise the pool, use virtual threads, or use non-blocking I/O.
- Capacity of a full pool: threads divided by latency.
- A latency spike can saturate a pool with no extra traffic.
- Limit the downstream with a timeout, or its slowness becomes yours.
What are the downsides of reactive code?
It is harder to write, read and debug. Stack traces show operators and not your call path, so a failure can be hard to trace. ThreadLocal-based tools, such as MDC (Mapped Diagnostic Context) and security contexts, need extra care. The whole path must be non-blocking, or the benefit is lost, and a forgotten subscribe silently does nothing. Teams also need time to learn it.
Hooks.onOperatorDebugandcheckpoint()improve stack traces, at a cost.- One blocking library call can undo the whole design.
- Errors move from try/catch to operators.
See it in the infographic: Thread per request or event loop?
Is reactive programming the same as asynchronous programming?
No. Asynchronous means a caller does not wait for a result, as with a CompletableFuture. Reactive adds a model of streams: many values over time, composed with operators, with demand signalled upstream through backpressure. A Mono is close to a lazy future; a Flux has no future equivalent. A stream can even be synchronous, as Flux.range is with no scheduler.
- Backpressure is what a future does not have.
- A future is eager, and a Mono is lazy.
- Reactor is concurrency-agnostic, so it does not create threads unless asked to.
See it in the infographic: Thread per request or event loop?
How much memory does a parked thread cost?
A platform thread reserves a stack, about 1 MB by default on 64-bit systems, though only touched pages use real memory. It also costs a kernel thread and context switches. So thousands of parked threads are expensive, which is the cost an event loop or a virtual thread avoids.
Does the JVM (Java Virtual Machine) have a similar answer that keeps blocking code?
Yes, virtual threads. A blocked virtual thread unmounts from its carrier, so waiting costs almost nothing, and you keep plain sequential code. They remove much of reactive's thread-saving advantage, while backpressure and streaming remain reactive's strengths.
Check yourself
Show answers
- 20: Correct. Little's law gives the rate times the latency, so 200 times 0.1 is 20.
- 200: Incorrect. That is the request rate, and each thread is released after only 100 ms.
- One per core: Incorrect. That is an event loop. Here, each request in flight holds its own thread.
Show answers
- No. It is limited by cores, not waiting.: Correct. Saving threads helps when requests wait. Here, they compute, and it could even stall the loop.
- Yes. Reactive code runs faster.: Incorrect. Reactive code does not compute faster. It only uses fewer threads while waiting.
- Yes. It adds more threads.: Incorrect. An event loop uses fewer threads, not more.
Show answers
- One blocking call stalls every request on that thread.: Correct. A loop thread serves many requests, so blocking it delays them all.
- Each waiting request needs a large stack.: Incorrect. That is the cost of thread-per-request. A waiting request holds no thread here.
- The thread pool runs out at 200 threads.: Incorrect. That is Tomcat's default, and it is what an event loop avoids.