Reactor operators, backpressure and schedulers

Every Spring WebFlux handler returns a Mono or a Flux, and how it behaves depends on the Reactor operators inside it. This page explains how a Reactor pipeline runs, then shows each important operator family running: ordering in flatMap, empty results, errors and retries, backpressure, threads, Context and testing with virtual time.

Contents

How a Reactor pipeline runs

Spring WebFlux is built on Project Reactor. A controller method returns a Mono (zero or one value) or a Flux (zero to many values), and WebFlux subscribes to it when it writes the response. Everything between the source and that subscription is a chain of operators, and most WebFlux bugs are really operator bugs.

Three ideas explain almost all of Reactor's behaviour:

  • Assembly is not execution: calling map or flatMap only builds a description of the work and returns a new, immutable publisher. Nothing runs until something subscribes.
  • Signals flow down, requests flow up: a subscriber asks for n items with request(n), and the source sends at most that many onNext signals, followed by onComplete or onError. This demand is called backpressure.
  • Each subscription is separate: most publishers are cold, so every subscriber triggers the whole pipeline again, including any HTTP call or database query inside it.

This program builds a pipeline, shows that nothing ran, then subscribes twice:

Java
import reactor.core.publisher.Flux;

public class LazyAssembly {

    public static void main(String[] args) {
        System.out.println("1. Building the pipeline");
        Flux<Integer> pipeline = Flux.range(1, 3)
                .doOnSubscribe(s -> System.out.println("   subscribed"))
                .doOnRequest(n -> System.out.println("   request(" + n + ")"))
                .map(i -> {
                    System.out.println("   map " + i);
                    return i * 10;
                });
        System.out.println("   pipeline built, nothing ran yet");

        System.out.println("2. First subscriber");
        pipeline.subscribe(v -> System.out.println("   got " + v),
                e -> System.out.println("   error " + e),
                () -> System.out.println("   complete"));

        System.out.println("3. Second subscriber runs everything again");
        pipeline.take(1).subscribe(v -> System.out.println("   got " + v));

        System.out.println("4. Operators return new instances");
        Flux<Integer> source = Flux.just(1, 2, 3);
        source.map(i -> i * 100);
        source.subscribe(v -> System.out.println("   source still emits " + v));
    }
}
Output
1. Building the pipeline
   pipeline built, nothing ran yet
2. First subscriber
   subscribed
   request(9223372036854775807)
   map 1
   got 10
   map 2
   got 20
   map 3
   got 30
   complete
3. Second subscriber runs everything again
   subscribed
   request(1)
   map 1
   got 10
4. Operators return new instances
   source still emits 1
   source still emits 2
   source still emits 3
  • "pipeline built, nothing ran yet" is printed before any map line: building the chain did no work.
  • The plain subscribe call requested 9223372036854775807 items, which is Long.MAX_VALUE and means "unbounded". Values then flowed one at a time: map 1, got 10, map 2, and so on.
  • The second subscriber ran map 1 again. With take(1), Reactor requested only 1 item, so the source produced just one.
  • Step 4 called source.map(...) and threw the result away. The source still emits 1, 2, 3, because operators never change the publisher they are called on. Forgetting to use the returned value is a common mistake.
Operator families covered on this page
FamilyOperatorsUse for
Transformingmap, flatMap, concatMap, flatMapSequentialChanging each value, or calling something asynchronous per value
Empty resultsdefaultIfEmpty, switchIfEmpty, filter, hasElementLookups that find nothing
Combiningzip, merge, concat, firstWithValueCalling several services and joining the results
ErrorsonErrorReturn, onErrorResume, onErrorMap, retry, retryWhenFallbacks, translation and retries
DemandlimitRate, onBackpressureBuffer, onBackpressureDropSources faster than their consumers
ThreadspublishOn, subscribeOnMoving work off the event loop
ContextcontextWrite, deferContextualRequest-scoped data such as a request id

The examples are plain Java programs using Reactor 3.8.8, the version managed by Spring Boot 4.1.2, so each operator can be seen on its own. Inside a WebFlux controller the same pipeline is subscribed by the framework instead of by block(). The Spring WebFlux page covers the server side.

