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
Monois a recipe, not a running task. When your controller returns it, Spring subscribes and the work starts. AMonoyou 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.findByIdand the pricing call are both started, andzip(orasync/awaitin Kotlin) combines them when both are ready. The total time is the slower of the two, not the sum.timeout(300 ms)andonErrorResumegive the price call a deadline and a fallback, so a slow pricing service can’t hold the page.switchIfEmptyturns “no product” into a 404.liveOrdersreturns 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
suspendfunction: 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?
Reactive repositories return lazy publishers. orderRepository.save(order) only builds a recipe; since its Mono is ignored, it's never subscribed, and no SQL is executed. The client gets a 200 with an order that doesn't exist. Return the pipeline instead: return orderRepository.save(Order.from(r));, so the framework's subscription runs the insert. (In Kotlin coroutines, save is a suspend function you call directly, which avoids this class of bug.)
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);
});
}Hint: Which thread runs the lambda inside map, and what does restTemplate do with it?
map runs on the event-loop thread that delivered the item, and RestTemplate blocks that thread for the whole HTTP call. With four event-loop threads, four slow calls stop the server from handling any request or connection, including health checks. It works in local testing and collapses under load.
Use the non-blocking client and flatMap, which subscribes to the inner call without blocking (and limit how many run at once):
.flatMap({ item ->
users.get().uri("/{id}", item.authorId)
.retrieve().bodyToMono(Author::class.java)
.map(item::withAuthor)
}, 16) // at most 16 concurrent author calls.flatMap(item -> users.get().uri("/{id}", item.authorId())
.retrieve().bodyToMono(Author.class)
.map(item::withAuthor),
16) // at most 16 concurrent author callsBetter still, fetch all authors of the page in one batch call. Add BlockHound to tests to catch blocking calls on event-loop threads automatically.
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
| Need | Operator |
|---|---|
| Combine independent results | Mono.zip, Flux.zip; Kotlin: async/await |
| Call per element, concurrently | flatMap(fn, concurrency); ordered: flatMapSequential; one at a time: concatMap |
| Latest only (search as you type) | switchMap |
| Deadline and fallback | timeout, onErrorResume, onErrorReturn |
| Retry with backoff | retryWhen(Retry.backoff(3, Duration.ofMillis(100)).jitter(0.5)) |
| Bridge blocking code | Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) |
| Request-scoped data | contextWrite, deferContextual, Micrometer context propagation |
- Event loop sized to cores; handlers return lazy
Mono/Fluxthat 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;
boundedElasticas a bridge. zip/flatMap(fn, concurrency)/concatMap/switchMap;timeout+onErrorResume;retryWhen(Retry.backoff…).- Backpressure via request(n);
publishOn/subscribeOnmove execution. - Context: Reactor
Context+ Micrometer context propagation instead of ThreadLocals. Kotlin:suspendhandlers andFlow.
Check this part
What does a Mono represent?
Why is a JDBC query inside a WebFlux map a problem?
A handler calls repository.save(order) and returns Mono.just(order). Is the order saved?
How do you call another service once per item without overwhelming it?