Reactive Streams and backpressure

Mid-level Always asked 7 min

On this page

The question

What is backpressure, and how is it signalled in Reactive Streams?

30-second answer

Backpressure lets a slow consumer control how fast it receives data. In Reactive Streams, the signal is explicit: the Subscriber calls request(n) on its Subscription, and the Publisher may send at most n elements through onNext. Demand flows up and data flows down. A plain subscribe() requests everything, so a slow consumer must opt in to limits.

Understand it

The signals between Publisher and Subscriber

Step by step

subscribe() connects them. Nothing has flowed yet: a Publisher only describes data, and it waits to be told how much to send.

Step 1 of 8
View as text

A Publisher box at the top and a Subscriber box at the bottom, with a signal travelling between them. A demand counter and a row of delivered elements sit below.

subscribe() connects them. Nothing has flowed yet: a Publisher only describes data, and it waits to be told how much to send.

The Publisher hands back a Subscription through onSubscribe. It is the channel for demand, and the way to cancel.

The Subscriber asks for 2 with request(2). This is backpressure: demand travels upstream, and the consumer sets the pace.

The first element arrives through onNext. One unit of demand is used, so one is left.

The second element uses the last unit. Demand is 0, so the Publisher must stop, even though it has a third element ready.

When the Subscriber can take more, it calls request(1). Nothing arrives until it does.

The third element arrives, and demand is back to 0. The source has nothing left to send.

onComplete ends the stream, and it needs no demand. onError would end it the same way. After either one, no more signals arrive.

A Publisher box at the top and a Subscriber box at the bottom, with a signal travelling between them. A demand counter and a row of delivered elements sit below.

subscribe() connects them. Nothing has flowed yet: a Publisher only describes data, and it waits to be told how much to send.

The Publisher hands back a Subscription through onSubscribe. It is the channel for demand, and the way to cancel.

The Subscriber asks for 2 with request(2). This is backpressure: demand travels upstream, and the consumer sets the pace.

The first element arrives through onNext. One unit of demand is used, so one is left.

The second element uses the last unit. Demand is 0, so the Publisher must stop, even though it has a third element ready.

When the Subscriber can take more, it calls request(1). Nothing arrives until it does.

The third element arrives, and demand is back to 0. The source has nothing left to send.

onComplete ends the stream, and it needs no demand. onError would end it the same way. After either one, no more signals arrive.

Takeaway: Data flows down only after demand flows up. subscribe connects, request(n) asks, onNext delivers at most n, and onComplete or onError ends the stream.

A fast producer and a slow consumer

Explore

A source that can wait produces only what is requested, so it slows to 20/s. Nothing is lost. Flux.generate works this way.

100 /s
20 /s
View as text

A producer box and a consumer box with the chosen strategy between them, above three bars: elements produced, delivered and lost in 10 seconds. A mark names the outcome.

At 20/s against 50/s the consumer keeps up, so demand never runs out and all 200 elements arrive, whatever the strategy.

A source that can wait produces only what is requested, so it slows to 20/s. Nothing is lost. Flux.generate works this way.

onBackpressureDrop discards what arrives with no demand: 800 of 1000 elements are lost in 10 s, and the stream stays alive.

onBackpressureLatest keeps only the newest waiting element. The consumer stays current, and about 800 older elements are overwritten.

The buffer overflows at 1.3 s and cancels the source. The consumer drains 125 elements first, so OverflowException arrives only at 6.3 s.

onBackpressureError fails as soon as an element arrives with no demand: OverflowException, almost at once, after one delivered element.

A producer box and a consumer box with the chosen strategy between them, above three bars: elements produced, delivered and lost in 10 seconds. A mark names the outcome.

At 20/s against 50/s the consumer keeps up, so demand never runs out and all 200 elements arrive, whatever the strategy.

A source that can wait produces only what is requested, so it slows to 20/s. Nothing is lost. Flux.generate works this way.

onBackpressureDrop discards what arrives with no demand: 800 of 1000 elements are lost in 10 s, and the stream stays alive.

onBackpressureLatest keeps only the newest waiting element. The consumer stays current, and about 800 older elements are overwritten.

The buffer overflows at 1.3 s and cancels the source. The consumer drains 125 elements first, so OverflowException arrives only at 6.3 s.

onBackpressureError fails as soon as an element arrives with no demand: OverflowException, almost at once, after one delivered element.

Takeaway: Backpressure only slows a source that can wait. For one that cannot, such as a timer or a socket, you choose what to lose: elements, freshness or the stream.

