Java.Reactive.What is backpressure in the context of reactive programming?

🙌 Backpressure is one of the most important — and often misunderstood — concepts in reactive programming, especially when dealing with asynchronous streams.

Let’s unpack it clearly 👇

🔄 What is Backpressure?

Backpressure refers to a situation and a mechanism in reactive programming where:

🔹 The data producer is faster than the consumer,
🔹 So we need a way to slow down or buffer the data
🔹 Otherwise, we risk out-of-memory errors, dropped data, or crashes

🧠 Real-world Analogy:

Imagine you’re filling water into a cup:

  • If you pour too fast, the cup overflows.
  • The cup (consumer) needs a way to tell the faucet (producer) to slow down.

That’s backpressure.

🎯 Why Is It Important?

In reactive systems (like RxJava, Reactor, Spring WebFlux), you often deal with:

  • Fast publishers (e.g. user events, network messages, Kafka topics)
  • Slow consumers (e.g. writing to disk, slow database, UI rendering)

Without backpressure:

  • You may flood your system with more data than it can handle.
  • Memory usage spikes ⬆️, performance drops ⬇️, and bugs appear 🐛.

🛠 Reactive Types and Backpressure Support

TypeBackpressure?Notes
Observable❌ NoSuitable for UI or small, fast streams
Flowable✅ YesUse for high-throughput or unbounded streams
Publisher (Java Flow API)✅ YesPart of Reactive Streams specification
Mono / Flux (Project Reactor)✅ YesUsed in Spring WebFlux

🔄 How Flowable Handles Backpressure in RxJava

Flowable<Integer> fastSource = Flowable.range(1, 1000000)
    .observeOn(Schedulers.io());

fastSource
    .map(i -> {
        Thread.sleep(1); // simulate slow consumer
        return i;
    })
    .subscribe(System.out::println);

If you don’t handle backpressure, this may crash or behave unpredictably.

But with .onBackpressureBuffer():

fastSource
    .onBackpressureBuffer()
    .map(...)
    .subscribe(...);

You can choose what to do when pressure builds:

StrategyWhat It Does
onBackpressureBuffer()Buffers items until consumer is ready (default)
onBackpressureDrop()Drops new items if buffer is full
onBackpressureLatest()Keeps only the latest item, drops older ones
onBackpressureError()Throws an error immediately when overwhelmed

🔍 Spring WebFlux (Reactor)

Spring WebFlux’s Flux is backpressure-aware by default because it implements Publisher from the Reactive Streams spec.

Consumers can request(n) items — controlling how much they can handle.

🧠 Summary

  • Backpressure = “Slow down! I can’t handle that much data right now!”
  • Prevents overwhelming the consumer.
  • Crucial for building robust, scalable, and memory-safe reactive systems.
This entry was posted in Без рубрики. Bookmark the permalink.