map, flatMap, concatMap and flatMapSequential

map applies a plain function and returns the result at once. When the function itself returns a Mono, such as a remote call, you need one of the flattening operators, and they differ in ordering and concurrency. The fake lookup below takes 300 ms for user 1, 100 ms for user 2 and 200 ms for user 3, so a different finishing order is easy to see:

Java
import java.time.Duration;
import java.util.List;
import java.util.function.Function;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class FlatMapOrdering {

    // A fake remote lookup: user 1 is slow, user 2 is fast, user 3 is in between
    static Mono<String> lookup(int id) {
        long millis = switch (id) {
            case 1 -> 300;
            case 2 -> 100;
            default -> 200;
        };
        return Mono.delay(Duration.ofMillis(millis)).map(t -> "user" + id);
    }

    static void run(String name, Function<Flux<Integer>, Flux<String>> operator) {
        long start = System.nanoTime();
        List<String> result = operator.apply(Flux.just(1, 2, 3)).collectList().block();
        long millis = (System.nanoTime() - start) / 1000000;
        long rounded = Math.round(millis / 100.0) * 100;
        System.out.printf("%-18s %s  about %d ms%n", name, result, rounded);
    }

    public static void main(String[] args) {
        Flux.just(1).flatMap(FlatMapOrdering::lookup).blockLast(); // warm-up, not timed
        run("map", ids -> ids.map(id -> "user" + id));
        run("flatMap", ids -> ids.flatMap(FlatMapOrdering::lookup));
        run("concatMap", ids -> ids.concatMap(FlatMapOrdering::lookup));
        run("flatMapSequential", ids -> ids.flatMapSequential(FlatMapOrdering::lookup));
        run("flatMap(conc. 1)", ids -> ids.flatMap(FlatMapOrdering::lookup, 1));
    }
}
Output
map                [user1, user2, user3]  about 0 ms
flatMap            [user2, user3, user1]  about 300 ms
concatMap          [user1, user2, user3]  about 600 ms
flatMapSequential  [user1, user2, user3]  about 300 ms
flatMap(conc. 1)   [user1, user2, user3]  about 600 ms
  • flatMap subscribed to all three lookups at once and emitted each result as soon as it arrived: user2 first, user1 last. The total was about 300 ms, the time of the slowest call.
  • concatMap waited for each lookup to finish before starting the next, so the order is kept, and the time is the sum, about 600 ms.
  • flatMapSequential ran the lookups concurrently, like flatMap, but buffered early results to emit them in the original order. It also took about 300 ms.
  • flatMap with a concurrency of 1 behaves like concatMap.

flatMap subscribes to at most 256 inner publishers at a time by default (Queues.SMALL_BUFFER_SIZE). Passing a smaller concurrency, as in flatMap(this::call, 8), is the usual way to avoid sending hundreds of requests to another service at once.

Empty results and the eager switchIfEmpty trap

A Mono that completes without a value is empty. Repository lookups that find nothing, and filter calls that reject a value, both produce one. WebFlux writes an empty Mono as a 200 response with no body, so empty cases need explicit handling. This example uses a cache lookup that falls back to a database:

Java
import reactor.core.publisher.Mono;

public class EmptyAndDefaults {

    static Mono<String> findInCache(String key) {
        return key.equals("known") ? Mono.just("cached " + key) : Mono.empty();
    }

    static Mono<String> loadFromDatabase(String key) {
        System.out.println("   loadFromDatabase(" + key + ") called");
        return Mono.just("loaded " + key);
    }

