Part 1 of 7 — Reactive Backend Engineering with Java & Spring

Reactor and WebFlux: Mono, Flux, Operators, and the Event Loop

Oct 2026 · 7 min read

This article proves through tests that concat, merge, and zip produce different emission orders, that the switchIfEmpty argument is evaluated at assembly time unless wrapped in Mono.defer, and that blocking work must be moved to boundedElastic so it does not hold the Netty event loop thread. Everything runs on Spring Boot 4.1 with StepVerifier and WebTestClient.

Full code: https://github.com/Sch39/java-spring-boot

Problem

Reactor operators that look similar produce different orders, a fallback that appears lazy has actually already run, and a single blocking call in a handler is enough to hold the thread that serves all requests.

  1. Eager fallback: the switchIfEmpty argument is evaluated when the chain is assembled, so its side effects run even when the source contains a value.

  2. Blocking on the event loop: Thread.sleep or synchronous I/O in a handler uses Netty threads, whose number is small and fixed.

Outcome

Readers can:

  • Distinguish the emission orders of concat, merge, and zip on two delayed Flux sources without waiting in real time (virtual time).

  • Explain when the switchIfEmpty argument is executed and use Mono.defer to defer it until the source is proven empty.

  • Prove the difference between the Netty event loop thread and boundedElastic via WebTestClient on a real server.

Implementation

Folder Structure

text
RM01-01-reactor-basics/
├── build.gradle
└── src/
    ├── main/
    │   ├── java/dev/sch39/reactor_basics/
    │   │   ├── ReactorBasicsApplication.java
    │   │   ├── Streams.java
    │   │   ├── Fallbacks.java
    │   │   └── ThreadController.java
    │   └── resources/application.yml
    └── test/java/dev/sch39/reactor_basics/
        ├── StreamsTest.java
        ├── FallbacksTest.java
        └── ThreadControllerTest.java

Setup

Make sure the Spring Boot CLI is installed; if not, follow Installing Spring Boot :: Spring Boot.

Initialize one project (run from the / folder):

bash
mkdir -p RM01-01-reactor-basics
cd RM01-01-reactor-basics

spring init --build=gradle --type=gradle-project --java-version=21 --group-id=dev.sch39 --artifact-id=reactor-basics --name=reactor-basics --dependencies=webflux --extract .

# remove the default test so Run Test only contains the article's tests
rm src/test/java/dev/sch39/reactor_basics/ReactorBasicsApplicationTests.java

Code Blocks

Block 1: concat, merge, zip — different emission orders

RM01-01-reactor-basics/src/main/java/dev/sch39/reactor_basics/Streams.java:

java
package dev.sch39.reactor_basics;

import java.time.Duration;
import reactor.core.publisher.Flux;

public class Streams {

    public Flux<String> letters() {
        return Flux.just("A", "B", "C").delayElements(Duration.ofMillis(100));
    }

    public Flux<String> digits() {
        // start 50 ms after letters so the emissions interleave
        return Flux.just("1", "2", "3").delayElements(Duration.ofMillis(100))
                .delaySubscription(Duration.ofMillis(50));
    }

    public Flux<String> concatenated() {
        return Flux.concat(letters(), digits());
    }

    public Flux<String> merged() {
        return Flux.merge(letters(), digits());
    }

    public Flux<String> zipped() {
        return letters().zipWith(digits(), (letter, digit) -> letter + digit);
    }
}

Goal: Show that concat preserves source order, merge follows emission order, and zip pairs elements by index.

Block 2: switchIfEmpty — assembly time vs subscribe time

RM01-01-reactor-basics/src/main/java/dev/sch39/reactor_basics/Fallbacks.java:

java
package dev.sch39.reactor_basics;

import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Mono;

public class Fallbacks {

    private final AtomicInteger fallbackCalls = new AtomicInteger();

    public Mono<String> eager(Mono<String> source) {
        return source.switchIfEmpty(fallback());
    }

    public Mono<String> lazy(Mono<String> source) {
        return source.switchIfEmpty(Mono.defer(this::fallback));
    }

    public int fallbackCalls() {
        return fallbackCalls.get();
    }

    private Mono<String> fallback() {
        fallbackCalls.incrementAndGet();
        return Mono.just("default");
    }
}

Goal: Show that fallback() as a direct argument is called when the chain is assembled, whereas Mono.defer defers it until the source is empty.

Block 3: blocking call — event loop vs boundedElastic

RM01-01-reactor-basics/src/main/java/dev/sch39/reactor_basics/ThreadController.java:

