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 map, flatMap, concatMap and flatMapSequential Empty results and the eager switchIfEmpty trap Combining streams: concat, merge, zip Errors end the stream: fallbacks and retries Backpressure: request(n), limitRate and overflow Schedulers: publishOn, subscribeOn and blocking calls Context instead of ThreadLocal Testing pipelines with StepVerifier and virtual time Choosing the right operator
How a Reactor pipeline runs
Spring WebFlux is built on Project Reactor. A controller method returns a MonoFlux
Three ideas explain almost all of Reactor's behaviour:
- Assembly is not execution: calling
ormap only builds a description of the work and returns a new, immutable publisher. Nothing runs until something subscribes.flatMap - Signals flow down, requests flow up: a subscriber asks for
items withn , and the source sends at most that manyrequest(n) signals, followed byonNext oronComplete . This demand is called backpressure.onError - 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:
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));
}
}
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
line: building the chain did no work.map - The plain
call requested 9223372036854775807 items, which issubscribe and means "unbounded". Values then flowed one at a time:Long.MAX_VALUE ,map 1 ,got 10 , and so on.map 2 - The second subscriber ran
again. Withmap 1 , Reactor requested only 1 item, so the source produced just one.take(1) - Step 4 called
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.source.map(...)
| Family | Operators | Use for |
|---|---|---|
| Transforming | mapflatMapconcatMapflatMapSequential | Changing each value, or calling something asynchronous per value |
| Empty results | defaultIfEmptyswitchIfEmptyfilterhasElement | Lookups that find nothing |
| Combining | zipmergeconcatfirstWithValue | Calling several services and joining the results |
| Errors | onErrorReturnonErrorResumeonErrorMapretryretryWhen | Fallbacks, translation and retries |
| Demand | limitRateonBackpressureBufferonBackpressureDrop | Sources faster than their consumers |
| Threads | publishOnsubscribeOn | Moving work off the event loop |
| Context | contextWritedeferContextual | Request-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()
map, flatMap, concatMap and flatMapSequential
mapMono
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));
}
}
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
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.flatMap waited for each lookup to finish before starting the next, so the order is kept, and the time is the sum, about 600 ms.concatMap ran the lookups concurrently, likeflatMapSequential , but buffered early results to emit them in the original order. It also took about 300 ms.flatMap with a concurrency of 1 behaves likeflatMap .concatMap
flatMapQueues.SMALL_BUFFER_SIZEflatMap(this::call, 8)
Empty results and the eager switchIfEmpty trap
A MonofilterMono
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]"));
}
}
}
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.
replaced the empty result with a fixed value.defaultIfEmpty("none")- With
, 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 lazyswitchIfEmpty(loadFromDatabase("known")) , that is a wasted database call on every cache hit.Mono - Wrapping the fallback in
postponed it until the source was actually empty: nothing was printed on the hit, and the database was called only on the miss.Mono.defer turned 15 into an emptyfilter , soMono returnedblock() , andnull reportedhasElement() .false- A
function must never returnmap . Reactor fails with anull naming the mapper. UseNullPointerException ormapNotNull when a mapping may produce no value.handle
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:
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);
}
}
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
subscribed toconcat only afterb completed, so alla values come first.a subscribed to both at once and emitted values in arrival order:merge at 100 ms,a0 at 140 ms,b0 at 200 ms,a1 at 280 ms, and so on.b1 paired values by position and stopped when the shorter source,zip with 2 values, completed.b was dropped.a2 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.Mono.zip- If any source of
is empty, the result is empty too, and the other values are lost. AddMono.zip to optional parts before zipping.defaultIfEmpty returned the fast mirror and cancelled the slow one, which suits hedged requests against replicas.Mono.firstWithValue
Errors end the stream: fallbacks and retries
In Reactor an error is a terminal signal, like completion. After onError
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());
}
}
}
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.
andonErrorReturn replace the rest of the stream with a fallback, so the results areonErrorResume and[12, 6, -1] . They do not resume the original source.[12, 6, 100, 200]- To skip only the failing element, handle the error inside the
, on each innerflatMap . Case 4 kept 12, 6 and 3 and dropped only the 0. AvoidMono for this: it depends on operator support upstream and its own reference documentation warns about its surprising behaviour.onErrorContinue translated theonErrorMap into a domain exception and kept the original as its cause.ArithmeticException resubscribed to the source after each failure. The source is aretry(3) , so each attempt ran it again, and attempt 3 succeeded.Mono.defer allowed two retries, waiting 100 ms and then 200 ms, so there were 3 attempts in all. When they were used up, it threwRetry.backoff(2, 100 ms) , with the last failure as its cause.RetryExhaustedException turns off the default random 50% jitter, so the delays are exact.jitter(0)
Retries only help when the source does real work on each subscription. Mono.just(callService())
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
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();
}
}
}
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
asked for 2 items, got exactly 2, and asked again. The source never sent more than was requested.BaseSubscriber 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.limitRate(10) is a timer and cannot pause.Flux.interval 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 withpublishOn , counting from 0.OverflowException: Could not emit tick 4 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.onBackpressureDrop
| Operator | When demand runs out | Fits |
|---|---|---|
| none | Error, as in part 3 | Sources that respect request(n) |
onBackpressureBuffer(n) | Queues up to n | Short bursts |
onBackpressureDrop() | Discards new items | Samples, metrics, ticks |
onBackpressureLatest() | Keeps only the newest item | Prices 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:
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);
}
}
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,
ran onmap , the thread that calledmain .blockLast() changed the thread only for operators after it: the firstpublishOn ran onmap , the second onmain .parallel-N moved the subscription itself, so the whole chain ran onsubscribeOn , even thoughboundedElastic-N was written last. Its position in the chain does not matter, which surprises many readers.subscribeOn is the standard wrapper for a blocking call, such as JDBC or a legacy SDK, inside a reactive application.Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic())- On this 2-core container,
has 2 workers, one per core, andparallel() 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.boundedElastic()
Never run blocking code on parallel()spring.threads.virtual.enabled=truereactor.schedulers.defaultBoundedElasticOnVirtualThreads=trueboundedElastic()
Context instead of ThreadLocal
Servlet applications keep request data, such as a request id or the security context, in a ThreadLocalpublishOnThreadLocalContext
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);
}
}
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
readThreadLocal afternull , because thepublishOn ran on amap thread where the value was never set.parallel - The Context value
survived the thread switch, because it travels with the subscription, not with a thread.r-2 reads it.deferContextual - Context flows from the subscriber up towards the source. The
written beforecontextWrite in the code applies only toflatMap , which comes earlier in the chain.Mono.just insideloadOrders() saw the value written after it.flatMap - 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 ReactiveSecurityContextHolderThreadLocalspring.reactor.context-propagationlimitedauto
Testing pipelines with StepVerifier and virtual time
StepVerifierreactor-test
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");
}
}
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.
also proved that nothing arrived early.expectNoEvent(Duration.ofDays(1)) - 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 withVirtualTimeFlux.intervalStepVerifierTestPublisher
Choosing the right operator
| Need | Use | Avoid |
|---|---|---|
| Call a service per element, order does not matter | flatMap | Unbounded flatMap |
| Call per element, keep the order | flatMapSequentialconcatMap | flatMap |
| Fallback when nothing is found | switchIfEmpty(Mono.defer(...))defaultIfEmpty | switchIfEmpty(eagerCall()) |
| Independent calls for one response | Mono.zip | Sequential block() |
| Transient remote failures | retryWhen(Retry.backoff(...).filter(...)) | Retrying a Mono.just |
| Skip bad elements, keep going | onErrorResumeflatMap | onErrorContinue |
| Blocking library call | fromCallablesubscribeOn(boundedElastic()) | Calling it on the event loop |
| Request-scoped data | contextWritedeferContextual | ThreadLocal |
| Time-based logic in tests | StepVerifier.withVirtualTime | Thread.sleep |
For the basics of MonoFlux