StackPractices
advanced By Mathias Paulenko

Reactive Streams Pattern

Process asynchronous data streams with backpressure. Subscribers request N items at a time, preventing fast producers from overwhelming slow consumers.

Overview

In a push-based streaming model, the producer fires data as fast as it can. If the consumer can’t keep up, items pile up in a buffer until memory runs out. Reactive Streams flips the direction: the subscriber asks for a specific number of items and the publisher sends only that many. That demand signal is backpressure — the publisher can’t push more than was requested, so memory stays bounded and the consumer sets the pace.

It’s the same problem the producer-consumer pattern solves with a bounded queue; Reactive Streams turns it into a standardized protocol that works across threads, libraries, and languages.

When to Use

  • A fast producer streams data to a slower consumer and you need flow control
  • You process large or unbounded data streams within a fixed memory budget
  • You need to compose stream operations (map, filter, merge) under backpressure
  • You want a protocol different reactive libraries can interoperate through

When NOT to Use

  • A handful of items or a one-shot async call — async/await is simpler
  • When every item must be indexed or searchable immediately — pull-based demand can delay delivery
  • If the producer can’t be paused (a hardware sensor that emits regardless), you’ll need buffering or sampling anyway; the protocol alone doesn’t stop the source

Solution

Python (asyncio + manual backpressure)

import asyncio

class Publisher:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def request(self, n):
        """Subscriber requests n items. Returns up to n items."""
        items = []
        for _ in range(n):
            if self.index >= len(self.data):
                break
            items.append(self.data[self.index])
            self.index += 1
        return items

class Subscriber:
    def __init__(self, publisher, batch_size=5):
        self.publisher = publisher
        self.batch_size = batch_size
        self.processed = 0

    async def consume(self):
        while True:
            # Request only batch_size items: that's the backpressure signal
            items = self.publisher.request(self.batch_size)
            if not items:
                break
            for item in items:
                await self.process(item)
                self.processed += 1
        print(f"Total processed: {self.processed}")

    async def process(self, item):
        await asyncio.sleep(0.01)  # Simulate slow processing
        print(f"Processed: {item}")

async def main():
    data = list(range(100))
    publisher = Publisher(data)
    subscriber = Subscriber(publisher, batch_size=5)
    await subscriber.consume()

asyncio.run(main())

JavaScript (ReadableStream + backpressure)

// A readable stream whose producer respects the internal queue size
function createNumberStream(max) {
  let current = 0;
  return new ReadableStream({
    start(controller) {
      function push() {
        if (current >= max) {
          controller.close();
          return;
        }
        // desiredSize reflects how much room the consumer's queue has.
        // Once it hits zero, stop pushing until read() drains the queue.
        if (controller.desiredSize > 0) {
          controller.enqueue(current++);
          push();
        }
      }
      push();
    },
  });
}

async function consume(stream) {
  const reader = stream.getReader();
  let processed = 0;

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    // Simulate slow processing — the queue fills while we await,
    // desiredSize drops, and the producer pauses on its own.
    await new Promise((r) => setTimeout(r, 10));
    processed++;
    console.log(`Processed: ${value}`);
  }
  console.log(`Total processed: ${processed}`);
}

consume(createNumberStream(100));

Java (Project Reactor, request(n))

This one actually pulls: request(5) up front, then one more per item processed. That is the backpressure signal.

import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

public class ReactiveStreamsExample {

    public static void main(String[] args) throws InterruptedException {
        Flux<Integer> publisher = Flux.range(0, 100);

        publisher
            .publishOn(Schedulers.parallel())
            .subscribe(new BaseSubscriber<Integer>() {
                @Override
                protected void hookOnSubscribe(Subscription s) {
                    request(5); // initial demand: 5 items only
                }

                @Override
                protected void hookOnNext(Integer item) {
                    try {
                        Thread.sleep(10); // simulate slow processing
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    System.out.println("Processed: " + item);
                    request(1); // ask for one more once this item is done
                }

                @Override
                protected void hookOnComplete() {
                    System.out.println("Done");
                }
            });

        Thread.sleep(2000); // give the async pipeline time to finish
        System.out.println("All done");
    }
}

Explanation

The Reactive Streams spec defines four interfaces:

  • Publisher: produces items and sends them to subscribers — never more than requested.
  • Subscriber: consumes items; calls request(n) on its Subscription to signal demand.
  • Subscription: the link between a publisher and a subscriber; carries request(n) and cancel().
  • Processor: a stage that’s both subscriber and publisher, for transformations mid-stream.

One rule carries the whole protocol: a publisher never emits more items than the subscriber asked for. Ask for 5, get at most 5. Process them, ask for 5 more. The flow is pull-based end to end, so the slowest stage dictates the pace instead of the fastest one.

Backpressure is what keeps a quick producer from burying a slow consumer. Rather than letting an unbounded buffer grow until the process dies, the publisher simply waits for demand. Memory stays flat no matter how long the stream runs.

The demand cycle — the subscriber sends request(n) through the subscription, the publisher emits at most n items, and the loop repeats at the consumer's pace.

Variants

VariantImplementationUse CaseTradeoff
Project ReactorJava (Spring)Enterprise, Spring WebFluxSteep learning curve
RxJavaJavaRich operator setLarge API surface
Akka StreamsScala/JavaActor-based streamsAkka dependency
ReadableStreamWeb Streams APIBrowser/Node.jsLimited operators
Manual backpressureasyncio + requestSimple, no frameworkNo composition operators

If a lighter pull-based option fits better, see the Async Generator pattern.

Scenario: reactive streams for event processing

A minimal TypeScript implementation of the four interfaces, batching analytics events before sending them:

// The four Reactive Streams roles, distilled
interface Publisher<T> {
  subscribe(subscriber: Subscriber<T>): void;
}

interface Subscriber<T> {
  onNext(value: T): void;
  onError(err: Error): void;
  onComplete(): void;
}

interface ClickEvent {
  x: number;
  y: number;
  timestamp: number;
}

class EventPublisher<T> implements Publisher<T> {
  private subscribers: Subscriber<T>[] = [];
  private buffer: T[] = [];
  private maxBuffer = 1000;

