Reactive Quarkus: Mutiny and Vert.x

Senior Frequently asked 5 min

On this page

The question

How do Mutiny's Uni and Multi compare with Reactor's Mono and Flux?

30-second answer

They play the same roles: Uni and Mono hold zero or one item, Multi and Flux hold many, and all four are lazy until subscribed. Mutiny's API is event-driven, grouping operators under onItem(), onFailure() and so on, so there are fewer names to learn. A Uni may emit null, which a Mono cannot. Quarkus uses Mutiny throughout, and converters bridge it to Reactor.

Understand it

Uni and Multi against Mono and Flux

Compare

Mutiny groups operators by the event they react to: onItem(), onFailure(). Uni holds zero or one item and may emit null; Multi holds many. Quarkus uses it throughout.

View as text

Six rows, each a task, with the type or operator that does it: zero or one item, zero to many items, transforming each item, calling something async, recovering from a failure, and whether an item can be null.

Mutiny: Mutiny groups operators by the event they react to: onItem(), onFailure(). Uni holds zero or one item and may emit null; Multi holds many. Quarkus uses it throughout. Zero or one item: Uni<T>. Zero to many items: Multi<T>. Transform each item: onItem().transform(f). Call something async: onItem().transformToUni(f). Recover from a failure: onFailure().recoverWithItem(x). A null item: Allowed in a Uni.

Reactor: Reactor offers one flat list of operators, such as map, flatMap and onErrorReturn. Mono holds zero or one item, never null; Flux holds many. Spring WebFlux uses it. Zero or one item: Mono<T>. Zero to many items: Flux<T>. Transform each item: map(f). Call something async: flatMap(f). Recover from a failure: onErrorReturn(x). A null item: Never: Mono.just(null) fails.

Six rows, each a task, with the type or operator that does it: zero or one item, zero to many items, transforming each item, calling something async, recovering from a failure, and whether an item can be null.

Mutiny: Mutiny groups operators by the event they react to: onItem(), onFailure(). Uni holds zero or one item and may emit null; Multi holds many. Quarkus uses it throughout. Zero or one item: Uni<T>. Zero to many items: Multi<T>. Transform each item: onItem().transform(f). Call something async: onItem().transformToUni(f). Recover from a failure: onFailure().recoverWithItem(x). A null item: Allowed in a Uni.

Reactor: Reactor offers one flat list of operators, such as map, flatMap and onErrorReturn. Mono holds zero or one item, never null; Flux holds many. Spring WebFlux uses it. Zero or one item: Mono<T>. Zero to many items: Flux<T>. Transform each item: map(f). Call something async: flatMap(f). Recover from a failure: onErrorReturn(x). A null item: Never: Mono.just(null) fails.

Takeaway: Uni and Multi play the roles of Mono and Flux. Mutiny names operators after the event they react to, so the API is smaller, and a Uni may emit null.

Vert.x event loops and the worker pool

Tap the parts

Select a part to see what it does.

Tap a part of the threading model. The stripe on each row shows where the work runs: on an event loop, a worker thread or a virtual thread.

View as text

A legend names three places where work runs: event loop, worker and virtual thread. Seven rows follow, each with a button, a colored stripe for its place, and two short lines.

Event loops, event loop: two per core, must never block. Vert.x runs network I/O on a few event loop threads, two per CPU core by default.

Returns Uni, event loop: runs on the loop, calls must not block. Quarkus REST picks the thread from the signature.

Blocked check, event loop: warns after 2 s, with a stack trace. Vert.x watches its loops.

Plain return, worker: runs on a worker, may block. A method returning a plain value, such as a List, runs on a worker thread, where blocking is allowed.

Worker pool, worker: many threads, but still bounded. Blocking endpoints and @Blocking work share one pool, by default the larger of 200 threads and eight per core.

@Blocking, worker: overrides the, signature. @Blocking moves a method that returns Uni to a worker, for example a Uni wrapping JDBC.

Virtual thread, virtual: one per request, Java 21 or later. @RunOnVirtualThread runs plain blocking code on a new virtual thread.

A legend names three places where work runs: event loop, worker and virtual thread. Seven rows follow, each with a button, a colored stripe for its place, and two short lines.

Event loops, event loop: two per core, must never block. Vert.x runs network I/O on a few event loop threads, two per CPU core by default.

Returns Uni, event loop: runs on the loop, calls must not block. Quarkus REST picks the thread from the signature.

Blocked check, event loop: warns after 2 s, with a stack trace. Vert.x watches its loops.

