Reactor Basics with example | Backpressure (Overflow) – DROP, ERROR, LATEST, IGNORE, BUFFER | Good for beginners

In this article we will go through very basic & simple examples of backpressure handling in Project Reactor (by Pivotal). For synchronous, async & parallel processing refer this article.

Reactor Basics with example | Create, Subscribe, Synchronous, Async, Parallel, Backpressure, Non-Blocking | Good for beginners

Backpressure / Overflow

During asynchronous processing, if subscriber is consuming data slower than publisher, this situation is called as backpressure or overflow. In reactor code it is referred as Overflow. Reactor provides ways to handle the Overflow/Backpressure gracefully.

Flux uses default small buffer of size 256 which we will see in below examples.

Backpressure (Overflow) Strategy: DROP

DROP strategy drops the most recent next value if the downstream can’t keep up because its too slow. There are also ways provided to consume dropped values and handle them separately.

In below output you can see that till 256 (default buffer size), values were successfully published & then values starts dropping. Subscriber also received 256 values successfully.

Backpressure (Overflow) Strategy: LATEST

LATEST strategy keeps only the latest next value, overwriting any previous value if the downstream can’t keep up because its too slow.

In below output you can see that publishing of all 999 values seems to have gone fine. Subscriber also started asynchronously receiving values. But you can see subscriber directly received 999 after 255. This means that after 255 (default buffer of 256), all values were replaced with latest & finally last value of 999 received by subscriber.

Backpressure (Overflow) Strategy: ERROR

ERROR strategy throws OverflowException in case the downstream can’t keep up due to slowness. Publisher can handle exception & make sure to call error handle so that subscriber can do handling on subscriber side for such error scenarios.

You can see in below output that publishing & subscribing started on different threads. Subscriber received values till 255 & then error handler was called due to OverflowException. After that subscriber stopped.

Backpressure (Overflow) Strategy: IGNORE

With IGNORE strategy, as name suggests tit ignores any backpressure strategy. Subscriber must handle overflow else they will receive error.

Backpressure (Overflow) Strategy: BUFFER

With BUFFER strategy, as name suggests all values are buffered so that subscriber can receive all values. As per program below, buffer is infinite, so if published values are large in count & subscriber is too slow, then there is chance of out of memory just like Observable.


Leave a Reply

Your email address will not be published. Required fields are marked *