java
package dev.sch39.reactor_basics;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@RestController
public class ThreadController {

    @GetMapping("/thread")
    public Mono<String> eventLoop() {
        return Mono.fromSupplier(() -> Thread.currentThread().getName());
    }

    @GetMapping("/thread/blocking")
    public Mono<String> offloaded() {
        return Mono.fromCallable(() -> {
            Thread.sleep(50);
            return Thread.currentThread().getName();
        }).subscribeOn(Schedulers.boundedElastic());
    }
}

Goal: Show that an ordinary handler runs on the event loop thread, whereas blocking work wrapped in fromCallable and subscribeOn(boundedElastic) runs on a separate thread.

Test Blocks

Test 1: Order of concat, merge, and zip

RM01-01-reactor-basics/src/test/java/dev/sch39/reactor_basics/StreamsTest.java:

java
package dev.sch39.reactor_basics;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;

class StreamsTest {

    private final Streams streams = new Streams();

    @Test
    void concatKeepsSourceOrderMergeFollowsEmissionOrderZipPairsByIndex() {
        StepVerifier.withVirtualTime(() -> streams.concatenated().collectList())
                .thenAwait(Duration.ofSeconds(2))
                .assertNext(list -> {
                    System.out.println("concat=" + list);
                    assertEquals(List.of("A", "B", "C", "1", "2", "3"), list, "concat");
                })
                .verifyComplete();

        StepVerifier.withVirtualTime(() -> streams.merged().collectList())
                .thenAwait(Duration.ofSeconds(2))
                .assertNext(list -> {
                    System.out.println("merge=" + list);
                    assertEquals(List.of("A", "1", "B", "2", "C", "3"), list, "merge");
                })
                .verifyComplete();

        StepVerifier.withVirtualTime(() -> streams.zipped().collectList())
                .thenAwait(Duration.ofSeconds(2))
                .assertNext(list -> {
                    System.out.println("zip=" + list);
                    assertEquals(List.of("A1", "B2", "C3"), list, "zip");
                })
                .verifyComplete();
    }
}

Goal: Prove that the three operators produce different orders from the same two sources, using virtual time so the test does not wait 2 real seconds.

Test 2: Eager vs deferred fallback

RM01-01-reactor-basics/src/test/java/dev/sch39/reactor_basics/FallbacksTest.java:

java
package dev.sch39.reactor_basics;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

class FallbacksTest {

    @Test
    void eagerFallbackRunsAtAssemblyTimeDeferredOnlyWhenEmpty() {
        Fallbacks eager = new Fallbacks();
        StepVerifier.create(eager.eager(Mono.just("value")))
                .expectNext("value")
                .verifyComplete();

        Fallbacks lazy = new Fallbacks();
        StepVerifier.create(lazy.lazy(Mono.just("value")))
                .expectNext("value")
                .verifyComplete();
        int withValue = lazy.fallbackCalls();
        StepVerifier.create(lazy.lazy(Mono.empty()))
                .expectNext("default")
                .verifyComplete();

        System.out.println("eager fallbackCalls=" + eager.fallbackCalls());
        System.out.println("lazy withValue=" + withValue + " afterEmpty=" + lazy.fallbackCalls());
        assertEquals(1, eager.fallbackCalls(), "eager fallbackCalls");
        assertEquals(0, withValue, "lazy withValue");
        assertEquals(1, lazy.fallbackCalls(), "lazy afterEmpty");
    }
}

Goal: Prove that the eager version calls the fallback even when the source contains a value, whereas the Mono.defer version only calls it when the source is empty.

Test 3: Event loop thread vs boundedElastic

RM01-01-reactor-basics/src/test/java/dev/sch39/reactor_basics/ThreadControllerTest.java:

java
package dev.sch39.reactor_basics;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
class ThreadControllerTest {

    @Autowired
    private WebTestClient client;

    @Test
    void blockingWorkMovesOffTheNettyEventLoop() {
        String eventLoop = client.get().uri("/thread").exchange()
                .returnResult(String.class).getResponseBody().blockFirst();
        String offloaded = client.get().uri("/thread/blocking").exchange()
                .returnResult(String.class).getResponseBody().blockFirst();

        System.out.println("eventLoop thread=" + eventLoop);
        System.out.println("offloaded thread=" + offloaded);
        assertTrue(eventLoop.startsWith("webflux-http-"), "eventLoop thread " + eventLoop);
        assertTrue(offloaded.startsWith("boundedElastic-"), "offloaded thread " + offloaded);
    }
}

