Sub topic 2
The Reactive Streams contract
This chapter assumes you know Java generics and lambdas, can read a basic Spring Boot controller, and understand why a thread-per-request server blocks threads while it waits for I/O. It covers the small specification that Reactor, and therefore WebFlux, is built on.
Why a contract is needed
Asynchronous libraries each used to invent their own way to pass data between a producer and a consumer. Two libraries could not be connected without adapters. Worse, most designs let a fast producer push data at a slow consumer with no way to say "stop". The consumer's only options were to buffer without limit or to drop data.
Reactive Streams is a small specification that fixes both problems. It defines:
- A common set of interfaces, so libraries can interoperate.
- A rule that the consumer controls how many items the producer may send.
- A fixed order of signals, so every implementation behaves predictably.
The interfaces live in the org.reactivestreams package. Since Java 9, the same four interfaces are mirrored in java.util.concurrent.Flow. Project Reactor, RxJava, Akka Streams, and R2DBC drivers all implement the specification. Spring WebFlux uses Reactor, so you rarely implement these interfaces yourself. You do need to understand them, because every operator, error, and cancellation you meet is defined by them.
The four interfaces
| Interface | Role | Methods |
|---|---|---|
| `Publisher<T>` | A source of zero or more items | `subscribe(Subscriber<? super T>)` |
| `Subscriber<T>` | A consumer of items | `onSubscribe`, `onNext`, `onError`, `onComplete` |
| `Subscription` | The link between one publisher and one subscriber | `request(long n)`, `cancel()` |
| `Processor<T, R>` | Both a `Subscriber<T>` and a `Publisher<R>` | Inherits all of the above |
Mono and Flux both implement Publisher. A Processor is a stage that sits in the middle of a pipeline. You will almost never write one, because Reactor operators fill that role.
A Subscription belongs to exactly one subscriber. If three subscribers subscribe to the same publisher, there are three independent subscriptions, each with its own demand.
The signal sequence
When a subscriber subscribes, the publisher and subscriber exchange signals in a fixed order.
The same order can be written as a rule of thumb:
onSubscribe onNext* (onError | onComplete)?In words:
onSubscribeis always first, and it is called exactly once.onNextis called zero or more times.- The stream ends with at most one terminal signal:
onErrororonComplete. - After a terminal signal, no further signals of any kind may be sent.
A stream may also never terminate. Flux.interval is an example, and so is a live feed. The stream then ends only when the subscriber calls cancel().
Demand: request(n)
Data moves downstream, but demand moves upstream. A publisher must not call onNext more times than the subscriber has requested through Subscription.request(n). Until the subscriber requests something, nothing is emitted.
This is the core of the contract. The subscriber announces its capacity, and the publisher respects it. The next chapters cover this in detail as backpressure. Here, note three rules that govern demand:
nmust be greater than zero. A call with zero or a negative value is a specification violation, and the publisher must signalonErrorwith anIllegalArgumentException.- Demand is cumulative. Calling
request(2)and thenrequest(3)means the publisher may emit up to five items in total. - A demand of
Long.MAX_VALUEmeans "unbounded". The publisher may emit as fast as it can. This is what a plainsubscribe(consumer)call in Reactor does.
A hand-written Subscriber
The following program implements Subscriber directly. It asks for two items at first, then asks for two more every time it receives an even number. Run it with reactor-core on the classpath.
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.publisher.Flux;
public class ManualDemand {
public static void main(String[] args) {
Flux.range(1, 5).subscribe(new Subscriber<Integer>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription s) {
this.subscription = s;
s.request(2); // initial demand
}
@Override
public void onNext(Integer item) {
System.out.println("got " + item);
if (item % 2 == 0) {
subscription.request(2); // ask for more
}
}
@Override
public void onError(Throwable t) {
System.err.println("failed: " + t);
}
@Override
public void onComplete() {
System.out.println("done");
}
});
}
}The output is got 1 through got 5, followed by done. The batches are 1 and 2, then 3 and 4, then 5. After the fifth item, the source has nothing left, so it calls onComplete. The subscriber never needed to ask a third time.
In practice you rarely implement Subscriber from scratch, because the specification contains many rules about thread safety and ordering that are easy to break. Reactor provides BaseSubscriber, which handles the bookkeeping and lets you override hooks:
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
public class OneAtATime {
public static void main(String[] args) {
Flux.just("a", "b", "c").subscribe(new BaseSubscriber<String>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
request(1);
}
@Override
protected void hookOnNext(String value) {
System.out.println("processing " + value);
request(1); // ask for the next one when ready
}
@Override
protected void hookOnComplete() {
System.out.println("finished");
}
});
}
}Nothing happens until you subscribe
A Publisher is a description of work. Calling subscribe starts it. The first example of this tutorial shows the consequence: building a Flux with map and filter runs nothing until a subscriber arrives.
Flux<Integer> odds = Flux.range(1, 5)
.map(n -> n * n)
.filter(n -> n % 2 == 1);
odds.subscribe(System.out::println); // prints 1, 9, 25Each operator in the chain is itself a Publisher that wraps the one before it. When subscribe is called on the last one, it subscribes to the one before it, and so on up to the source. Then onSubscribe travels back down, and request travels up again. In a WebFlux application you rarely call subscribe yourself. The framework subscribes for you when it writes the response.
Rules that matter in practice
The specification has dozens of numbered rules. The following ones affect everyday code.
- Signals are serial. A subscriber's
onNext,onError, andonCompleteare never called concurrently. They may arrive on different threads over time, but not at the same time. You do not need locks inside a subscriber for that reason alone. nullis forbidden. A publisher must never emitnull, and a subscriber must be prepared for aNullPointerExceptionif it tries. This is whyMono<Void>and emptyMonoexist, and whyOptionalis not needed for absent values.- Errors are terminal. After
onError, the stream is finished. A pipeline that must continue after a failure has to handle the error upstream, for example withonErrorResume. You will see this in the error handling chapter. - Cancellation is a request, not a guarantee. After
cancel(), the publisher should stop soon, but a few moreonNextcalls may still arrive before it does. - A subscriber must not block. Methods like
onNextshould return quickly. Blocking inside them holds up whichever thread the publisher is using, which in WebFlux may be an event-loop thread. - One subscription per subscriber. If
onSubscribeis called a second time on the same subscriber, the subscriber must cancel the new subscription.
Common errors
- Forgetting to subscribe. A method that builds a pipeline and discards it does nothing. If a database write seems not to happen, check that the returned
Monois returned to the framework or subscribed to. - Subscribing twice by accident. Each
subscribecall re-runs a cold publisher from the beginning, so a repository query or HTTP call runs twice. - Ignoring
onErrorin a manual subscriber. The defaultsubscribe(consumer)with no error handler logs the error as anErrorCallbackNotImplementedexception, which is easy to overlook. Pass an error consumer or use an operator to handle it. - Requesting zero. Computing demand as
batchSize - inFlightcan yield zero. Guard the call. - Assuming
onNextruns on the subscribing thread. Signals run on whatever thread the source uses. Do not rely on thread-local state across operators.
Summary
Reactive Streams defines four interfaces and a strict signal order: onSubscribe, then any number of onNext, then at most one of onError or onComplete. The subscriber sets the pace through Subscription.request(n), and it can stop the flow with cancel(). Reactor's Mono and Flux, which come next, are implementations of Publisher that obey these rules, so you can compose them safely without checking the rules yourself.
Exercise
A subscriber receives onSubscribe and then calls request(3) once. The source holds ten items. How many items does the subscriber receive, does the stream complete, and what must the subscriber do to receive the rest?
Show answer
It receives exactly three items through onNext. The stream does not complete, because the publisher still has items and no terminal signal is allowed until they are delivered or the subscriber cancels. To receive more, the subscriber must call request(n) again. Demand is cumulative, so request(7) in total after the first call lets all ten items arrive, followed by onComplete.
Exercise
A colleague's pipeline calls repository.save(entity) inside a method and does not return the resulting Mono or subscribe to it. The entity is never stored. Using the contract, explain why, and name two ways to fix it.
Show answer
A Mono is a Publisher, and a Publisher does no work until a Subscriber subscribes and calls request. Because nothing subscribes, no signals flow and the save never runs. Fix it by returning the Mono from the controller or handler method so that WebFlux subscribes to it, or by chaining it into a larger pipeline, for example with flatMap or then, that is itself returned or subscribed. Calling subscribe() directly also works, but it is rarely the right choice in WebFlux code.