Can the source slow down?A source that can wait, such as a generator, simply produces what is requested. A source that cannot wait, such as a timer or a socket, needs a strategy, which is to buffer, drop, keep the latest or fail.Consumer is slowerthan the producerSource can wait:it obeys request(n)Source cannot wait:timer, socket, sinkNothing is lostBuffer, drop,latest or error
Can the source slow down?A source that can wait, such as a generator, simply produces what is requested. A source that cannot wait, such as a timer or a socket, needs a strategy, which is to buffer, drop, keep the latest or fail.Consumer is slowerthan the producerSource can wait:it obeys request(n)Source cannot wait:timer, socket, sinkNothing is lostBuffer, drop,latest or error
Can the source slow down?

In code

Flux.range(1, 3).subscribe(new BaseSubscriber<Integer>() {
    private int seen;

    @Override
    protected void hookOnSubscribe(Subscription subscription) {
        subscription.request(2);        // ask for 2, not everything
    }

    @Override
    protected void hookOnNext(Integer value) {
        System.out.println("got " + value);
        if (++seen == 2) {
            request(1);                 // ready for one more
        }
    }
});
A subscriber that sets the pace
Flux<Long> ticks = Flux.interval(Duration.ofMillis(10));    // 100 per second

ticks.onBackpressureDrop(tick -> System.out.println("lost " + tick))
     .publishOn(Schedulers.boundedElastic(), 1)
     .subscribe(tick -> slowWrite(tick));                   // 20 per second
A timer cannot wait, so choose what to lose
Three interfaces, four signals down, two upA Publisher accepts a Subscriber. The Subscriber receives onSubscribe, onNext, onComplete and onError. The Subscription it receives offers request and cancel, which travel back up.Publisher:subscribeSubscriber:onSubscribe,onNext,onComplete, onErrorSubscription:request(n), cancel()
Three interfaces, four signals down, two upA Publisher accepts a Subscriber. The Subscriber receives onSubscribe, onNext, onComplete and onError. The Subscription it receives offers request and cancel, which travel back up.Publisher:subscribeSubscriber:onSubscribe,onNext,onComplete, onErrorSubscription:request(n), cancel()
Three interfaces, four signals down, two up
Flux.range(1, 1_000)
    .doOnRequest(n -> log.info("request({})", n))   // request(100), then request(75) each time 75 are used
    .limitRate(100)
    .subscribe(this::process);
limitRate: ask upstream in batches instead of all at once

Solve it

A sensor stream outruns the database

A sensor emits a reading every millisecond with Flux.interval. Each reading is saved with one insert that takes about 5 ms. The pipeline fails with “Could not emit tick due to lack of requests”. With onBackpressureBuffer() added, memory grows until the service dies.

  1. Compare the rates. 1,000 readings per second arrive, about 200 per second are saved: 800 per second pile up.
  2. Ask whether the source can slow down. A timer cannot wait for demand, so backpressure cannot slow it. Choose what happens to the excess.
  3. Make the consumer faster. Batch: bufferTimeout(100, 1s) and one multi-row insert per batch cut the cost per reading, so the database keeps up.
  4. Bound what remains. An unbounded buffer only delays the crash. Cap it and decide what to drop, counting each drop in a metric.
  5. Check. Under load, memory stays flat, the batch rate matches the input rate and the drop counter stays near zero.
Flux.interval(Duration.ofMillis(1))
    .map(tick -> sensor.read())
    .onBackpressureBuffer(10_000, dropped -> droppedReadings.increment(), BufferOverflowStrategy.DROP_OLDEST)
    .bufferTimeout(100, Duration.ofSeconds(1))              // up to 100 readings, or whatever arrived in 1 s
    .concatMap(batch -> repository.saveAll(batch).then())   // one insert per batch, in order
    .subscribe();
Bounded buffer, batched writes, one batch at a time

How to answer

  • Demand is a number the Subscriber sends, and it adds up across calls.
  • A Publisher never sends more than was requested.
  • A source that cannot wait, such as a timer, needs a strategy instead.
  • onComplete and onError need no demand.

Common mistakes

  • Saying backpressure is a buffer. A buffer is one strategy for a source that cannot slow down.
  • Thinking subscribe() with a lambda limits anything. It requests Long.MAX_VALUE.

Follow-up questions

What are Publisher, Subscriber and Subscription in Reactive Streams?

A Publisher produces elements and has one method, subscribe. A Subscriber receives onSubscribe, onNext, onComplete and onError. A Subscription links one Subscriber to one Publisher, with request(n) and cancel(). A Processor is both a Subscriber and a Publisher. The specification defines only these, and libraries such as Reactor implement them.

  • The order is onSubscribe, then any number of onNext, then at most one terminal signal.
  • Java 9 copied these interfaces as java.util.concurrent.Flow.
  • You rarely implement them, because Flux and Mono already do.