Plain return, worker: runs on a worker, may block. A method returning a plain value, such as a List, runs on a worker thread, where blocking is allowed.

Worker pool, worker: many threads, but still bounded. Blocking endpoints and @Blocking work share one pool, by default the larger of 200 threads and eight per core.

@Blocking, worker: overrides the, signature. @Blocking moves a method that returns Uni to a worker, for example a Uni wrapping JDBC.

Virtual thread, virtual: one per request, Java 21 or later. @RunOnVirtualThread runs plain blocking code on a new virtual thread.

Takeaway: A few event loop threads do the I/O and must never block. Quarkus sends blocking methods to a worker pool, or a virtual thread, and the signature decides which.

Which thread runs a Quarkus REST method?A method that returns Uni or Multi runs on the event loop. A method that returns a plain value runs on a worker thread, and so does one annotated Blocking. A method annotated RunOnVirtualThread runs on a virtual thread.What does themethod say?Returns Uni or Multi:event loopReturns a plainvalue:worker thread@Blocking:worker threadMarked to run ona virtual thread
Which thread runs a Quarkus REST method?A method that returns Uni or Multi runs on the event loop. A method that returns a plain value runs on a worker thread, and so does one annotated Blocking. A method annotated RunOnVirtualThread runs on a virtual thread.What does themethod say?Returns Uni or Multi:event loopReturns a plainvalue:worker thread@Blocking:worker threadMarked to run ona virtual thread
Which thread runs a Quarkus REST method?

In code

// Mutiny, in Quarkus: runs on the event loop
@GET
@Path("/{id}")
public Uni<OrderView> order(@RestPath Long id) {
    return orders.findById(id)
            .onItem().ifNull().failWith(NotFoundException::new)
            .chain(order -> customers.get(order.customerId())
                    .onItem().transform(c -> new OrderView(order, c)))
            .onFailure(TimeoutException.class)
            .recoverWithItem(OrderView.unavailable());
}

// Reactor, in Spring WebFlux
Mono<OrderView> order(Long id) {
    return orders.findById(id)
            .switchIfEmpty(Mono.error(new NotFoundException()))
            .flatMap(order -> customers.get(order.customerId())
                    .map(c -> new OrderView(order, c)))
            .onErrorReturn(TimeoutException.class, OrderView.unavailable());
}
One endpoint in Mutiny, and the same chain in Reactor
@GET
@Path("/legacy")
@Blocking // returns Uni, but calls JDBC: run it on a worker
public Uni<List<Order>> legacy() {
    return Uni.createFrom().item(() -> jdbcOrders.findAll());
}

@GET
@Path("/all")
@RunOnVirtualThread // plain blocking code, on a virtual thread
public List<Order> all() {
    return jdbcOrders.findAll();
}
Override the thread the signature picks
A reactive request, and when the loop is freeThe request arrives on an event loop, which asks the reactive SQL client for a Uni and is then free for other requests. When the row arrives, the loop transforms it, and Quarkus writes the response.GET /orders/42on an event loopReactive SQL clientreturns a UniLoop is free whilethe query runsRow arrives:onItem().transformQuarkus writesthe response
A reactive request, and when the loop is freeThe request arrives on an event loop, which asks the reactive SQL client for a Uni and is then free for other requests. When the row arrives, the loop transforms it, and Quarkus writes the response.GET /orders/42on an event loopReactive SQL clientreturns a UniLoop is free whilethe query runsRow arrives:onItem().transformQuarkus writesthe response
A reactive request, and when the loop is free
Uni<Price> price = prices.get(id);
Uni<Stock> stock = stocks.get(id);

Uni<ProductPage> page = Uni.combine().all().unis(price, stock)
    .with((p, s) -> new ProductPage(p, s));        // like Reactor's Mono.zip
Two calls at once, combined when both arrive

Solve it

A Uni<Uni<Customer>> appears: load an order, then its customer

orders.find(id) returns Uni<Order>, and customers.find(customerId) returns Uni<Customer>. A first attempt, orders.find(id).onItem().transform(o -> customers.find(o.customerId())), has the type Uni<Uni<Customer>>, and the endpoint returns nothing useful.

  1. Read the type. transform maps a value to a value. Given a function that returns a Uni, it wraps one Uni in another, like map where flatMap was needed.
  2. Chain the async step. transformToUni subscribes to the inner Uni and passes on its item: Mutiny’s flatMap.
  3. Handle a missing order. If the order is not found, the item is null. onItem().ifNull().failWith(...) turns that into a 404.
  4. Know the stream version. For a Multi of orders, transformToUniAndConcatenate keeps the order and transformToUniAndMerge runs the calls concurrently.
  5. Check. Subscribe with UniAssertSubscriber, await the item and assert the customer.
