Mono and Flux
Mid-level Always asked 7 min
On this page
The question
What is the difference between Mono and Flux?
30-second answer
Both are Reactor's Publishers. A Mono delivers at most one element, then completes or fails; a Flux delivers zero to N, possibly without end. The type states the contract: Mono<Order> is one result or none, and Flux<Order> is a sequence. They are lazy, so nothing runs until something subscribes.
Understand it
Mono and Flux as marble lanes
CompareA Mono ends after at most one element. It can succeed with a value, succeed empty or fail, so empty is a normal outcome and not an error.
View as text
Three timelines, one per outcome. A circle is an element, a vertical bar is onComplete, and a cross is onError. Two lines below say how many elements it holds and what it is used for.
Mono: A Mono ends after at most one element. It can succeed with a value, succeed empty or fail, so empty is a normal outcome and not an error. Mono.just(1) draws one element and a bar. Mono.empty() draws only a bar. Mono.error(ex) draws only a cross.
Flux: A Flux delivers any number of elements, even an endless stream, then completes or fails. Elements delivered before a failure stay delivered. Flux.just(1, 2, 3) draws three elements and a bar. Flux.empty() draws only a bar. The failing Flux draws two elements and a cross.
Three timelines, one per outcome. A circle is an element, a vertical bar is onComplete, and a cross is onError. Two lines below say how many elements it holds and what it is used for.
Mono: A Mono ends after at most one element. It can succeed with a value, succeed empty or fail, so empty is a normal outcome and not an error. Mono.just(1) draws one element and a bar. Mono.empty() draws only a bar. Mono.error(ex) draws only a cross.
Flux: A Flux delivers any number of elements, even an endless stream, then completes or fails. Elements delivered before a failure stay delivered. Flux.just(1, 2, 3) draws three elements and a bar. Flux.empty() draws only a bar. The failing Flux draws two elements and a cross.
Takeaway: Both are Publishers, and each ends with one terminal signal. Mono promises at most one element, so its type tells the caller what to expect; Flux promises any number.
What runs without subscribe?
PredictThis code builds a Flux with a map that prints, then prints "built". It never calls subscribe.
View as text
Java code on top and its console output below. This code builds a Flux with a map that prints, then prints "built". It never calls subscribe. The learner first predicts the output.
Only "built" prints. Operators wrap each other into a description of the work, called assembly time. No element moved, so map never ran. The console reads built.
subscribe() starts it: the signal travels up to the source, and elements flow down. Now map runs once per element. The console reads built, map 1, map 2 and map 3.
A second subscribe runs everything again, because this Flux is cold. Each subscriber gets its own run from the start. The console shows map 1, map 2 and map 3 once more.
The trap: Java evaluates arguments first. Mono.just(call()) runs call() while assembling, before any subscribe. Mono.fromCallable(this::call) waits for one. The code becomes Mono.just(call()), and the console reads called, then assembled.
Java code on top and its console output below. This code builds a Flux with a map that prints, then prints "built". It never calls subscribe. The learner first predicts the output.
Only "built" prints. Operators wrap each other into a description of the work, called assembly time. No element moved, so map never ran. The console reads built.
subscribe() starts it: the signal travels up to the source, and elements flow down. Now map runs once per element. The console reads built, map 1, map 2 and map 3.
A second subscribe runs everything again, because this Flux is cold. Each subscriber gets its own run from the start. The console shows map 1, map 2 and map 3 once more.
The trap: Java evaluates arguments first. Mono.just(call()) runs call() while assembling, before any subscribe. Mono.fromCallable(this::call) waits for one. The code becomes Mono.just(call()), and the console reads called, then assembled.
Takeaway: Building a chain only describes the work. Nothing runs until something subscribes, and in WebFlux the framework is what subscribes to the Mono you return.
In code
interface OrderRepository {
Mono<Order> findById(String id); // found, or empty
Flux<Order> findAll(); // any number
Mono<Void> deleteById(String id); // only success or failure
}Mono<Order> order = Mono.fromCallable(() -> legacy.load(id)); // nothing runs yet
Mono<List<Order>> all = repository.findAll().collectList(); // Flux to Mono
Flux<Order> single = order.flux(); // Mono to Flux
order.subscribe(System.out::println); // runs here
Flux<Long> hot = Flux.interval(Duration.ofSeconds(1)).share(); // one shared run
Mono<Order> cached = order.cache(); // one load, replayedMono<Rates> rates = webClient.get().uri("/rates").retrieve().bodyToMono(Rates.class);
rates.subscribe(r -> pricing.update(r));
rates.subscribe(r -> audit.record(r)); // a second HTTP request
Mono<Rates> shared = rates.cache(Duration.ofMinutes(5));
shared.subscribe(r -> pricing.update(r));
shared.subscribe(r -> audit.record(r)); // one request, replayed for 5 minutesSolve it
GET /users/{id} answers 200 with an empty body for an unknown id
repository.findById(id) returns a Mono<User>, and the WebFlux handler returns it as is. For an unknown id the client
gets 200 and no body, instead of 404. Fix it, and avoid the classic trap in the fix.
- Read the signal. An empty
Monocompletes without a value. That is a normal completion, so WebFlux writes 200 with nothing in it. - Make “not found” explicit. Turn emptiness into an error with
switchIfEmpty(Mono.error(...)), and map that error to 404. - Avoid eager fallbacks.
switchIfEmpty(createDefaultUser())calls the method while the chain is built, even when a user is found. Wrap such work inMono.defer. - Do not reach for
block()or null checks. AMononever emits null, and blocking on the event loop stalls every request. - Check.
WebTestClientexpects 404 for an unknown id and 200 with a body for a known one.
@GetMapping("/users/{id}")
Mono<User> user(@PathVariable String id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no user " + id)));
}
Mono<User> userOrGuest(String id) {
return repository.findById(id)
.switchIfEmpty(Mono.defer(() -> createGuest(id))); // runs only when the user is missing
}How to answer
- Empty is a normal completion for both, not an error.
Mono<Void>means only success or failure, with no value.collectList()turns a Flux into a Mono, andflux()does the reverse.- Use Mono for one result and Flux for many, so the signature tells callers what to expect.
Common mistakes
- Returning
Mono<List<Order>>for a large result. It holds everything in memory, andFlux<Order>can stream. - Calling a Mono "a Future". A Mono is lazy and can run again; a Future is already running.
Follow-up questions
Why does nothing happen until you subscribe?
A chain is a description of work, not the work. Each operator wraps the previous one at assembly time. Subscribing sends a signal up to the source, and only then do elements flow down. This laziness lets you build a chain once, run it many times, retry it from the start and stop it, because no work has begun.
- Assembly builds the chain, subscription starts it, and run time moves the data.
- A retry works because it can subscribe again.
- Forgetting to return or subscribe a chain silently does nothing.
repository.save(order); // nothing is saved
return repository.save(order); // the framework subscribes What is the difference between cold and hot publishers?
A cold publisher starts a new run for each subscriber, so everyone gets everything from the start; most are cold, such as an HTTP call or a database query. A hot publisher runs regardless of its subscribers, so a late one only gets what comes next, as with a Sinks stream or live events. share() makes a cold one hot.
- Two subscribers to a cold HTTP Mono make two HTTP calls.
share()runs the source once for everyone while someone is subscribed.cache()also replays stored values to late subscribers.
What is the difference between Mono.just(call()) and Mono.fromCallable(this::call)?
Mono.just(call()) runs call() immediately, on the current thread and during assembly, because Java evaluates arguments first. It is not lazy, it runs even if nobody subscribes, and a retry reuses the same value. Mono.fromCallable runs it at subscription, once per subscriber. So wrap a blocking or failing call in fromCallable, or use defer.
- With
Mono.just(call()).retry(2),callran once. - With
Mono.fromCallable(...).retry(2), a failing call ran three times. Mono.justalso rejects null, with aNullPointerException.Mono.deferis the same idea when the supplier already returns a Mono.
Can a Mono hold null? How do you model "not found"?
No. Reactive Streams forbids null elements, so Mono.just(null) throws a NullPointerException, and a map returning null fails the stream. Model "not found" as an empty Mono, and use justOrEmpty to convert a nullable value. Handle it with switchIfEmpty or defaultIfEmpty, because operators such as map are simply skipped on empty.
- An empty Mono completes with no value, so
mapnever runs. switchIfEmpty(Mono.error(...))turns not found into a failure, such as a 404.block()on an empty Mono returns null, which is a common surprise.
When should you call subscribe() yourself?
Rarely, and almost never inside a chain or a controller. At the edge of the application, the framework subscribes, or a test does. Call it yourself only at a true entry point, such as a scheduled task or a startup listener, and always pass an error handler. Without one, the error is only logged through onErrorDropped.
- Nested
subscribe()breaks backpressure, cancellation and the Reactor Context. - Compose with
flatMaportheninstead of subscribing inside a callback. - A subscribe with no error consumer does not throw to the caller.
Who subscribes in a WebFlux controller?
The framework does. You return a Mono or Flux, and WebFlux subscribes when it writes the response. So calling subscribe() yourself in a controller is usually a bug, because that work is detached from the request: its errors and cancellation go nowhere.
How is a Mono different from a CompletableFuture?
A CompletableFuture starts when it is created, holds one result and caches it. A Mono does nothing until subscribed, runs again for each subscriber unless you use cache(), can be cancelled, and may complete empty. Convert with Mono.fromFuture and toFuture.
Check yourself
Show answers
- onComplete only: Correct. Empty is a success with no element, and the terminal signal needs no demand.
- onNext(null), then onComplete: Incorrect. Reactive Streams forbids null elements.
- onError with NoSuchElementException: Incorrect. Empty is not a failure. Only single() turns it into one.
Show answers
- It answers "ok" and saves nothing.: Correct. Nothing subscribed to the Mono that save returned, so the write never ran.
- It saves the order, then answers "ok".: Incorrect. Calling save only assembled a Mono. It needs a subscriber to run.
- It fails, because the Mono was ignored.: Incorrect. Nothing checks for this, which is why the bug is so quiet.
Show answers
- Two: Correct. It is cold, so each subscriber starts its own run.
- One, then the result is shared: Incorrect. Sharing needs an explicit operator, such as cache().
- None, until block() is called: Incorrect. Any subscriber starts it. block() is just one way of subscribing.