    public static void main(String[] args) {
        System.out.println("defaultIfEmpty, a fixed value:");
        System.out.println("   " + findInCache("other").defaultIfEmpty("none").block());

        System.out.println("switchIfEmpty(loadFromDatabase(key)), cache hit:");
        String hit = findInCache("known").switchIfEmpty(loadFromDatabase("known")).block();
        System.out.println("   result: " + hit);

        System.out.println("switchIfEmpty(Mono.defer(...)), cache hit:");
        String lazy = findInCache("known")
                .switchIfEmpty(Mono.defer(() -> loadFromDatabase("known"))).block();
        System.out.println("   result: " + lazy);

        System.out.println("switchIfEmpty(Mono.defer(...)), cache miss:");
        String miss = findInCache("other")
                .switchIfEmpty(Mono.defer(() -> loadFromDatabase("other"))).block();
        System.out.println("   result: " + miss);

        System.out.println("filter can turn a value into empty:");
        Mono<Integer> adult = Mono.just(15).filter(age -> age >= 18);
        System.out.println("   block() returns " + adult.block());
        System.out.println("   hasElement: " + adult.hasElement().block());

        System.out.println("map returning null:");
        try {
            Mono.just("x").map(s -> (String) null).block();
        } catch (NullPointerException e) {
            // the message names the lambda class, which differs between runs
            System.out.println("   NullPointerException: "
                    + e.getMessage().replaceFirst("\\[.*\\]", "[lambda]"));
        }
    }
}
Output
defaultIfEmpty, a fixed value:
   none
switchIfEmpty(loadFromDatabase(key)), cache hit:
   loadFromDatabase(known) called
   result: cached known
switchIfEmpty(Mono.defer(...)), cache hit:
   result: cached known
switchIfEmpty(Mono.defer(...)), cache miss:
   loadFromDatabase(other) called
   result: loaded other
filter can turn a value into empty:
   block() returns null
   hasElement: false
map returning null:
   NullPointerException: The mapper [lambda] returned a null value.
  • defaultIfEmpty("none") replaced the empty result with a fixed value.
  • With switchIfEmpty(loadFromDatabase("known")), the cache hit, but "loadFromDatabase(known) called" still printed. Java evaluates method arguments before the call, so the fallback method ran while the pipeline was being built. If the method starts a query directly instead of returning a lazy Mono, that is a wasted database call on every cache hit.
  • Wrapping the fallback in Mono.defer postponed it until the source was actually empty: nothing was printed on the hit, and the database was called only on the miss.
  • filter turned 15 into an empty Mono, so block() returned null, and hasElement() reported false.
  • A map function must never return null. Reactor fails with a NullPointerException naming the mapper. Use mapNotNull or handle when a mapping may produce no value.

Combining streams: concat, merge, zip

A WebFlux endpoint often gathers data from several sources. The combining operators differ in when they subscribe and how they order values. Two timers with different periods, 100 ms and 140 ms, make the ordering differences visible:

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

public class CombiningStreams {

    static Flux<String> ticks(String prefix, long periodMillis, int count) {
        return Flux.interval(Duration.ofMillis(periodMillis))
                .take(count)
                .map(i -> prefix + i);
    }

    static Mono<String> call(String name, long millis) {
        return Mono.delay(Duration.ofMillis(millis)).thenReturn(name);
    }