@GET
@Path("/orders/{id}/customer")
public Uni<Customer> customerOf(long id) {
    return orders.find(id)
        .onItem().ifNull().failWith(() -> new NotFoundException("no order " + id))
        .onItem().transformToUni(order -> customers.find(order.customerId()));
}

@Test
void loadsTheCustomer() {
    resource.customerOf(42).subscribe().withSubscriber(UniAssertSubscriber.create())
        .awaitItem()
        .assertItem(new Customer(7, "Ana"));
}
transformToUni chains the second call; ifNull turns a missing order into 404

How to answer

  • map becomes onItem().transform, and flatMap becomes onItem().transformToUni, or chain.
  • Mutiny 2 implements java.util.concurrent.Flow, the JDK (Java Development Kit) form of Reactive Streams.
  • Multi and Flux both support backpressure.
  • Mutiny comes from the SmallRye project and was designed with Quarkus.

Common mistakes

  • Assuming a Uni runs as soon as it is created. Like a Mono, it runs only when subscribed.
  • Treating a Uni like a CompletableFuture. A Uni is lazy and can be retried; a started future cannot.

Follow-up questions

In Quarkus, what runs on the event loop and what runs on a worker thread?

Vert.x handles network I/O on a few event loop threads, two per core by default, which must never block. Quarkus REST chooses from the method signature: a method returning Uni or Multi runs on the event loop, and a method returning a plain value runs on a worker thread from a larger pool, where blocking calls such as JDBC (Java Database Connectivity) are allowed.

  • Block an event loop, and every request on that thread waits.
  • Vert.x logs a blocked thread warning when a loop is busy for more than 2 seconds.
  • The worker pool is bounded, so long blocking waits can still use it up.

See it in the infographic: Vert.x event loops and the worker pool

What do @Blocking, @NonBlocking and @RunOnVirtualThread do?

They override the thread Quarkus picks from the signature. @Blocking runs a method on a worker thread even if it returns Uni, for example a Uni that wraps JDBC. @NonBlocking keeps a method with a plain return type on the event loop, when it never blocks. @RunOnVirtualThread runs the method on a new virtual thread, so blocking code waits cheaply.

  • The same annotations apply to messaging methods, such as Kafka consumers.
  • @RunOnVirtualThread needs Java 21 or later.
  • Prefer clear signatures, and annotate only when the default is wrong.

See it in the infographic: Vert.x event loops and the worker pool

A method returns a Uni but calls a JDBC repository inside it. What happens, and how do you fix it?

The method runs on the event loop, so the JDBC call blocks a loop thread, and every request on that thread waits. Hibernate ORM (object-relational mapping) refuses outright to run on an I/O thread, and other blocking calls make Vert.x log blocked thread warnings. Fix it with @Blocking, by returning a plain value, or by switching to a reactive client such as Hibernate Reactive.

  • Uni.createFrom().item(supplier) runs the supplier on the subscribing thread, here the loop.
  • emitOn and runSubscriptionOn move work to another executor, like publishOn and subscribeOn.
  • Test under load, since one blocked loop slows unrelated endpoints.

See it in the infographic: Vert.x event loops and the worker pool

Who subscribes to the Uni that a REST (Representational State Transfer) method returns?

Quarkus REST does. It subscribes on the event loop when the request arrives, writes the item as the response, and maps a failure to an error status. Your code only builds the pipeline, and the framework runs it, as WebFlux does with a Mono.

Check yourself

1. Which Mutiny call matches Reactor's flatMap on a Mono?
Show answers
  • onItem().transformToUni(f): Correct. It calls something async per item and continues with its result, as flatMap does.
  • onItem().transform(f): Incorrect. That is map. It changes the item without calling anything async.
  • onFailure().recoverWithItem(x): Incorrect. That is onErrorReturn. It only handles failures.
2. A Quarkus REST method returns List<Order> and has no threading annotation. Which thread runs it?
Show answers
  • A worker thread: Correct. A plain return type means the method may block, so Quarkus runs it on a worker.
  • An event loop thread: Incorrect. Only methods returning Uni or Multi, or marked @NonBlocking, run on the loop.
  • A virtual thread: Incorrect. That needs @RunOnVirtualThread.