Context: Moving Beyond Thread-per-Request
Traditional Spring MVC applications follow a straightforward concurrency model: one thread per HTTP request. Unlike modern multithreading approaches like structured concurrency in Java, when a client calls your endpoint, a dedicated worker from a pool (typically 200 threads in standard Tomcat) handles authentication, queries the database, waits on downstream APIs, and writes the response. This model is simple to reason about and straightforward to debug. However, it degrades quickly under heavy load or during slow network round-trips.
Threads sitting idle during I/O waits still consume resources. Each thread reserves an OS stack (often 1MB by default). If 500 concurrent requests stall on a slow payment gateway taking 2 seconds to respond, Tomcat consumes roughly 500MB of RAM just maintaining blocked threads. Before long, thread pools exhaust, request queues overflow, and latency spikes across the entire system.
While you can also configure Java 21 virtual threads in Spring Boot 3 to scale thread-per-request workloads, Spring Boot 3 and WebFlux tackle this bottleneck with an event-driven loop powered by Netty. Rather than allocating hundreds of blocking threads, Netty typically allocates a small core pool—usually 2 × available CPU cores.
That means an 8-core server runs comfortably on just 16 worker threads. These threads register non-blocking I/O socket events, kick off asynchronous pipelines, and immediately return to accept new connections. When downstream data arrives, an OS event notification dispatches execution back onto the loop to deliver the chunk.
Non-blocking I/O is built on the Reactive Streams specification. You work with two primary types: Mono (emitting 0 or 1 item) and Flux (emitting 0 to N items).
But speed creates a new challenge: what happens when a publisher produces 10,000 events per second, while a database writer can only persist 1,000? Without backpressure, your JVM runs out of heap within seconds. Backpressure gives the subscriber explicit control, letting downstream consumers dictate exactly how many items they can handle at a given moment.
Installation: Bootstrapping a Spring Boot 3 WebFlux Application
Spring Boot 3 requires Java 17 or later. To get started, scaffold a project via Spring Initializr or your build tool. Select Spring Reactive Web (spring-boot-starter-webflux) instead of standard Spring MVC (as typically used when building Spring Boot 3 REST APIs with blocking drivers).
Here is a clean pom.xml dependency setup for Maven:
<dependencies>
<!-- Spring WebFlux Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- Reactive Test Utilities -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
If you build with Gradle, add these dependencies to build.gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}
Make sure you exclude spring-boot-starter-web. If both starters end up on the classpath, Spring Boot defaults to the servlet container (Tomcat) rather than Netty. That undoes the fully non-blocking architecture.
Configuration: Reactive Endpoints and Backpressure Strategies
Configuring a reactive service requires two core components: an asynchronous HTTP client and an explicit strategy for backpressure. Let us look at both.
1. Setting Up WebClient
WebFlux replaces the legacy, blocking RestTemplate with WebClient. Below is a configuration class setting a strict 5-second response timeout on Netty's underlying HTTP client:
package com.itfromzero.reactive.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import java.time.Duration;
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient(WebClient.Builder builder) {
HttpClient httpClient = HttpClient.create()
.responseTimeout(Duration.ofSeconds(5));
return builder
.baseUrl("https://api.example.com")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
}
2. Applying Backpressure Operators
Fast publishers overwhelm slow downstream consumers unless you configure defensive buffering or shedding. Project Reactor gives you several explicit strategies:
onBackpressureBuffer(capacity, consumer): Stores bursts up to a fixed buffer limit (e.g., 50 items). Drops or raises an error when full.onBackpressureDrop(consumer): Discards newly arrived items immediately if the subscriber is currently busy.onBackpressureLatest(): Retains only the most recent emission, overwriting older unconsumed items to conserve memory.
Here is how you apply these strategies in a telemetry service emitting signals every 10ms:
package com.itfromzero.reactive.service;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import java.time.Duration;
@Service
public class TelemetryService {
// Limits queued events to 50 entries, then drops excess traffic
public Flux<String> getBufferedStream() {
return Flux.interval(Duration.ofMillis(10))
.map(seq -> "Telemetry Signal #" + seq)
.onBackpressureBuffer(
50,
dropped -> System.err.println("Buffer capacity exceeded, dropped: " + dropped)
);
}
// Discards events immediately if the downstream client falls behind
public Flux<String> getDropStream() {
return Flux.interval(Duration.ofMillis(10))
.map(seq -> "High-Rate Metric #" + seq)
.onBackpressureDrop(item -> System.out.println("Slow consumer detected; shedding: " + item));
}
}
3. Exposing a Streaming REST Controller
To stream items continuously over HTTP without buffering the entire payload in memory, use Server-Sent Events (text/event-stream) or Newline Delimited JSON (application/x-ndjson):
package com.itfromzero.reactive.controller;
import com.itfromzero.reactive.service.TelemetryService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
@RequestMapping("/api/telemetry")
public class TelemetryController {
private final TelemetryService telemetryService;
public TelemetryController(TelemetryService telemetryService) {
this.telemetryService = telemetryService;
}
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamMetrics() {
return telemetryService.getDropStream();
}
}
Verification & Monitoring: Testing and Metrics
Standard unit test assertions run synchronously, which means they finish before an asynchronous pipeline even emits data. You need specialized tools to test reactive flows properly.
1. Testing Backpressure with StepVerifier
The StepVerifier utility from reactor-test lets you test demand signaling by requesting a precise count of items (request(n)):
package com.itfromzero.reactive;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
class BackpressureTest {
@Test
void shouldHonorDownstreamDemand() {
Flux<Integer> numbers = Flux.range(1, 100).log();
StepVerifier.create(numbers, 2) // Pull exactly 2 items first
.expectNext(1)
.expectNext(2)
.thenRequest(3) // Demand 3 more items
.expectNext(3, 4, 5)
.thenCancel() // Cancel remaining 95 items
.verify();
}
}
2. Verifying Real-Time Delivery via Curl
Run your application and test the stream with curl from your terminal:
curl -N http://localhost:8080/api/telemetry/stream
The -N flag disables output buffering. You will see individual events printed to the console the millisecond Netty flushes them, rather than waiting for the entire response to buffer.
3. Production Monitoring with Micrometer
Thread dumps offer little insight into reactive systems because worker threads rarely block. Instead, you need visibility into thread scheduling, queue sizes, and connection pools. Add spring-boot-starter-actuator and enable Reactor metrics inside your main application class:
package com.itfromzero.reactive;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import reactor.core.publisher.Hooks;
import reactor.core.scheduler.Schedulers;
@SpringBootApplication
public class ReactiveApplication {
public static void main(String[] args) {
// Expose scheduler metrics to Micrometer
Schedulers.enableMetrics();
// Propagate trace IDs and security context across thread hops
Hooks.enableAutomaticContextPropagation();
SpringApplication.run(ReactiveApplication.class, args);
}
}
Check your active thread count and scheduler load directly through Actuator:
curl http://localhost:8080/actuator/metrics/jvm.threads.live
Compare this number against a classic MVC service handling similar concurrency. While Spring MVC often sits at 200+ threads under peak load, WebFlux stays steady at 16 to 32 threads, keeping heap usage predictable and latency consistent.
