Sub topic 5
Backpressure: letting consumers set the pace
This chapter assumes you can read a Reactor pipeline built from Flux and Mono, and that you know a subscribe call triggers the work. It also assumes you know the three Reactive Streams interfaces: Publisher, Subscriber, and Subscription. You don't need to have written a custom Subscriber before.
The problem backpressure solves
A producer and a consumer rarely run at the same speed. A database cursor can return rows faster than a slow HTTP client can download them. A message topic can deliver events faster than your service can process them.
If the producer simply pushes everything it has, something between the two has to hold the surplus. That is usually an unbounded queue, and it grows until the JVM runs out of memory.
Backpressure is the mechanism that prevents this. The consumer tells the producer how many items it is ready to receive, and the producer sends no more than that. Demand flows upstream and data flows downstream.
Demand is a number
In Reactive Streams, backpressure comes down to one method: Subscription.request(long n). The rules are:
- A
Publishermust not send moreonNextsignals than the total demand requested so far. - Demand is cumulative.
request(2)followed byrequest(3)allows five items in total. request(Long.MAX_VALUE)means unbounded demand. The publisher may emit as fast as it can and stop counting.cancel()tells the publisher to stop and release resources.
Seeing demand with a custom subscriber
A plain subscribe(consumer) call requests unbounded demand, so you never see backpressure at work. To control demand yourself, extend BaseSubscriber. The doOnRequest operator prints each request as it reaches the source.
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
public class RequestDemo {
public static void main(String[] args) {
Flux.range(1, 6)
.doOnRequest(n -> System.out.println("request(" + n + ")"))
.subscribe(new BaseSubscriber<Integer>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
request(2); // initial demand
}
@Override
protected void hookOnNext(Integer value) {
System.out.println("got " + value);
if (value % 2 == 0) {
request(2); // ask for the next batch
}
}
});
}
}The output shows items arriving in batches of two, each batch preceded by a request(2). The source never emits an item that nobody asked for.
Controlling demand with operators
You rarely write a Subscriber by hand. Most of the time you shape demand with operators placed in the pipeline.
limitRate
limitRate(n) stops a fast downstream request from reaching the source as one huge number. It asks upstream for n items first, then asks for more as the downstream consumes them. It replenishes in batches of 75% of n. This is useful when the downstream requests unbounded demand but the source is expensive, such as a database cursor.
Flux.range(1, 1000)
.doOnRequest(n -> System.out.println("upstream request " + n))
.limitRate(100)
.subscribe(i -> { /* process */ });The source sees request(100), then a series of request(75).
Overflow strategies
Sometimes the source cannot slow down. Timers, mouse events, sensor readings and market ticks do not wait for you. For these sources you must choose what happens when demand runs out.
| Operator | Behaviour when the consumer is behind | Typical use |
|---|---|---|
| `onBackpressureBuffer()` | Queues items. The default queue is unbounded. | Short bursts, when memory is not a concern |
| `onBackpressureBuffer(maxSize)` | Queues up to `maxSize`, then signals an error | Bounded bursts with a hard limit |
| `onBackpressureDrop()` | Discards items that arrive without demand | Samples where losing some values is fine |
| `onBackpressureLatest()` | Keeps only the newest item and replaces older ones | Prices, positions, status values |
| `onBackpressureError()` | Fails the stream with an overflow error | Cases where silent loss is unacceptable |
Choosing one is a business decision as much as a technical one. Dropping a stock tick is fine. Dropping a payment event is not.
A common failure: Flux.interval
Flux.interval is a source that cannot slow down, because it emits on a timer. If the consumer cannot keep up, Reactor throws an OverflowException with a message like "Could not emit tick N due to lack of requests".
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class IntervalDemo {
public static void main(String[] args) {
Flux.interval(Duration.ofMillis(1))
.onBackpressureDrop() // remove this line to see the error
.concatMap(tick ->
Mono.delay(Duration.ofMillis(100)).thenReturn(tick))
.take(5)
.doOnNext(tick -> System.out.println("processed tick " + tick))
.blockLast();
}
}Each tick takes 100 ms to process but arrives every millisecond. With onBackpressureDrop() the pipeline processes about one tick in a hundred and discards the rest. Without that line, concatMap runs out of demand after its small prefetch and the stream fails with the overflow error. The blockLast() call is acceptable here because this is a main method and not a request thread.
Where backpressure is hidden: prefetch and concurrency
Operators that hop threads or run inner publishers keep internal queues, and each has a demand setting.
publishOn(scheduler)prefetches 256 items by default.publishOn(scheduler, n)changes that.flatMapruns up to 256 inner publishers at the same time by default.flatMap(fn, concurrency)lowers that limit. For a call to a fragile downstream service, a concurrency of 8 or 16 is often more sensible than 256.concatMapprocesses inner publishers one at a time and prefetches a small number of source items.
A quick check on any slow pipeline is to ask where the demand limit is. If a flatMap calls a remote service for each item and you have not set a concurrency, a large source can start 256 simultaneous calls.
Flux<String> ids = Flux.range(1, 10_000).map(i -> "id-" + i);
Flux<String> results = ids.flatMap(
id -> lookup(id), // returns Mono<String>
16); // at most 16 lookups in flightBackpressure in a WebFlux application
In a WebFlux service, the HTTP connection is the consumer. When you return a Flux from a controller, the framework subscribes to it. It requests items as the network connection can accept them. A slow client therefore leads to a slower pull from your pipeline, and this works all the way back to the source, provided every stage in between respects demand.
Two practical points follow.
- A client that disconnects causes a
cancel(), which stops the upstream work. Your pipeline should release resources when it is cancelled.doFinallyruns on cancellation as well as on completion and error. - For an endless stream whose source ignores demand, you must add an overflow strategy yourself.
@GetMapping(path = "/ticks", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> ticks() {
return Flux.interval(Duration.ofMillis(10))
.onBackpressureLatest(); // a slow client sees the newest tick, not an error
}Common mistakes
- Assuming
subscribe(consumer)applies backpressure. It requests unbounded demand. UselimitRate,BaseSubscriber, or a boundedflatMapwhen you need a limit. - Using an unbounded buffer as a fix.
onBackpressureBuffer()hides the problem until the heap is full. Prefer a bounded buffer or a drop strategy. - Blocking inside the pipeline. A blocking call stops the thread from requesting more items, so the pipeline stalls instead of slowing down gracefully. Blocking work is covered in the chapter on threading and schedulers.
- Dropping silently by accident.
onBackpressureDroploses data with no error. Pass a consumer, as inonBackpressureDrop(item -> log.warn("dropped {}", item)), so you can see how much is lost. - Expecting backpressure across a network hop. Backpressure applies inside a Reactor chain and to the connection to the client. It does not extend through a message broker or a remote service. Each hop needs its own limits.
Exercise
A controller returns Flux.interval(Duration.ofMillis(1)) as a Server-Sent Events stream, and some clients on slow connections receive an error about being unable to emit a tick. Which operator would you add so slow clients always receive the most recent tick, and why is onBackpressureBuffer() a poor choice here?
Show answer
Add onBackpressureLatest(). It keeps only the newest tick while the client has no demand, so a slow client skips old values but stays connected. onBackpressureBuffer() with no size queues every tick for each slow client. Memory grows without limit as the backlog builds, and the client falls further behind the live data.
Exercise
A pipeline reads 1,000,000 ids and calls flatMap(id -> client.fetch(id)) with no other settings. The remote service starts failing under load. What is the cause, and what is the smallest change that fixes it?
Show answer
By default flatMap allows up to 256 inner publishers to run at the same time, so the service receives up to 256 concurrent calls. Pass a lower concurrency value, for example flatMap(id -> client.fetch(id), 16). The operator then requests only enough items from upstream to keep 16 calls in flight.