WebFlux boundaries and blocking
What you will learn
Spring WebFlux implements reactive HTTP handling. Controllers return publishers and the framework subscribes to write the response. Non-blocking I/O can help when many requests wait on network operations, but blocking work on a shared event loop delays unrelated requests. Choose the stack according to the entire dependency chain and operational needs.
- Explain the WebFlux subscription boundary.
- Distinguish non-blocking I/O from asynchronous wrappers around blocking calls.
- Choose a bounded execution strategy and map absence to HTTP status.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Reactor and WebFlux examples require the companion Maven project. Their predicted results are not execution evidence.
Bound a legacy resource
public class Main {
public static void main(String[] args) {var permits = new java.util.concurrent.Semaphore(1); if(!permits.tryAcquire()) throw new IllegalStateException(); try { System.out.println("extra=" + permits.tryAcquire()); } finally { permits.release(); } System.out.println("available=" + permits.availablePermits()); }}Expected output:
extra=falseavailable=1A permit limits admission independently of thread count. This is a model, not event-loop scheduling; use a non-blocking admission policy on an event loop.
Where blocking belongs
A small number of event-loop threads multiplex work. Blocking a shared thread prevents other ready work from progressing. When a legacy blocking API is unavoidable, defer it with Mono.fromCallable and subscribeOn(Schedulers.boundedElastic()) near the source; bound concurrent access and impose deadlines at the actual I/O boundary. publishOn moves downstream work, whereas subscribeOn influences upstream subscription and request execution. Neither makes JDBC non-blocking. R2DBC requires a reactive driver; connection lifetime and transactions must be scoped to the publisher. Do not hold a database transaction while waiting for unrelated network calls.
Architecture decisions
MVC with platform or virtual threads is often easier for blocking JDBC and existing synchronous libraries; virtual threads reduce the cost of waiting but still need database connection limits. WebFlux fits end-to-end reactive dependencies and streaming demand. Neither architecture guarantees better latency or throughput; benchmark identical workloads and resource limits. WebClient composes an HTTP call into a publisher; set trusted base URL, connection and response deadlines, body size limits, and distinguish 404 from server failure. Cancellation or timeout of a publisher does not prove that a remote write did not happen.
Map only expected absence to 404
public class Main { static int status(java.util.Optional<Integer> value) { return value.isPresent() ? 200 : 404; } public static void main(String[] args) {System.out.println(status(java.util.Optional.of(5))); System.out.println(status(java.util.Optional.empty())); }}Expected output:
200404A successful lookup with no item is different from an exception; the real controller must preserve server errors.
Return a publisher from a controller
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/main/java/lab/CatalogApplication.java; use the companion lab README.
package lab;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.*;import reactor.core.publisher.Mono;@SpringBootApplication@RestControllerpublic class CatalogApplication { public static void main(String[] args) { SpringApplication.run(CatalogApplication.class, args); } public record Item(String sku, int stock) {} @GetMapping("/items/{sku}") public Mono<ResponseEntity<Item>> item(@PathVariable("sku") String sku) { return Mono.justOrEmpty("B1".equals(sku) ? new Item("B1", 5) : null) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.notFound().build()); }}Predicted behavior: B1 returns HTTP 200 with stock 5; MISSING returns 404.
The framework subscribes. No block or manual subscribe is required.
Compose an HTTP client
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/main/java/lab/CatalogClient.java; use the companion lab README.
package lab;import java.time.Duration;import org.springframework.http.HttpStatus;import org.springframework.web.reactive.function.client.WebClient;import reactor.core.publisher.Mono;public class CatalogClient { // Inject a client with fixed trusted base URL, bounded codec size and connection timeout. private final WebClient client; public CatalogClient(WebClient client) { this.client = client; } public Mono<CatalogApplication.Item> read(String sku) { return client.get().uri("/items/{sku}", sku).exchangeToMono(response -> { if (response.statusCode().equals(HttpStatus.NOT_FOUND)) return Mono.empty(); if (response.statusCode().is2xxSuccessful()) return response.bodyToMono(CatalogApplication.Item.class); return response.createException().flatMap(Mono::error); }).timeout(Duration.ofSeconds(2)); }}Predicted behavior: 200 yields a decoded item; 404 completes empty; other unsuccessful statuses fail.
exchangeToMono makes status-dependent decoding explicit and releases unconsumed response bodies when the returned publisher terminates. Timeout is not a proof of remote cancellation.
Test the HTTP boundary
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/test/java/lab/BoundaryTest.java; use the companion lab README.
package lab;import java.time.Duration;import org.junit.jupiter.api.Test;import org.springframework.test.web.reactive.server.WebTestClient;class BoundaryTest { @Test void httpContractWithoutServer() { var client = WebTestClient.bindToController(new CatalogApplication()) .configureClient().responseTimeout(Duration.ofSeconds(2)).build(); client.get().uri("/items/B1").exchange().expectStatus().isOk() .expectBody().jsonPath("$.stock").isEqualTo(5); client.get().uri("/items/MISSING").exchange().expectStatus().isNotFound(); }}Predicted behavior: Mock HTTP verifies 200 and 404 without a real socket.
Use a separate server integration test for actual networking and codecs under deployment configuration.
Common mistakes
Do not add both MVC and WebFlux starters without understanding Boot web-application selection. Do not wrap an already executed blocking call in Mono.just. Never turn every HTTP error into 404 or accept arbitrary user-controlled base URLs.
Practice
Model a capacity-two resource gate using Semaphore. Acquire both permits without waiting, print whether a third succeeds, release both in finally, and print available permits.
Expected output:
false2Compare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
WebFlux boundaries and blocking — knowledge check
Reactive programming reasoning.
Who subscribes to a reactive controller return value?
Why is blocking on an event loop harmful?
What does boundedElastic accomplish for blocking legacy calls?
Which database API requires a reactive driver?
When might MVC with virtual threads be a good fit?