Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

Why does the Reactive Streams specification forbid calling onNext concurrently and require request(n) to be positive? What goes wrong in a hand-written Publisher that ignores these rules?

The specification requires serialized signals so that a subscriber can keep its state, such as counters, buffers or the current position, without locks; concurrent onNext calls could corrupt that state or deliver items out of order. It requires request(n) to be positive because demand is a running count, so a call with n of zero or less must end the stream with onError carrying an IllegalArgumentException instead of silently breaking the count. A hand-written Publisher that ignores these rules races its subscribers and overflows slow ones, which defeats backpressure, so in practice we use Flux.create, Flux.generate or Sinks and verify any custom publisher with the Reactive Streams TCK.

Why this question is asked

The Reactive Streams rules look like fine print, but each one exists because of a concrete failure. Interviewers ask about these two because they separate people who have only used Reactor operators from people who understand what the operators guarantee. The question also has a practical side: teams sometimes write their own Publisher to wrap a callback API, and those hand-written publishers are a common source of subtle production bugs. In this answer, we will look at what the two rules say, why each exists, what a broken publisher does to its subscribers, and the safer ways to create streams.

1A Quick Recap of the Two Rules

A Publisher sends signals to a Subscriber: onSubscribe first, then onNext for each item, then at most one onComplete or onError. The subscriber controls the flow with subscription.request(n), which adds n to its demand, the number of items it is ready to receive.

The first rule says onSubscribe, onNext, onError and onComplete must be signalled serially: never two at the same time, even if the publisher produces items on several threads. Calls may come from different threads, but each must finish before the next begins, with a happens-before relationship between them. The second rule says that if a subscriber calls request with zero or a negative number, the publisher must signal onError with an IllegalArgumentException, because such a call is a bug in the subscriber.

2Why Signals Must Be Serialized

Serialization is a gift to subscriber authors. Because no two signals overlap, a subscriber can be written like single-threaded code. Consider a subscriber that counts items and adds them to a list. With serialized signals, a plain int field and an ArrayList are safe. If two threads called onNext at the same time, the counter could lose increments, the ArrayList could be corrupted, and an onComplete racing with a final onNext could close a file before the last line was written.

Ordering is the other reason. Many streams are ordered: rows from a cursor, events from a log, bytes of a response. If two threads deliver items concurrently, item 5 can overtake item 4. Requiring serialization pushes the coordination to the single place that knows about the threads, the publisher, instead of every subscriber in the ecosystem.

Java
class CountingSubscriber implements Subscriber<String> {
private int count; // no lock needed: signals are serialized
private final List<String> items = new ArrayList<>();
public void onNext(String s) { count++; items.add(s); }
public void onComplete() { System.out.println(count); } // 1000 with a correct publisher
// ...
}
// With a publisher calling onNext from 4 threads at once:
// 987, or an ArrayIndexOutOfBoundsException from ArrayList.add

3Why request(n) Must Be Positive

Demand is a running total. The publisher adds each request to its outstanding demand and decrements it for every onNext. If a subscriber calls request(0), it asks for nothing, which is almost certainly a bug; if it calls request(-5), adding it would reduce the demand, possibly below zero, or turn an unbounded demand into a small one, and the publisher's bookkeeping would no longer mean anything.

The specification could have said to ignore such calls, but that would hide the bug: the stream would simply hang, waiting for demand that never comes. Instead the publisher must signal onError with an IllegalArgumentException, which makes the mistake visible at once. The specification also says that demand totals reaching Long.MAX_VALUE are treated as unbounded, so publishers must cap the sum rather than let it overflow into a negative number.

Java
Flux.range(1, 10).subscribe(new BaseSubscriber<Integer>() {
@Override protected void hookOnSubscribe(Subscription s) { s.request(0); }
@Override protected void hookOnError(Throwable t) {
System.out.println(t.getClass().getSimpleName()); // IllegalArgumentException
}
});

4What Goes Wrong in a Hand-Written Publisher

Here is a publisher written to wrap a message listener. It looks reasonable, and it passes a quick test with a fast subscriber.

Java
class ListenerPublisher implements Publisher<Message> {
public void subscribe(Subscriber<? super Message> s) {
s.onSubscribe(new Subscription() {
public void request(long n) { } // demand ignored, negative n accepted
public void cancel() { listener.stop(); }
});
listener.onMessage(s::onNext); // called from 4 listener threads at once
}
}
Step throughA publisher that ignores demand
Listener threadsHand-written publisherSlow subscriber
request(32): room for 32 items
message 1 to 32
onNext 1 to 32
messages 33 to 500 keep arriving
onNext 33, 34 ... with no demand left
queue overflows: error or unbounded memory

6 messages in order. Play them, or step through them one at a time.