See it in the infographic: The signals between Publisher and Subscriber

A Kafka listener or timer pushes data faster than you can process it. What are your options?

It cannot obey request(n), so choose what to lose. onBackpressureBuffer holds elements, at a memory cost. onBackpressureDrop loses the excess but keeps running. onBackpressureLatest keeps only the newest, which suits prices or sensor readings. onBackpressureError fails fast. Also try consuming faster, or batching with buffer. With no strategy, Flux.interval fails by itself.

  • Drop suits metrics; latest suits current state; error suits data you cannot lose.
  • An unbounded buffer only delays the failure until memory runs out.
  • Flux.interval throws OverflowException when demand runs out.

See it in the infographic: A fast producer and a slow consumer

With onBackpressureBuffer(100), a source at 100 per second and a consumer at 20, when does the subscriber see the error?

Later than you would expect. The buffer fills after about 1.25 seconds, because it gains 80 per second, and the source is cancelled then. The subscriber still drains what was buffered, so OverflowException reaches it after about 6 seconds. Between those moments, the stream looks healthy while no new data enters.

  • Overflow time is capacity divided by the gap in rates.
  • The error waits behind the elements already buffered.
  • Pass an overflow strategy, such as BufferOverflowStrategy.DROP_OLDEST, to keep the stream alive.

See it in the infographic: A fast producer and a slow consumer

What does limitRate do?

It splits a large demand into small batches. limitRate(10) requests 10 from upstream, then 8 each time three quarters of the batch is consumed, even when downstream asked for everything. This keeps a source such as a database cursor from fetching a huge amount at once. It shapes demand, not time, so it is not a rate limiter per second.

  • It replenishes at 75 percent by default, which is why the next request is 8.
  • For a limit per second, delay elements or use a dedicated rate limiter.
Flux.range(1, 30)
    .doOnRequest(n -> System.out.println("request " + n))
    .limitRate(10)
    .subscribe();    // request 10, 8, 8, 8

See it in the infographic: The signals between Publisher and Subscriber

How does a consumer stop a stream early, and what happens upstream?

It calls cancel() on the Subscription, and the signal travels upstream through every operator, so a source can release its connection or stop its work. Operators such as take(n) do this for you once they have n elements. Elements already in flight may still arrive, so a Subscriber must tolerate a few.

  • Cancel is what frees a database cursor when a client disconnects.
  • doOnCancel runs when it happens; doFinally runs on any kind of ending.
  • A stream can end without onComplete, so cleanup belongs in doFinally.

See it in the infographic: The signals between Publisher and Subscriber

What does publishOn do to demand?

It requests a prefetch from upstream, not what the Subscriber asked for. By default it requests 256, then 192 whenever three quarters are consumed, so a source can run ahead by up to one prefetch. To tighten this, pass a smaller prefetch, as in publishOn(scheduler, 1).

Does backpressure work across the network?

Not as request(n), because that signal stays inside one process. Between services, HTTP relies on TCP (Transmission Control Protocol) flow control: when a reader stops, the window fills and the writer stalls. Reactor Netty links this to demand. Protocols such as RSocket carry demand over the wire.

Check yourself

1. How much does a plain subscribe(value -> ...) request?
Show answers
  • Long.MAX_VALUE, which means everything: Correct. A lambda subscriber opts out of pacing. Run with doOnRequest, and it prints the maximum value.
  • One element at a time: Incorrect. That would need a subscriber calling request(1) each time, as BaseSubscriber can.
  • 256, the default prefetch: Incorrect. That is what publishOn requests from upstream, not what subscribe asks for.
2. A Subscriber has called request(2) and received 2 elements. The Publisher has more ready. What does it do?
Show answers
  • It waits for more demand.: Correct. A Publisher may never send more than was requested, however much it has ready.
  • It keeps sending, and the Subscriber buffers the rest.: Incorrect. That breaks the specification. The Subscriber never agreed to more.
  • It sends onComplete.: Incorrect. The stream has not ended. It is only waiting for demand.
3. A stream of live prices arrives faster than the screen can draw. Only the current price matters. Which strategy fits?
Show answers
  • onBackpressureLatest: Correct. It overwrites what is waiting, so the consumer always gets the newest value.
  • onBackpressureBuffer: Incorrect. The consumer would fall further behind, drawing prices that are out of date.
  • onBackpressureError: Incorrect. A slow screen is no reason to end the stream.