    public static void main(String[] args) {
        // a ticks every 100 ms, b every 140 ms, so their elements interleave
        System.out.println("concat: " + Flux.concat(ticks("a", 100, 3), ticks("b", 140, 3))
                .collectList().block());
        System.out.println("merge : " + Flux.merge(ticks("a", 100, 3), ticks("b", 140, 3))
                .collectList().block());
        System.out.println("zip   : " + Flux.zip(ticks("a", 100, 3), ticks("b", 140, 2),
                (x, y) -> x + "+" + y).collectList().block());

        long start = System.nanoTime();
        String profile = Mono.zip(call("user", 300), call("orders", 200), call("prefs", 100))
                .map(t -> t.getT1() + ", " + t.getT2() + ", " + t.getT3())
                .block();
        long millis = (System.nanoTime() - start) / 1000000;
        System.out.println("Mono.zip of three calls: " + profile
                + " in about " + Math.round(millis / 100.0) * 100 + " ms");

        String partial = Mono.zip(call("user", 100), Mono.<String>empty())
                .map(t -> t.getT1() + t.getT2())
                .defaultIfEmpty("zip with an empty Mono is empty")
                .block();
        System.out.println(partial);

        String first = Mono.firstWithValue(call("slow mirror", 300), call("fast mirror", 100))
                .block();
        System.out.println("firstWithValue: " + first);
    }
}
Output
concat: [a0, a1, a2, b0, b1, b2]
merge : [a0, b0, a1, b1, a2, b2]
zip   : [a0+b0, a1+b1]
Mono.zip of three calls: user, orders, prefs in about 300 ms
zip with an empty Mono is empty
firstWithValue: fast mirror
  • concat subscribed to b only after a completed, so all a values come first.
  • merge subscribed to both at once and emitted values in arrival order: a0 at 100 ms, b0 at 140 ms, a1 at 200 ms, b1 at 280 ms, and so on.
  • zip paired values by position and stopped when the shorter source, b with 2 values, completed. a2 was dropped.
  • Mono.zip of three calls taking 300, 200 and 100 ms finished in about 300 ms, because all three ran at the same time. This is the standard way to make independent calls in parallel.
  • If any source of Mono.zip is empty, the result is empty too, and the other values are lost. Add defaultIfEmpty to optional parts before zipping.
  • Mono.firstWithValue returned the fast mirror and cancelled the slow one, which suits hedged requests against replicas.

Errors end the stream: fallbacks and retries

In Reactor an error is a terminal signal, like completion. After onError, no more values arrive. The source below divides 12 by 1, 2, 0 and 4, so the third element fails:

Java
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

public class ErrorOperators {

    static Flux<Integer> numbers() {
        return Flux.just(1, 2, 0, 4).map(i -> 12 / i);
    }

    public static void main(String[] args) {
        System.out.println("1. An error ends the stream:");
        numbers().subscribe(v -> System.out.println("   " + v),
                e -> System.out.println("   error: " + e.getMessage()));

        System.out.println("2. onErrorReturn: "
                + numbers().onErrorReturn(-1).collectList().block());

        System.out.println("3. onErrorResume: " + numbers()
                .onErrorResume(ArithmeticException.class, e -> Flux.just(100, 200))
                .collectList().block());

        System.out.println("4. Recover per element inside flatMap: " + Flux.just(1, 2, 0, 4)
                .flatMap(i -> Mono.fromCallable(() -> 12 / i).onErrorResume(e -> Mono.empty()))
                .collectList().block());

        System.out.print("5. onErrorMap: ");
        try {
            numbers().onErrorMap(e -> new IllegalStateException("bad input", e))
                    .collectList().block();
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage() + ", cause "
                    + e.getCause().getClass().getSimpleName());
        }

        AtomicInteger attempts = new AtomicInteger();
        Mono<String> flaky = Mono.defer(() -> {
            int n = attempts.incrementAndGet();
            System.out.println("   attempt " + n);
            return n < 3 ? Mono.error(new IllegalStateException("503 from server"))
                    : Mono.just("ok on attempt " + n);
        });
        System.out.println("6. retry(3) resubscribes to the source:");
        System.out.println("   " + flaky.retry(3).block());

        attempts.set(0);
        System.out.println("7. retryWhen(Retry.backoff(2, 100 ms)) when every attempt fails:");
        try {
            Mono.defer(() -> {
                System.out.println("   attempt " + attempts.incrementAndGet());
                return Mono.<String>error(new IllegalStateException("503 from server"));
            }).retryWhen(Retry.backoff(2, Duration.ofMillis(100)).jitter(0)
                    .doBeforeRetry(signal -> System.out.println("   retry "
                            + (signal.totalRetries() + 1) + " after "
                            + signal.failure().getMessage()))).block();
        } catch (RuntimeException e) {
            System.out.println("   " + e.getClass().getSimpleName() + ": " + e.getMessage()
                    + ", cause: " + e.getCause().getMessage());
        }
    }
}
Output
1. An error ends the stream:
   12
   6
   error: / by zero
