Skip to content
Commitwise
Menu
Java Backend

Reactive Spring with WebFlux

Understand non-blocking servers and the event loop, build endpoints with Mono and Flux, WebClient and R2DBC, combine calls concurrently with timeouts and fallbacks, stream with server-sent events, avoid the classic bugs (blocking the event loop, nothing subscribed, unbounded flatMap), and choose between WebFlux, Kotlin coroutines and Spring MVC on virtual threads.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A notifications gateway keeps 50,000 mobile clients connected through server-sent events and calls three services per message. With classic Spring MVC, each open connection held a thread, and the team ran out of threads (and memory) long before CPU. They moved it to Spring WebFlux and it ran on four cores with a handful of threads. Then someone added a restTemplate call inside a map, and under load the whole gateway froze.

Reactive servers don’t give each request its own thread. A few event-loop threads handle everything, and code is written as pipelines of Mono (zero or one value) and Flux (many values) that run when data arrives. That makes them excellent for many concurrent, mostly waiting connections, and unforgiving of a single blocking call. This lesson covers how WebFlux works, the bugs that bite, and when you should choose it today, now that virtual threads exist.

New to some of these? Open what you need, or skip ahead.

Basics:What is a thread pool?

A server handles each request on a thread. Threads are limited (Tomcat’s default is 200), so they’re kept in a pool and reused. A thread waiting for a slow network call can’t serve anyone else. If every thread is waiting, new requests queue up and eventually fail, even though the CPU is idle.

Basics:Blocking and non-blocking calls

A blocking call stops the thread until the result arrives: restTemplate.getForObject(…) or a JDBC query. A non-blocking call starts the work and returns immediately; the result is delivered later, through a callback, a future, or a reactive stream. While waiting, the thread is free to do other work.

Part Not started

Mono, Flux and the event loop

Think of a restaurant. In a classic server, each table gets its own waiter, who stands next to the kitchen until the food is ready: 200 tables need 200 waiters, mostly standing around. In a reactive server, a few waiters take orders, hand them to the kitchen, and serve other tables; when a dish is ready, the kitchen rings a bell and any free waiter brings it out.

In code, you describe what should happen when data arrives, using two types:

  • Mono<T>: a result that will arrive later: zero or one value (like a single product).
  • Flux<T>: a stream of values that arrive over time (like orders as they’re placed).

Two rules matter most:

  • Nothing happens until someone subscribes. A Mono is a recipe, not a running task. When your controller returns it, Spring subscribes and the work starts. A Mono you create and forget never runs.
  • Never block. There are only a few threads. If one of them waits for a slow call (Thread.sleep, JDBC, RestTemplate), every request assigned to that thread waits too.

So WebFlux apps use non-blocking clients everywhere: WebClient for HTTP, R2DBC for SQL databases, and the reactive drivers for Redis, MongoDB and Kafka.

WebFlux runs on Reactor Netty with an event loop sized to the CPU count; handlers return Publishers that the framework subscribes to. Reactor types are lazy (assembly vs subscription time), composable (map, flatMap, zip, switchIfEmpty, timeout, retryWhen, onErrorResume) and support backpressureBackpressureA way for a consumer to tell a producer to slow down, so fast producers don't overwhelm slow consumers.Open in glossary → (subscribers request n items; Netty propagates it to the socket). Operators run on whatever thread signals them unless moved with publishOn (downstream) or subscribeOn (subscription and upstream). Blocking on an event-loop thread stalls every connection multiplexed on it; detect it with BlockHound in tests, and isolate unavoidable blocking calls with Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()). The whole I/O path must be non-blocking for the model to pay off: WebClient, R2DBC (no JPA, lazy loading or Hibernate sessions), reactive Redis/Kafka/Mongo clients. Error handling is part of the pipeline; ThreadLocal-based context (MDC, security) needs Reactor Context and Micrometer context propagation. Kotlin users can write the same handlers as suspend functions and Flows, which WebFlux supports natively.

