Learn how Spring WebFlux handles backpressure to maintain responsiveness and prevent system overload in reactive applications.
๐ Table of Contents:
- What is Backpressure?
- Why Backpressure Matters in Reactive Systems
- Reactive Streams and Backpressure
- How WebFlux Handles Backpressure
- Controlling Data Flow with Operators
- Simulating a Slow Consumer
- Tips for Optimizing Backpressure
- Final Thoughts

๐ 1. What is Backpressure?
Backpressure refers to the mechanism that allows a subscriber to signal to the publisher that it can’t keep up with the data rate โ essentially applying “back pressure” on the stream.
โ 2. Why Backpressure Matters in Reactive Systems
Without backpressure:
- Memory can overflow from unbounded queues
- The system becomes unresponsive under load
- You lose the benefits of non-blocking IO
Reactive systems must be resilient to slow consumers and high data throughput.
๐ 3. Reactive Streams and Backpressure
Reactive Streams specification supports backpressure natively.
In Reactor (used by WebFlux):
Mono
handles backpressure implicitly (single item)Flux
honors demand via request(n)
When using Flux
, you can request only N items at a time.
โ๏ธ 4. How WebFlux Handles Backpressure
WebFlux automatically:
- Applies backpressure between layers (controller โ service โ repository)
- Utilizes bounded elastic and parallel schedulers
- Uses a reactive HTTP layer that communicates demand
Example:
1 2 3 4 5 6 7 8 |
@GetMapping("/events") public Flux<String> streamEvents() { return Flux.interval(Duration.ofMillis(100)) .map(i -> "Event " + i); } |
This will slow down if the subscriber can’t keep up.
๐ง 5. Controlling Data Flow with Operators
๐งฐ Useful Operators:
limitRate(n)
โ Limits the request rate from the downstreamonBackpressureBuffer(n)
โ Buffers data when overwhelmedonBackpressureDrop()
โ Drops data silentlyonBackpressureLatest()
โ Keeps only the most recent item
Example:
1 2 3 4 5 6 7 |
Flux.range(1, 1000) .onBackpressureBuffer(100) .doOnNext(System.out::println) .subscribe(); |
๐งช 6. Simulating a Slow Consumer
1 2 3 4 5 6 7 8 9 |
Flux.interval(Duration.ofMillis(10)) .onBackpressureDrop() .subscribe(i -> { Thread.sleep(100); // Simulate slow subscriber System.out.println("Received: " + i); }); |
๐ก 7. Tips for Optimizing Backpressure
- Avoid unbounded data sources
- Use buffering or throttling operators wisely
- Profile memory and CPU for large streams
- Combine with retry + rate-limiting strategies
โ 8. Final Thoughts
Backpressure is the heart of resilient reactive systems. Spring WebFlux offers seamless backpressure handling out of the box, but understanding how to apply buffering, dropping, or limiting strategies is key for production-grade applications.