Without demand tracking, the slow subscriber has no way to slow the producer down.

It breaks both rules. Messages arrive on four threads, so onNext runs concurrently and the subscriber's state races. It ignores request(n), so a slow subscriber, for example one that writes each message to a remote service, receives messages as fast as they arrive. Operators downstream, such as flatMap or publishOn, keep queues sized for the demand they requested, typically 32 or 256 items; when more arrive than requested, Reactor fails the stream with an overflow error, or the items pile up in memory until the service runs out of heap. Backpressure, the reason we chose reactive streams, is gone. It also does not handle cancel races, onError after onComplete, or exceptions thrown by the subscriber.

5Safer Ways to Create a Publisher

Writing a correct publisher means handling demand accounting with atomic counters, serializing signals from many threads, honouring cancellation and avoiding races between terminal signals. Reactor already does all of that, so we should almost never implement Publisher directly.

Flux.generate is for synchronous, pull-style sources: Reactor calls our generator once per requested item, so demand is honoured automatically. Flux.create is for callback-based sources such as listeners: we push into a FluxSink, which serializes calls from several threads and buffers according to a chosen overflow strategy, and sink.onRequest lets us pause or resume the underlying source. Sinks, for example Sinks.many().multicast().onBackpressureBuffer(), are for programmatic emission from application code; their tryEmitNext returns a result such as FAIL_NON_SERIALIZED instead of corrupting the stream when two threads emit at once.

Java
Flux<Message> messages = Flux.create(sink -> {
listener.onMessage(sink::next); // safe from many threads: FluxSink serializes
sink.onRequest(n -> listener.resume()); // react to demand
sink.onDispose(listener::stop); // cancel and termination
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> counter = Flux.generate(() -> 0, (state, sink) -> {
sink.next(state); // called once per requested item
if (state == 99) sink.complete();
return state + 1;
});

If we really must write our own Publisher, for example in a library, we verify it with the Reactive Streams TCK, the official test kit. We extend PublisherVerification, provide a factory for a publisher of n elements, and the TCK runs tests for each numbered rule, including concurrent request calls, request(0), and cancellation.

6Follow-up questions

Does serialized mean all signals come from the same thread?

No. Successive signals may come from different threads, as happens after publishOn or with a thread pool. Serialized only means they never overlap and each happens-before the next, so the subscriber sees a consistent order and consistent memory without its own locks.

What does Reactor do when a source emits more than requested?

It depends on the operator. Many operators detect it and fail with an overflow exception, often reported as a message about being unable to emit due to lack of requests. With Flux.create, the overflow strategy decides: buffer, drop, keep the latest, or error. The operator onBackpressureBuffer or onBackpressureDrop makes the choice explicit.

Why not just use locks in the subscriber instead?

Every subscriber in every library would need them, which adds cost to the common case and still would not fix ordering. Putting the burden on the publisher, which knows how many threads it uses, keeps the many subscribers simple and fast.

7Conclusion

In this answer, we saw that serialized signals let subscribers keep state without locks and preserve order, so concurrent onNext calls can corrupt state or reorder items. request(n) must be positive because demand is a running count, and a call with n of zero or less must produce onError with an IllegalArgumentException so the bug shows instead of hanging the stream. A hand-written publisher that ignores demand overflows slow subscribers and breaks backpressure, so we use Flux.generate, Flux.create or Sinks, and verify any custom Publisher with the Reactive Streams TCK.

What to say in the interviewAbout 90 seconds aloud

Open with

The serialization rule exists for the subscriber's sake. If onNext, onComplete and onError never overlap, a subscriber can keep plain fields, a counter, a buffer, a file handle, without any locking, and items keep their order.

Then, if they want more

If a publisher calls onNext from several threads at once, counts get lost, collections get corrupted, an onComplete can race a final onNext, and items can overtake each other. So the coordination belongs in the publisher, the one place that knows about its threads. Signals can still come from different threads, they just can't overlap.

The request rule is about the demand bookkeeping. Demand is a running total that the publisher decrements for each item, so request of zero or a negative number is meaningless and would corrupt the count. The spec says the publisher must respond with onError and an IllegalArgumentException, which surfaces the bug instead of leaving the stream hanging.

A hand-written publisher that ignores these rules typically wraps a listener and calls onNext from the listener's threads with no demand tracking, so a slow subscriber gets flooded, Reactor operators fail with overflow errors or memory grows, and backpressure is lost.

That's why I would use Flux.create, which serializes and buffers, Flux.generate for pull sources, or Sinks, and if I really had to implement Publisher myself, I would run it through the Reactive Streams TCK.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why does the Reactive Streams specification forbid calling onNext concurrently and...": https://scrivio-interview-library.netlify.app/spring-boot/reactive-fundamentals/95011bee7e/