  subscribe(sub: Subscriber<T>) { this.subscribers.push(sub); }

  emit(value: T) {
    this.buffer.push(value);
    if (this.buffer.length > this.maxBuffer) {
      this.buffer.shift(); // discard oldest rather than grow forever
    }
    this.subscribers.forEach(s => {
      try { s.onNext(value); }
      catch (err) { s.onError(err as Error); }
    });
  }

  complete() {
    this.subscribers.forEach(s => s.onComplete());
    this.subscribers = [];
  }
}

class BatchProcessor<T> implements Subscriber<T> {
  private batch: T[] = [];

  constructor(
    private batchSize: number,
    private processFn: (batch: T[]) => Promise<void>,
  ) {}

  async onNext(value: T) {
    this.batch.push(value);
    if (this.batch.length >= this.batchSize) {
      const batch = this.batch.splice(0, this.batchSize);
      await this.processFn(batch);
    }
  }
  onError(err: Error) { console.error("[REACTIVE] Error:", err); }
  async onComplete() {
    if (this.batch.length > 0) await this.processFn(this.batch);
    console.log("[REACTIVE] Stream complete");
  }
}

// Usage: ship click events to analytics in batches of 100
const publisher = new EventPublisher<ClickEvent>();
const processor = new BatchProcessor<ClickEvent>(100, async (batch) => {
  await fetch("/api/analytics", { method: "POST", body: JSON.stringify(batch) });
});
publisher.subscribe(processor);

for (let i = 0; i < 350; i++) {
  publisher.emit({ x: i, y: i * 2, timestamp: Date.now() });
}
publisher.complete(); // flushes the final batch of 50

Compared with a general-purpose library like RxJS:

AspectReactive StreamsRxJS
StandardReactive Streams specLibrary
BackpressureExplicit (Subscription)Buffer/lossy
OperatorsBasic100+ operators
TypingGenericsNative TypeScript
Use caseEvent-driven systemsUI, transformations

Lessons from the example:

  • Reactive Streams standardizes pub/sub with backpressure on top.
  • The publisher emits, the subscriber consumes, the subscription controls demand.
  • Batching cuts overhead: 100 events per HTTP request instead of 350.
  • In Node.js you’d normally reach for RxJS or most.js rather than hand-rolling this.

What Works

  • Start with a small request size (5–10) and tune from measured throughput.
  • Keep operators like buffer and window on bounded sizes so memory can’t grow unbounded.
  • Always handle onError: an unhandled failure cancels the subscription quietly.
  • Use subscribeOn and publishOn to pick which thread produces and which consumes.
  • Cancel subscriptions when you’re done — it stops the publisher and frees resources.
  • Watch the demand signal: if the subscriber never requests again, the stream stalls.
  • Pick the right overflow strategy: onBackpressureBuffer, onBackpressureDrop, or onBackpressureLatest.

Common Mistakes

  • Requesting unbounded demand: request(Long.MAX_VALUE) switches backpressure off entirely and you’re back to push mode. Only do it when the consumer is provably faster.
  • Blocking inside the subscriber: a blocking call in onNext stalls the publisher thread. Offload work to a scheduler.
  • Skipping onError: exceptions get swallowed and the stream just stops with no signal.
  • Ignoring cancellation: a consumer that finishes without cancelling leaves the publisher producing into the void.
  • Mixing push and pull: calling onNext without a matching request breaks the protocol — some implementations throw on it.
  • Huge request sizes: asking for thousands of items per round weakens backpressure and spikes memory.

Further Reading

Frequently Asked Questions

How is this different from pub/sub?

Pub/sub fans every message out to all subscribers and has no flow control at all. Reactive Streams pairs one subscriber with one subscription and an explicit demand signal. Reach for pub/sub to fan events out; reach for Reactive Streams to actually process a stream. See the publish-subscribe pattern for the broadcast variant.

How is this different from async generators?

Both are pull-based — the consumer asks for the next item. On top of that, Reactive Streams layers a standard protocol, composition operators, and support across threads. Async generators stay simpler; Reactive Streams gives you more machinery when you need it.

What happens when the subscriber is much slower?

It requests fewer items per batch, or one at a time, and the publisher waits. Memory stays bounded. If the lag is unrecoverable, onBackpressureDrop discards items or onBackpressureLatest keeps only the freshest.

Should I use Reactive Streams or plain async/await?

For one producer feeding one consumer with no composition, async/await is less code. Once you need pipelines — map, filter, merge, retry, debounce — the libraries' operators beat hand-rolled loops by a wide margin.

Can I have multiple subscribers?

Yes — every subscriber still gets its own subscription, and demand is tracked separately for each. A publish operator shares a single upstream subscription across subscribers; a multicast operator buffers items for subscribers that join late.

How do I handle backpressure in reactive streams?

You've got five strategies: 1) Buffer — store up to a limit (can still OOM). 2) Drop — discard new events. 3) Latest — keep only the most recent. 4) Throttle — cap the emission rate. 5) Request(n): the subscriber pulls N items at a time — the answer the protocol itself was built around. Which one fits depends on the use case: dropping is fine for analytics, while payments usually need buffering plus persistence.