Goal: Prove on a real Netty server that an ordinary handler runs on the event loop thread and blocking work runs on a boundedElastic thread.

Run Test

Run from the RM01-01-reactor-basics/ folder:

bash
./gradlew cleanTest test -i

Output:

text
...
FallbacksTest > eagerFallbackRunsAtAssemblyTimeDeferredOnlyWhenEmpty() STANDARD_OUT
    eager fallbackCalls=1
    lazy withValue=0 afterEmpty=1

StreamsTest > concatKeepsSourceOrderMergeFollowsEmissionOrderZipPairsByIndex() STANDARD_OUT
    concat=[A, B, C, 1, 2, 3]
    merge=[A, 1, B, 2, C, 3]
    zip=[A1, B2, C3]

ThreadControllerTest STANDARD_OUT
    21:12:40.181 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils ...
> Task :test

ThreadControllerTest > blockingWorkMovesOffTheNettyEventLoop() STANDARD_OUT
    eventLoop thread=webflux-http-epoll-2
    offloaded thread=boundedElastic-1
...
BUILD SUCCESSFUL in 13s
5 actionable tasks: 2 executed, 3 up-to-date
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.8.2/userguide/configuration_cache_enabling.html

Why It Works

Assembly time vs subscribe time: fallback() is a plain Java method call evaluated as an argument when the chain is assembled, so the counter increments even when Mono.just("value") contains a value. Mono.defer defers the creation of the publisher until there is a subscription, and switchIfEmpty only subscribes to the alternative when the source completes without an element. The Reactor documentation notes that just captures the value at assembly time and that defer turns it into a cold publisher.

concat, merge, zip: concat only subscribes to the next source after the previous source completes, so the result is ordered per source. merge subscribes to all sources at once and emits elements in emission order: A (100 ms), 1 (150 ms), B (200 ms), and so on. zip waits for one element from each side and then pairs them by index.

Event loop and boundedElastic: WebFlux assumes the application does not block, so the non-blocking server uses a small thread pool with a fixed size. Mono.fromCallable wraps a synchronous call and subscribeOn(Schedulers.boundedElastic()) moves its execution to a pool with a bounded number of threads. The output shows /thread running on webflux-http-epoll-2 and /thread/blocking on boundedElastic-1.

Edge Cases

merge in real time: merge follows real emission order, so two sources whose emissions are close together can swap on a real timer. The test here is deterministic because it uses virtual time.

Supplier on withVirtualTime: The Reactor documentation requires that the Flux be created inside the Supplier lambda. If the Flux is created beforehand outside the lambda, virtual time is not guaranteed to apply.

zip with different lengths: zip stops at the source with the fewest elements, so the remaining elements of the longer source are never paired.

Trade-offs

Strategy

Pro

Con

Leave blocking on the event loop

No extra code

Holds the Netty threads, whose number is small and fixed

Mono.fromCallable + subscribeOn(boundedElastic)

Moves blocking to a pool with a bounded number of threads

Extra threads; the work is still blocking

Switch to a non-blocking client

No extra threads needed

Requires a reactive library that may not be available

Best practice: Prefer non-blocking APIs. If blocking is unavoidable, wrap it with Mono.fromCallable and attach subscribeOn(Schedulers.boundedElastic()) right after the source.

Gotchas I Ran Into

  • spring init --build=gradle ... alone fails with Multiple types found with build 'gradle' and format 'project' use --type with a more specific value [gradle-project, gradle-project-kotlin]; add --type=gradle-project. Without --java-version=21, the generated build.gradle uses the Java 17 toolchain.

  • @WebFluxTest with WebTestClient does not start Netty (the log does not contain Netty started on port), and the /thread handler reports the parallel-1 thread, not the event loop thread. To measure the Netty thread, use @SpringBootTest(webEnvironment = RANDOM_PORT) with @AutoConfigureWebTestClient.

  • The Netty event loop thread in Spring Boot 4.1.2 on Linux is named webflux-http-epoll-2, not reactor-http-nio-* as in the Spring documentation examples; the startsWith("reactor-http-") assertion fails until the prefix is changed.

Production Checklist

  • Are there blocking calls (JDBC, Thread.sleep, synchronous I/O) in a handler? Wrap them with Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()).

  • Does the switchIfEmpty argument call a method with side effects or a cost (query, HTTP call)? Wrap it with Mono.defer.

  • Do time-based operator tests still wait in real time? Replace them with StepVerifier.withVirtualTime and create the Flux inside the lambda.

References