Sub topic 5
Backpressure: letting consumers set the pace
This chapter assumes you know the Publisher, Subscriber, and Subscription roles from the Reactive Streams chapter. It also assumes you can build a basic Flux pipeline.
The problem
A producer can emit items faster than a consumer can handle them. In a blocking program the slow consumer simply holds up the producer's thread. In an asynchronous pipeline nothing blocks, so the extra items pile up in memory until the process fails.
Backpressure solves this. The consumer tells the producer how many items it is ready to receive, and the producer sends no more than that.
Demand travels upstream
Backpressure uses the Subscription object. A subscriber calls request(n) to ask for n more items. The publisher may emit at most the total number requested so far.
Controlling demand yourself
BaseSubscriber lets you issue requests by hand. By default, subscribe with a lambda requests an unbounded amount. The code below requests two items at a time.
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
public class PacedDemo {
public static void main(String[] args) {
Flux.range(1, 6).subscribe(new BaseSubscriber<Integer>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
request(2);
}
@Override
protected void hookOnNext(Integer value) {
System.out.println("got " + value);
if (value % 2 == 0) {
request(2);
}
}
});
}
}It prints got 1 through got 6. The subscriber asks for the next batch only after it finishes the current one.
When the producer cannot slow down
Some sources, such as timers, sensors, and user events, cannot pause. If the consumer is slower, Reactor needs a policy for the surplus. You choose it with an onBackpressure... operator.
| Operator | Behavior when demand runs out |
|---|---|
| `onBackpressureBuffer()` | Stores surplus items in a queue. Memory grows if the consumer stays slow. |
| `onBackpressureDrop()` | Discards surplus items. |
| `onBackpressureLatest()` | Keeps only the newest surplus item. |
| `onBackpressureError()` | Fails the pipeline with an overflow error. |
The next example uses a ticker that emits every millisecond and a consumer that needs 100 ms per item.
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
public class DropDemo {
public static void main(String[] args) {
Flux.interval(Duration.ofMillis(1))
.onBackpressureDrop(n -> System.out.println("dropped " + n))
.publishOn(Schedulers.single(), 4)
.doOnNext(n -> slowWork())
.take(Duration.ofSeconds(1))
.blockLast();
}
static void slowWork() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}publishOn with a prefetch of 4 limits how much it requests from upstream. Without the onBackpressureDrop line, interval would fail with an OverflowException, because it cannot emit when there is no demand.
Batching demand with limitRate
An operator such as flatMap can request a large number of items from upstream. limitRate(n) caps the batch size. It requests n items, then replenishes demand once most of them have been consumed. This is useful when the source is a database cursor and you want bounded reads.
repository.findAll()
.limitRate(100)
.flatMap(this::enrich, 8);Here limitRate keeps reads in batches of 100, and the concurrency argument of flatMap allows only 8 enrichments in flight at once.
Common mistakes
- Subscribing with
subscribe(consumer)and assuming the consumer sets the pace. It requests unbounded demand, so only the operators in between can limit the flow. - Using
onBackpressureDropwhere every item matters, such as payments or orders. - Expecting backpressure across an HTTP connection to behave like in-process demand. The network layer applies it through TCP flow control, and the next chapters on streaming show where that matters.
Exercise
A Flux of sensor readings emits 1,000 values per second. The dashboard consumer handles only the most recent reading and does not need older ones. Which operator fits, and why not onBackpressureBuffer()?
Show answer
Use onBackpressureLatest(). It keeps only the newest surplus item, which matches a dashboard that wants current values. onBackpressureBuffer() would queue old readings that nobody needs, and with an unbounded queue it would use more and more memory while the consumer falls behind.