@RestController
class ProductController(
    private val products: ProductRepository,                     // R2DBC: CoroutineCrudRepository<Product, Long>
    builder: WebClient.Builder,
) {
    private val pricing = builder.baseUrl("http://pricing").build()

    @GetMapping("/products/{id}")
    suspend fun product(@PathVariable id: Long): ProductView = coroutineScope {
        val product = async { products.findById(id) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND) }
        val price = async {
            try {
                withTimeout(300) { pricing.get().uri("/prices/{id}", id).retrieve().awaitBody<Price>() }
            } catch (e: TimeoutCancellationException) {
                Price.unknown()                                  // the page still renders
            } catch (e: WebClientException) {
                Price.unknown()
            }
        }
        ProductView(product.await(), price.await())              // both run concurrently
    }

    @GetMapping("/orders/live", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
    fun liveOrders(): Flow<OrderEvent> = orderEvents.asFlow()   // server-sent events, one connection per client
}
@RestController
class ProductController {
    private final ProductRepository products;           // R2DBC: ReactiveCrudRepository<Product, Long>
    private final WebClient pricing;

    ProductController(ProductRepository products, WebClient.Builder builder) {
        this.products = products;
        this.pricing = builder.baseUrl("http://pricing").build();
    }

    @GetMapping("/products/{id}")
    Mono<ProductView> product(@PathVariable long id) {
        Mono<Product> product = products.findById(id)
            .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
        Mono<Price> price = pricing.get().uri("/prices/{id}", id)
            .retrieve()
            .bodyToMono(Price.class)
            .timeout(Duration.ofMillis(300))
            .onErrorResume(e -> Mono.just(Price.unknown()));     // the page still renders
        return Mono.zip(product, price, ProductView::new);        // both run concurrently
    }

    @GetMapping(value = "/orders/live", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<OrderEvent> liveOrders() {
        return orderEvents.asFlux();                             // server-sent events, one connection per client
    }
}
  • products.findById and the pricing call are both started, and zip (or async/await in Kotlin) combines them when both are ready. The total time is the slower of the two, not the sum.
  • timeout(300 ms) and onErrorResume give the price call a deadline and a fallback, so a slow pricing service can’t hold the page.
  • switchIfEmpty turns “no product” into a 404.
  • liveOrders returns a stream: each new order is pushed to connected clients as a server-sent event. Thousands of open streams cost almost no threads.
  • In Kotlin, the same handler is a suspend function: it reads like normal sequential code, and WebFlux runs it without blocking.

Predict the output

A handler does: Mono<Order> create(OrderRequest r) { Order order = Order.from(r); orderRepository.save(order); return Mono.just(order); } with a reactive (R2DBC) repository. What ends up in the database?

Spot the bugA gateway that freezes under load

Tap the line with the bug.

@GetMapping("/feed/{userId}")
fun feed(@PathVariable userId: String): Flux<FeedItem> =
    feedRepository.findByUserId(userId)
        .map { item ->
            val author = restTemplate.getForObject("http://users/{id}", Author::class.java, item.authorId)
            item.withAuthor(author!!)
        }
@GetMapping("/feed/{userId}")
Flux<FeedItem> feed(@PathVariable String userId) {
    return feedRepository.findByUserId(userId)
        .map(item -> {
            Author author = restTemplate.getForObject("http://users/{id}", Author.class, item.authorId());
            return item.withAuthor(author);
        });
}

Exercisemedium

Make a handler reactive end to end

A WebFlux handler loads a user with jdbcTemplate.queryForObject(…) and their recent orders with a WebClient call, then returns both. What’s wrong, and how would you fix it if you can’t switch the user query to R2DBC yet?

›

JDBC is blocking. Where can blocking code run in a reactive app without stalling the event loop?

SolutionTry it yourself first

The JDBC call blocks an event-loop thread. Until the database access moves to R2DBC, wrap it and move it to a scheduler meant for blocking work:

suspend fun userWithOrders(id: Long): UserWithOrders = coroutineScope {
    val user = async(Dispatchers.IO) { jdbcTemplate.queryForObject(SQL, userMapper, id)!! }   // blocking, off the event loop
    val orders = async { ordersClient.get().uri("/users/{id}/orders", id).retrieve().awaitBody<List<Order>>() }
    UserWithOrders(user.await(), orders.await())
}
Mono<User> user = Mono.fromCallable(() -> jdbcTemplate.queryForObject(SQL, userMapper, id))
    .subscribeOn(Schedulers.boundedElastic());        // runs on a pool for blocking calls
Mono<List<Order>> orders = ordersClient.get().uri("/users/{id}/orders", id)
    .retrieve().bodyToFlux(Order.class).collectList();
return Mono.zip(user, orders, UserWithOrders::new);

boundedElastic (or Dispatchers.IO) is a separate pool that may block, so the event loop stays free. It’s a bridge, not a goal: an app that blocks most of the time gets nothing from WebFlux.

Operators that matter

NeedOperator
Combine independent resultsMono.zip, Flux.zip; Kotlin: async/await
Call per element, concurrentlyflatMap(fn, concurrency); ordered: flatMapSequential; one at a time: concatMap
Latest only (search as you type)switchMap
Deadline and fallbacktimeout, onErrorResume, onErrorReturn
Retry with backoffretryWhen(Retry.backoff(3, Duration.ofMillis(100)).jitter(0.5))
Bridge blocking codeMono.fromCallable(...).subscribeOn(Schedulers.boundedElastic())
Request-scoped datacontextWrite, deferContextual, Micrometer context propagation
  • Event loop sized to cores; handlers return lazy Mono/Flux that the framework subscribes to. Ignored publishers never run.
  • Non-blocking end to end: WebClient, R2DBC (no JPA), reactive Redis/Kafka/Mongo. Blocking on the event loop stalls all connections; BlockHound in tests; boundedElastic as a bridge.
  • zip/flatMap(fn, concurrency)/concatMap/switchMap; timeout + onErrorResume; retryWhen(Retry.backoff…).
  • Backpressure via request(n); publishOn/subscribeOn move execution.
  • Context: Reactor Context + Micrometer context propagation instead of ThreadLocals. Kotlin: suspend handlers and Flow.

Check this part

