Backpressure in Java: Flow Control With Reactive Streams and Virtual Threads
What backpressure is and why unbounded buffers fail. Demand with request(n), SubmissionPublisher's blocking submit and dropping offer, Reactor's limitRate and drop, latest and buffer strategies, and the virtual-thread equivalents: bounded queues and semaphores.
kvi5hnuCode Sprout team member8 min readOn this page
A fast producer and a slow consumer can't run side by side for long. If a price feed delivers 1,000 ticks a second and the code that stores them handles 100, the other 900 have to go somewhere every second. Without a plan they pile up in an unbounded buffer until the heap runs out, or latency grows until every result is stale. Backpressure is the plan: a way for the consumer's limits to affect the producer.
There are only a few honest answers to "the consumer is full":

- Slow the producer down. It produces only what the consumer asked for, or blocks until there's room. Nothing is lost.
- Drop items that don't fit. Fine for samples and metrics.
- Keep only the latest value. Fine for state that is replaced wholesale: a price, a position, a progress bar.
- Buffer up to a limit, then fail, which absorbs short bursts and turns sustained overload into a visible error.
"Buffer without a limit" isn't on the list, because it just postpones the failure.
Demand in Reactive Streams
Reactive Streams builds option 1 into the protocol (article 45). A subscriber says how many items it can take with request(n), and the publisher may never send more. A pull-based source, such as a database cursor, a file or Flux.range, produces exactly what's requested. Demand also propagates through the pipeline: each operator requests from upstream according to what downstream requested.
Some sources can't be slowed down: market data, sensor readings, user clicks, a message broker pushing to you. For those, the pipeline has to choose one of the other strategies at the point where demand runs out.
Backpressure in the JDK
The program puts a slow consumer (10 ms per item) behind a fast producer of 50 items, four ways: a SubmissionPublisher with submit, one with offer, and the virtual-thread tools, a bounded queue and a semaphore.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
/** A consumer that needs 10 ms per item and asks for one item at a time. */
static final class SlowSubscriber implements Flow.Subscriber<Integer> {
final AtomicInteger received = new AtomicInteger();
final CountDownLatch done = new CountDownLatch(1);
private Flow.Subscription subscription;
@Override public void onSubscribe(Flow.Subscription s) { subscription = s; s.request(1); }
@Override public void onNext(Integer item) {
try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
received.incrementAndGet();
subscription.request(1);
}
@Override public void onError(Throwable e) { done.countDown(); }
@Override public void onComplete() { done.countDown(); }
}
static long millisSince(long start) { return (System.nanoTime() - start) / 1_000_000; }
public static void main(String[] args) throws Exception {
ExecutorService delivery = Executors.newVirtualThreadPerTaskExecutor();
// 1. submit() blocks when the subscriber's buffer is full: the producer is slowed to the consumer's pace
var blocking = new SubmissionPublisher<Integer>(delivery, 4); // buffer of 4 items per subscriber
var a = new SlowSubscriber();
blocking.subscribe(a);
long start = System.nanoTime();
for (int i = 1; i <= 50; i++) blocking.submit(i);
long producerTime = millisSince(start);
blocking.close();
a.done.await();
System.out.println("1. submit: received " + a.received + " of 50; producer was held back: " + (producerTime >= 300));
// 2. offer() with a drop handler never blocks: items that don't fit are dropped
var dropping = new SubmissionPublisher<Integer>(delivery, 4);
var b = new SlowSubscriber();
dropping.subscribe(b);
AtomicInteger dropped = new AtomicInteger();
start = System.nanoTime();
for (int i = 1; i <= 50; i++) {
dropping.offer(i, (subscriber, item) -> { dropped.incrementAndGet(); return false; }); // false: don't retry
}
producerTime = millisSince(start);
dropping.close();
b.done.await();
System.out.println("2. offer: producer was held back: " + (producerTime >= 300)
+ "; most items dropped: " + (dropped.get() > 25)
+ "; received + dropped = " + (b.received.get() + dropped.get()));
// 3. With virtual threads, a bounded queue is backpressure: put() blocks the producer cheaply
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(4);
AtomicInteger consumed = new AtomicInteger();
Thread consumer = Thread.ofVirtual().start(() -> {
try {
for (int item = queue.take(); item != -1; item = queue.take()) {
Thread.sleep(10);
consumed.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
start = System.nanoTime();
for (int i = 1; i <= 50; i++) queue.put(i);
queue.put(-1); // end-of-stream marker
producerTime = millisSince(start);
consumer.join();
System.out.println("3. queue: consumed " + consumed + " of 50; producer was held back: " + (producerTime >= 300));
// 4. A semaphore limits how many calls reach a downstream service at once
Semaphore permits = new Semaphore(5);
AtomicInteger inFlight = new AtomicInteger(), maxInFlight = new AtomicInteger();
try (ExecutorService requests = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100; i++) {
requests.submit(() -> {
permits.acquire();
try {
maxInFlight.accumulateAndGet(inFlight.incrementAndGet(), Math::max);
Thread.sleep(20); // the downstream call
inFlight.decrementAndGet();
} finally {
permits.release();
}
return null;
});
}
}
System.out.println("4. semaphore: 100 requests, at most " + maxInFlight + " in flight at once");
delivery.close();
}
}
Output:
1. submit: received 50 of 50; producer was held back: true
2. offer: producer was held back: false; most items dropped: true; received + dropped = 50
3. queue: consumed 50 of 50; producer was held back: true
4. semaphore: 100 requests, at most 5 in flight at once
submitblocks. Each subscriber has a bounded buffer, here 4 items (the default isFlow.defaultBufferSize(), 256). When it was full,submitblocked the producer until the consumer made room, so the producer ran at the consumer's pace, and all 50 items arrived.offerdrops.offer(item, onDrop)never blocks. When the buffer is full it calls the drop handler, which can returntrueto retry once orfalseto give up. The producer finished at once, most items were dropped, and every item was either received or dropped: none disappeared silently.offer(item, timeout, unit, onDrop)waits up to a timeout first.- A bounded queue.
ArrayBlockingQueue.putblocks when the queue is full. On a virtual thread, that blocking costs almost nothing, so a bounded queue between a producer thread and a consumer thread is backpressure, with the same effect assubmit. - A semaphore caps how many requests reach a downstream service at the same time (article 12). A hundred virtual threads were started, but never more than 5 were inside the guarded call. The rest waited cheaply for a permit.
Backpressure in Reactor
Reactor exposes demand with limitRate and handles sources that ignore demand with the onBackpressure... operators. This program needs reactor-core and was run with Reactor 3.7.6. Its ticks() source pushes 1,000 items as fast as it can, ignoring demand.
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.scheduler.Schedulers;
// Needs reactor-core (io.projectreactor:reactor-core:3.7.x) on the class path
public class ReactorBackpressure {
/** A source that pushes 1,000 ticks as fast as it can, ignoring demand, like a market feed. */
static Flux<Integer> ticks() {
return Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) sink.next(i);
sink.complete();
}, FluxSink.OverflowStrategy.IGNORE);
}
static void slow(int tick) {
try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
public static void main(String[] args) {
// 1. A demand-aware source: limitRate splits demand into batches
List<Long> requests = new CopyOnWriteArrayList<>();
Flux.range(1, 40).doOnRequest(requests::add).limitRate(10).blockLast();
System.out.println("1. requests seen by range(): " + requests);
// 2. A source that ignores demand, three strategies for the overflow
AtomicInteger dropped = new AtomicInteger(), received = new AtomicInteger();
ticks().onBackpressureDrop(t -> dropped.incrementAndGet())
.publishOn(Schedulers.single(), 16)
.doOnNext(ReactorBackpressure::slow)
.doOnNext(t -> received.incrementAndGet())
.blockLast();
System.out.println("2. drop: received + dropped = " + (received.get() + dropped.get())
+ "; most dropped: " + (dropped.get() > 500));
AtomicReference<Integer> last = new AtomicReference<>();
ticks().onBackpressureLatest()
.publishOn(Schedulers.single(), 16)
.doOnNext(ReactorBackpressure::slow)
.doOnNext(last::set)
.blockLast();
System.out.println(" latest: last tick received = " + last.get());
try {
ticks().onBackpressureBuffer(50)
.publishOn(Schedulers.single(), 16)
.doOnNext(ReactorBackpressure::slow)
.blockLast();
} catch (RuntimeException e) {
System.out.println(" buffer(50): " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
Output:
1. requests seen by range(): [10, 8, 8, 8, 8, 8]
2. drop: received + dropped = 1000; most dropped: true
latest: last tick received = 1000
buffer(50): OverflowException: The receiver is overrun by more signals than expected (bounded queue...)
limitRate(10)turned the subscriber's unbounded demand (blockLastrequests everything) into batches: first 10, then 8 each time 75% of the batch had been consumed.rangeproduced exactly that much at a time.- The overflow strategies.
publishOn(scheduler, 16)requests 16 items at a time, far slower thanticks()pushes:onBackpressureDropdiscarded what couldn't be delivered and reported each dropped item to its callback. Received plus dropped was always 1,000.onBackpressureLatestkept only the newest undelivered item, so the consumer skipped ahead and still ended with tick 1,000.onBackpressureBuffer(50)absorbed up to 50 extra items and then failed the stream withOverflowException.onBackpressureError(), not shown, fails as soon as demand is exceeded.
Where you place the operator matters: it handles overflow from everything above it, on behalf of everything below.
Virtual threads have backpressure too
A common claim is that virtual threads "have no backpressure". It's more accurate to say they don't need a protocol for it, because blocking is cheap:
- A blocking call is demand. A virtual thread that calls
socket.read()orqueue.take()consumes exactly as fast as it processes. TCP flow control then slows down a remote sender automatically. - Bounded queues connect producers and consumers inside a process, with
putandtake(orofferwith a timeout, for dropping). - Semaphores limit concurrency towards a shared resource, such as a database pool or a rate-limited API.
- Structured concurrency bounds the work per request (Part 4).
What's missing is the ready-made operator vocabulary: onBackpressureLatest, time windows, sampling. With virtual threads, you write those few lines yourself, for example a consumer that drains the queue and keeps only the newest element. For pipelines full of such stream logic, a reactive library may still be the clearer tool (article 47).
The real anti-pattern in both worlds is the unbounded buffer: Executors.newFixedThreadPool with its unbounded queue, onBackpressureBuffer() without a size, starting a virtual thread per incoming message from a firehose. Every one of them converts overload into memory growth.
What's current
SubmissionPublisheris unchanged since Java 9. Its buffer capacity is rounded up to a power of two, andFlow.defaultBufferSize()returns 256.- Reactor 3.7's
onBackpressureBufferhas variants with a time-to-live and an overflow strategy (DROP_OLDEST,DROP_LATEST,ERROR). RxJava 3 has the same operators onFlowable. - JDK 21's virtual threads made blocking backpressure (bounded queues, semaphores) practical at the scale where reactive operators used to be the only option.
Common questions
Is a large buffer a good idea? Only to absorb bursts. A buffer doesn't change the long-term rates: if the consumer is slower on average, any buffer fills up eventually. It does add latency, because items wait in it.
How do I choose between drop and latest? Drop when every item is independent and losing some is acceptable (sampling). Latest when only the current value matters and every newer value replaces the older ones.
Does backpressure work across the network? Within one TCP connection, yes: a reader that stops reading fills the receive window and the sender's writes block or stall. Across services it depends on the protocol. RSocket and gRPC streaming carry demand explicitly, while plain HTTP request/response relies on timeouts, rate limits and load shedding.
Why did onBackpressureLatest still end with tick 1,000?
Because the newest item is always kept when the consumer is busy, and the last item emitted is the newest one of all. The consumer skipped the intermediate ticks, not the final state.
Summary
- Backpressure handles a producer that's faster than its consumer: slow the producer, drop items, keep the latest, or buffer to a limit and fail. Never buffer without a limit.
- Reactive Streams carries demand with
request(n). Pull-based sources honour it, and push-based sources need an overflow strategy. SubmissionPublisher.submitblocks when a subscriber's buffer is full, andofferdrops through a handler.- Reactor offers
limitRateandonBackpressureDrop,Latest,BufferandError. - With virtual threads, cheap blocking is backpressure: bounded queues between producers and consumers, and semaphores in front of shared resources.
Practice questions
A service receives events from a message broker and, for each one, starts a virtual thread that writes to a database with 20 connections. During a spike, 200,000 events arrive in a minute. What goes wrong, and how do you fix it?
Answer
200,000 virtual threads are created, and almost all of them wait for the 20 connections. Memory grows, timeouts fire, and the database is hammered as soon as connections free up. There's no backpressure towards the broker. Fix it by bounding the work: consume with a fixed number of consumer threads (or a semaphore of about 20 permits) that only fetch the next message when they have capacity, so the broker keeps the backlog.
A dashboard shows live positions of 500 vehicles, updated by a feed at 50 updates per second per vehicle. The UI can render 5 updates per second. Which strategy fits, and why?
Answer
Keep the latest, per vehicle: each update replaces the previous position, so intermediate updates have no value once a newer one exists. In Reactor, group by vehicle and use onBackpressureLatest, or sample(Duration.ofMillis(200)). With virtual threads, keep a map of the latest position per vehicle that the renderer reads 5 times a second.
What's the difference between SubmissionPublisher.submit and offer, when a subscriber's buffer is full?
Answer
submit blocks the calling thread until there is room in the buffer, slowing the producer to the subscriber's pace. offer doesn't block (or blocks only up to a timeout in its timed variant). It calls the drop handler, which decides whether to retry once, and reports the item as dropped otherwise.
Previous: Reactive Streams in Java: Publisher, Subscriber and the Flow API
Next: Reactive Programming vs Virtual Threads in Java: How to Choose

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.