2. onErrorReturn: [12, 6, -1]
3. onErrorResume: [12, 6, 100, 200]
4. Recover per element inside flatMap: [12, 6, 3]
5. onErrorMap: bad input, cause ArithmeticException
6. retry(3) resubscribes to the source:
   attempt 1
   attempt 2
   attempt 3
   ok on attempt 3
7. retryWhen(Retry.backoff(2, 100 ms)) when every attempt fails:
   attempt 1
   retry 1 after 503 from server
   attempt 2
   retry 2 after 503 from server
   attempt 3
   RetryExhaustedException: Retries exhausted: 2/2, cause: 503 from server
  • Case 1 printed 12 and 6, then the error. The value 4 was never processed, because the stream ended at 0.
  • onErrorReturn and onErrorResume replace the rest of the stream with a fallback, so the results are [12, 6, -1] and [12, 6, 100, 200]. They do not resume the original source.
  • To skip only the failing element, handle the error inside the flatMap, on each inner Mono. Case 4 kept 12, 6 and 3 and dropped only the 0. Avoid onErrorContinue for this: it depends on operator support upstream and its own reference documentation warns about its surprising behaviour.
  • onErrorMap translated the ArithmeticException into a domain exception and kept the original as its cause.
  • retry(3) resubscribed to the source after each failure. The source is a Mono.defer, so each attempt ran it again, and attempt 3 succeeded.
  • Retry.backoff(2, 100 ms) allowed two retries, waiting 100 ms and then 200 ms, so there were 3 attempts in all. When they were used up, it threw RetryExhaustedException, with the last failure as its cause. jitter(0) turns off the default random 50% jitter, so the delays are exact.

Retries only help when the source does real work on each subscription. Mono.just(callService()) calls the service once, while building the pipeline, and retrying it re-emits the same captured value or error.

Backpressure: request(n), limitRate and overflow

Backpressure lets a consumer tell the producer how much it can take. Inside WebFlux, Reactor Netty requests data as the socket can accept it, so a slow client slows down a Flux response instead of filling memory. The first two parts of this program show the requests themselves, and the last two show a source that cannot slow down:

Java
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

public class Backpressure {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("1. A subscriber that asks for two items at a time:");
        Flux.range(1, 5)
                .doOnRequest(n -> System.out.println("   source asked for " + n))
                .subscribe(new BaseSubscriber<Integer>() {
                    private int received;

                    @Override
                    protected void hookOnSubscribe(Subscription subscription) {
                        request(2);
                    }

                    @Override
                    protected void hookOnNext(Integer value) {
                        System.out.println("   got " + value);
                        if (++received % 2 == 0) {
                            request(2);
                        }
                    }
                });

        System.out.println("2. limitRate(10) on a request for everything:");
        List<Long> requests = new ArrayList<>();
        Flux.range(1, 40).doOnRequest(requests::add).limitRate(10).blockLast();
        System.out.println("   requests seen by the source: " + requests);

        System.out.println("3. A fast timer and a slow consumer:");
        Flux.interval(Duration.ofMillis(1))
                .publishOn(Schedulers.boundedElastic(), 4)
                .doOnNext(i -> sleep(50))
                .take(10)
                .onErrorResume(e -> {
                    System.out.println("   " + e.getClass().getSimpleName() + ": "
                            + e.getMessage());
                    return Flux.empty();
                })
                .blockLast();

        System.out.println("4. The same with onBackpressureDrop:");
        AtomicInteger dropped = new AtomicInteger();
        List<Long> kept = Flux.interval(Duration.ofMillis(1))
                .onBackpressureDrop(i -> dropped.incrementAndGet())
                .publishOn(Schedulers.boundedElastic(), 4)
                .doOnNext(i -> sleep(50))
                .take(6)
                .collectList()
                .block();
        System.out.println("   first ticks kept: " + kept.subList(0, 4)
                + ", later ticks skipped ahead: " + (kept.get(5) > 5)
                + ", some dropped: " + (dropped.get() > 0));
    }

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
Output
1. A subscriber that asks for two items at a time:
   source asked for 2
   got 1
   got 2
   source asked for 2
   got 3
   got 4
   source asked for 2
   got 5