  1. What does a Mono represent?

  2. Why is a JDBC query inside a WebFlux map a problem?

  3. A handler calls repository.save(order) and returns Mono.just(order). Is the order saved?

  4. How do you call another service once per item without overwhelming it?

WebFlux runs on a few event-loop threads; handlers return Mono (0..1) or Flux (0..n) pipelines that run when subscribed, which the framework does for returned publishers. Use non-blocking clients end to end: WebClient, R2DBC, reactive Redis and Kafka. Combine calls with zip and flatMap, add timeout and onErrorResume per call. Never block an event-loop thread; offload unavoidable blocking work to boundedElastic.

Part Not started

WebFlux, coroutines or virtual threads?

Since Java 21, there’s a simpler way to handle many waiting requests: virtual threads. They’re so cheap that the server can give every request its own thread again, even 100,000 of them, and blocking code (JDBC, RestTemplate) becomes fine, because a waiting virtual thread doesn’t hold a real one.

So how do you choose?

  • Spring MVC with virtual threads: most request-response services (CRUD APIs, admin backends). Simple code, JPA works, easy debugging.
  • WebFlux: lots of long-lived connections and streams (server-sent events, WebSockets, a gateway proxying traffic), or when you need backpressure, and you can use non-blocking libraries everywhere.
  • Kotlin + WebFlux with coroutines: if your team writes Kotlin and needs WebFlux, suspend functions keep the code readable.

WebFlux is the better tool for high-fan-in streaming and connection-heavy workloads (SSE and WebSocket gateways, proxies, streaming aggregation), end-to-end backpressure, and environments where every dependency already has a non-blocking client. Spring MVC on virtual threads (spring.threads.virtual.enabled=true) covers most request-response services with blocking-style code, JDBC/JPA, ThreadLocal-based libraries and readable stack traces; limits shift to connection pools and downstream capacity, so bulkheads still matter, and pinning (native frames, older synchronized behavior) should be checked with JFR. Kotlin coroutines on WebFlux combine the non-blocking runtime with sequential code and structured concurrency (cancellation propagates, coroutineScope scopes child calls). Reactive’s costs are real: assembly-time vs runtime stack traces (use checkpoint() or the Reactor debug agent), context propagation for MDC, tracing and security, a smaller ecosystem (R2DBC instead of JPA), and a steeper learning curve. A mixed estate is normal: a reactive edge gateway and MVC-on-virtual-threads business services.

// application.yml: spring.threads.virtual.enabled: true
@RestController
class ProductController(
    private val products: ProductRepository,           // Spring Data JPA, blocking: fine on virtual threads
    builder: RestClient.Builder,
) {
    private val pricing = builder.baseUrl("http://pricing").build()  // configure timeouts on the request factory
    private val executor = Executors.newVirtualThreadPerTaskExecutor()

    @GetMapping("/products/{id}")
    fun product(@PathVariable id: Long): ProductView {
        val product = executor.submit<Product> { products.findById(id).orElseThrow { NotFoundException() } }
        val price = executor.submit<Price> { priceOrUnknown(id) }
        return ProductView(product.get(), price.get())               // both run concurrently, plain blocking code
    }

    private fun priceOrUnknown(id: Long): Price =
        try {
            pricing.get().uri("/prices/{id}", id).retrieve().body<Price>()!!
        } catch (e: RestClientException) {
            Price.unknown()
        }
}
// application.yml: spring.threads.virtual.enabled: true
@RestController
class ProductController {
    private final ProductRepository products;          // Spring Data JPA, blocking: fine on virtual threads
    private final RestClient pricing;
    private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

    ProductController(ProductRepository products, RestClient.Builder builder) {
        this.products = products;
        this.pricing = builder.baseUrl("http://pricing").build();   // configure timeouts on the request factory
    }

    @GetMapping("/products/{id}")
    ProductView product(@PathVariable long id) throws Exception {
        Future<Product> product = executor.submit(() -> products.findById(id).orElseThrow(NotFoundException::new));
        Future<Price> price = executor.submit(() -> priceOrUnknown(id));
        return new ProductView(product.get(), price.get());          // both run concurrently, plain blocking code
    }

    private Price priceOrUnknown(long id) {
        try {
            return pricing.get().uri("/prices/{id}", id).retrieve().body(Price.class);
        } catch (RestClientException e) {
            return Price.unknown();
        }
    }
}
  • The request runs on a virtual thread, so blocking calls (JPA, RestClient) are fine: while one waits, the real thread serves others.
  • The two calls still run in parallel, each on its own virtual thread, and get() waits for both.
  • Compare it with the WebFlux version: same behavior, ordinary Java, and JPA works.

Production puzzles

Predict the output

A WebFlux service logs with MDC (a ThreadLocal) to attach the request id to every log line, set in a WebFilter. Logs written inside flatMap after a WebClient call often have no request id. Why?

Exercisehard

Pick the stack

Three new services: (1) an admin CRUD API over PostgreSQL with complex JPA mappings; (2) a notifications gateway holding 100,000 SSE connections and fanning out messages from Kafka; (3) a pricing service that calls four internal services per request with a 200 ms budget. Which stack for each, and why?

›

Look at connection count and lifetime, the persistence technology, and whether the code mostly waits or streams.

SolutionTry it yourself first
  1. Admin CRUD: Spring MVC on virtual threads with JPA. Request-response, complex mappings, low concurrency; reactive would only add cost.
  2. Notifications gateway: WebFlux (Java or Kotlin coroutines/Flow) with reactive Kafka. Long-lived streaming connections and fan-out are where the event loop and backpressure shine; slow clients must not hold threads or buffer unboundedly (onBackpressureDrop or bounded buffers per connection).
  3. Pricing service: either works. MVC on virtual threads with structured concurrency (parallel calls, per-call timeouts) is simpler; WebFlux or coroutines if the team already runs reactive and needs fine-grained cancellation. The key requirements, parallel calls, deadlines and fallbacks, are the same in both.
  • WebFlux: streaming (SSE, WebSockets), gateways and proxies, backpressure, fully non-blocking stacks.
  • MVC on virtual threads: most request-response services; blocking code, JDBC/JPA, ThreadLocals and readable traces; limits move to pools and downstreams.
  • Kotlin: suspend handlers and Flow on WebFlux, structured concurrency and cancellation.
  • Reactive costs: debugging (checkpoint(), debug agent), context propagation (Reactor Context + Micrometer), no JPA, learning curve. Mixed estates are normal.

Check this part

  1. Which fits a CRUD API with JPA best since Java 21?

  2. Where does WebFlux clearly shine?

  3. Why does MDC lose the request id in reactive pipelines?

  4. With virtual threads, what still limits concurrency?

WebFlux pays off for many concurrent, mostly waiting connections, streaming (SSE, WebSockets) and backpressure, when the whole I/O stack is non-blocking. Since Java 21, Spring MVC on virtual threads gives similar concurrency for request-response services with simple blocking code, JDBC and JPA. Kotlin coroutines make WebFlux code sequential. Reactive costs: harder debugging, stack traces and context propagation, and no JPA.

Key takeaways

  • Reactive servers use a few threads and pipelines of Mono and Flux.
  • Nothing runs until it’s subscribed; return your pipelines.
  • Never block an event-loop thread; use WebClient and R2DBC.
  • For most CRUD services, Spring MVC on virtual threads is simpler; WebFlux shines for streaming and many connections.
  • Go reactive end to end or not at all; detect blocking with BlockHound.
  • Bound concurrency in flatMap, add timeouts and fallbacks per call.
  • Plan for context propagation, debugging and the R2DBC ecosystem.
  • Choose per service: WebFlux or coroutines for streaming edges, virtual threads for request-response business logic.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.