2. limitRate(10) on a request for everything:
   requests seen by the source: [10, 8, 8, 8, 8, 8]
3. A fast timer and a slow consumer:
   OverflowException: Could not emit tick 4 due to lack of requests (interval doesn't support small downstream requests that replenish slower than the ticks)
4. The same with onBackpressureDrop:
   first ticks kept: [0, 1, 2, 3], later ticks skipped ahead: true, some dropped: true
  • The BaseSubscriber asked for 2 items, got exactly 2, and asked again. The source never sent more than was requested.
  • limitRate(10) split an unbounded request into a first request of 10, then requests of 8. It asks for more once 75% of the batch has been used, so items keep flowing without large buffers.
  • Flux.interval is a timer and cannot pause. publishOn with a prefetch of 4 requested 4 ticks, the consumer took 50 ms per item, and the fifth tick at about 5 ms had no demand. Reactor failed with OverflowException: Could not emit tick 4, counting from 0.
  • onBackpressureDrop throws away ticks that nobody requested instead of failing. The first ticks 0 to 3 arrived, later values skipped ahead, and some ticks were dropped. The exact numbers depend on timing, so the program prints only the checks.
Strategies for a source that ignores demand
OperatorWhen demand runs outFits
noneError, as in part 3Sources that respect request(n)
onBackpressureBuffer(n)Queues up to n items, then errors or applies an overflow strategyShort bursts
onBackpressureDrop()Discards new itemsSamples, metrics, ticks
onBackpressureLatest()Keeps only the newest itemPrices or status values where only the latest matters

Schedulers: publishOn, subscribeOn and blocking calls

Reactor does not create threads on its own. Without a scheduler, every operator runs on the thread that subscribed, or on the thread that emitted a signal, such as a Netty event loop or a timer. Schedulers move work to other threads. The program prints thread names with the worker number removed, because that number depends on which worker was free:

Java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public class SchedulersDemo {

    static String thread() {
        // strip the counter so the output does not depend on which worker was picked
        return Thread.currentThread().getName().replaceAll("-\\d+$", "-N");
    }

    static String blockingRead(String key) {
        try {
            Thread.sleep(20); // stands in for JDBC, a file read or a legacy SDK call
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return key.toUpperCase();
    }

    public static void main(String[] args) {
        System.out.println("1. No scheduler: everything runs on the subscribing thread");
        Flux.just("a").map(s -> { System.out.println("   map on " + thread()); return s; })
                .blockLast();

        System.out.println("2. publishOn switches the thread for the operators after it");
        Flux.just("a")
                .map(s -> { System.out.println("   before publishOn: " + thread()); return s; })
                .publishOn(Schedulers.parallel())
                .map(s -> { System.out.println("   after publishOn : " + thread()); return s; })
                .blockLast();

        System.out.println("3. subscribeOn moves the whole chain, wherever it is written");
        Flux.just("a")
                .doOnSubscribe(s -> System.out.println("   subscribe on    : " + thread()))
                .map(s -> { System.out.println("   map on          : " + thread()); return s; })
                .subscribeOn(Schedulers.boundedElastic())
                .blockLast();

        System.out.println("4. Wrapping a blocking call");
        String value = Mono.fromCallable(() -> {
            System.out.println("   blockingRead on : " + thread());
            return blockingRead("key");
        }).subscribeOn(Schedulers.boundedElastic()).block();
        System.out.println("   result " + value);

        System.out.println("5. Scheduler sizes on this machine");
        System.out.println("   CPU cores                  : "
                + Runtime.getRuntime().availableProcessors());
        System.out.println("   parallel() workers         : "
                + Schedulers.DEFAULT_POOL_SIZE);
        System.out.println("   boundedElastic() max threads: "
                + Schedulers.DEFAULT_BOUNDED_ELASTIC_SIZE);
        System.out.println("   boundedElastic() queue cap  : "
                + Schedulers.DEFAULT_BOUNDED_ELASTIC_QUEUESIZE);
    }
}
Output
1. No scheduler: everything runs on the subscribing thread
   map on main
2. publishOn switches the thread for the operators after it
   before publishOn: main
   after publishOn : parallel-N
3. subscribeOn moves the whole chain, wherever it is written
   subscribe on    : boundedElastic-N
   map on          : boundedElastic-N
4. Wrapping a blocking call
   blockingRead on : boundedElastic-N
   result KEY
5. Scheduler sizes on this machine
   CPU cores                  : 2
   parallel() workers         : 2
   boundedElastic() max threads: 20
   boundedElastic() queue cap  : 100000
  • Without a scheduler, map ran on main, the thread that called blockLast().
  • publishOn changed the thread only for operators after it: the first map ran on main, the second on parallel-N.
  • subscribeOn moved the subscription itself, so the whole chain ran on boundedElastic-N, even though subscribeOn was written last. Its position in the chain does not matter, which surprises many readers.
  • Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) is the standard wrapper for a blocking call, such as JDBC or a legacy SDK, inside a reactive application.
  • On this 2-core container, parallel() has 2 workers, one per core, and boundedElastic() may create up to 20 threads, ten per core, each with a queue of up to 100,000 waiting tasks. Idle threads are removed after 60 seconds.

Never run blocking code on parallel() or on a Netty event loop: those pools have one thread per core, and one blocked thread stalls every request assigned to it. The Spring WebFlux page measures what that does to response times. When Spring Boot runs with spring.threads.virtual.enabled=true on Java 21 or later, it sets the system property reactor.schedulers.defaultBoundedElasticOnVirtualThreads=true, so boundedElastic() uses virtual threads.

Context instead of ThreadLocal

Servlet applications keep request data, such as a request id or the security context, in a ThreadLocal. A reactive request can hop between threads at every publishOn, network call or timer, so a ThreadLocal set at the start is gone later. Reactor's replacement is the Context, an immutable map attached to the subscription:

Java
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public class ContextDemo {

    static final ThreadLocal<String> REQUEST_ID = new ThreadLocal<>();

    static Mono<String> loadOrders() {
        return Mono.deferContextual(ctx ->
                Mono.just("orders for request " + ctx.getOrDefault("requestId", "?")));
    }

    public static void main(String[] args) {
        System.out.println("1. ThreadLocal set on the caller, read after publishOn:");
        REQUEST_ID.set("r-1");
        String seen = Mono.just("x")
                .publishOn(Schedulers.parallel())
                .map(x -> "requestId = " + REQUEST_ID.get())
                .block();
        System.out.println("   " + seen);
        REQUEST_ID.remove();

        System.out.println("2. Reactor Context, written at the end of the chain:");
        String orders = loadOrders()
                .publishOn(Schedulers.parallel())
                .contextWrite(ctx -> ctx.put("requestId", "r-2"))
                .block();
        System.out.println("   " + orders);

        System.out.println("3. Context flows up the chain, not down:");
        String upward = Mono.just("x")
                .contextWrite(ctx -> ctx.put("requestId", "written before flatMap"))
                .flatMap(x -> loadOrders())
                .contextWrite(ctx -> ctx.put("requestId", "written after flatMap"))
                .block();
        System.out.println("   " + upward);

        System.out.println("4. The nearest contextWrite below an operator wins:");
        String nearest = loadOrders()
                .contextWrite(ctx -> ctx.put("requestId", "inner"))
                .contextWrite(ctx -> ctx.put("requestId", "outer"))
                .block();
        System.out.println("   " + nearest);
    }
}
Output
1. ThreadLocal set on the caller, read after publishOn:
   requestId = null
2. Reactor Context, written at the end of the chain:
   orders for request r-2
3. Context flows up the chain, not down:
   orders for request written after flatMap
4. The nearest contextWrite below an operator wins:
   orders for request inner
  • The ThreadLocal read null after publishOn, because the map ran on a parallel thread where the value was never set.
  • The Context value r-2 survived the thread switch, because it travels with the subscription, not with a thread. deferContextual reads it.
  • Context flows from the subscriber up towards the source. The contextWrite written before flatMap in the code applies only to Mono.just, which comes earlier in the chain. loadOrders() inside flatMap saw the value written after it.
  • With two writes of the same key, the one nearest to the reading operator won: inner.

In WebFlux, Spring Security stores the authentication in the Context, which is why you read it with ReactiveSecurityContextHolder. To bridge Context and ThreadLocal values, such as the logging MDC or tracing, Spring Boot uses the Micrometer context-propagation library. The property spring.reactor.context-propagation defaults to limited; setting it to auto restores the registered thread-local values in every operator, at some cost per signal.

Testing pipelines with StepVerifier and virtual time

StepVerifier, from reactor-test, subscribes to a publisher and checks each signal in turn. With virtual time it also replaces the schedulers with a clock that the test moves forward, so a pipeline that waits for days can be tested in milliseconds. The example below sends one reminder per day for three days:

Java
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

public class VirtualTimeTest {

    // Emits a reminder once a day for three days
    static Flux<String> dailyReminders() {
        return Flux.interval(Duration.ofDays(1)).take(3).map(day -> "reminder " + (day + 1));
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        Duration took = StepVerifier.withVirtualTime(VirtualTimeTest::dailyReminders)
                .expectSubscription()
                .expectNoEvent(Duration.ofDays(1))
                .expectNext("reminder 1")
                .thenAwait(Duration.ofDays(2))
                .expectNext("reminder 2", "reminder 3")
                .verifyComplete();
        long realMillis = (System.nanoTime() - start) / 1000000;
        System.out.println("Three days of reminders verified");
        System.out.println("Real time under 5 seconds: " + (realMillis < 5000)
                + ", verify() measured under 1 second: " + (took.toMillis() < 1000));

        try {
            StepVerifier.create(Flux.just(1, 2, 3))
                    .expectNext(1, 2)
                    .expectNext(4)
                    .verifyComplete();
        } catch (AssertionError e) {
            System.out.println("Failed check: " + e.getMessage());
        }

        StepVerifier.create(Flux.just(1, 0).map(i -> 10 / i))
                .expectNext(10)
                .expectErrorMatches(e -> e instanceof ArithmeticException)
                .verify();
        System.out.println("Error case verified: 10, then ArithmeticException");
    }
}
Output
Three days of reminders verified
Real time under 5 seconds: true, verify() measured under 1 second: true
Failed check: expectation "expectNext(4)" failed (expected value: 4; actual value: 3)
Error case verified: 10, then ArithmeticException
  • The first check verified three days of timed events, and the whole run took less than 5 seconds of real time, most of it class loading. expectNoEvent(Duration.ofDays(1)) also proved that nothing arrived early.
  • The deliberately wrong check failed with a precise message: it expected 4 and got 3.
  • The error case checked a value followed by an ArithmeticException.

For virtual time to work, the publisher must be created inside the supplier passed to withVirtualTime, as the method reference does here. A Flux.interval built before the call captures the real scheduler, and the test then waits for real time. The Reactor testing page covers StepVerifier and TestPublisher in more depth.

Choosing the right operator

Common needs and the operators that fit them
NeedUseAvoid
Call a service per element, order does not matterflatMap with a concurrency limitUnbounded flatMap against a small service
Call per element, keep the orderflatMapSequential, or concatMap for one at a timeflatMap followed by sorting
Fallback when nothing is foundswitchIfEmpty(Mono.defer(...)), or defaultIfEmpty for a constantswitchIfEmpty(eagerCall())
Independent calls for one responseMono.zipSequential block() calls
Transient remote failuresretryWhen(Retry.backoff(...).filter(...))Retrying a Mono.just of an eager result
Skip bad elements, keep goingonErrorResume inside flatMaponErrorContinue
Blocking library callfromCallable plus subscribeOn(boundedElastic())Calling it on the event loop
Request-scoped datacontextWrite and deferContextualThreadLocal
Time-based logic in testsStepVerifier.withVirtualTimeThread.sleep in tests

For the basics of Mono and Flux without Spring, start with Reactor basics. To call other services from a reactive application, see Spring WebClient, and for reactive database access, Spring Data R2DBC.