How-To Guide

How to Implement Backpressure in Producers

Apply backpressure in producers: watch the consumer's signal, slow or drop when it is over capacity, and keep memory bounded under load.

On this page

  1. Introduction
  2. Observe the consumer’s signal
  3. Slow down or drop, deliberately
  4. Bound every buffer
  5. Propagate backpressure across services
  6. Test under overload
  7. Common pitfalls
  8. Conclusion

Introduction

A producer that generates work faster than the consumer can process it has three options: slow down, buffer, or drop. Doing none of them, which is the default in naive code, means the buffer between them grows without bound until memory is exhausted and the process crashes. Backpressure is the discipline of noticing that the consumer is over capacity and choosing one of the three, so the system degrades in a controlled way instead of failing outright.

This tutorial implements backpressure for producers that write to a stream, push to a queue, or send to a downstream service. It covers observing the consumer’s signal, choosing a slow-or-drop policy, bounding every buffer, and testing under overload. The examples span Node.js streams, a bounded queue, and a service client.

Observe the consumer’s signal

Backpressure works only if the producer can see that the consumer is behind. Streams expose this: a write that returns false means the internal buffer is full and the producer should wait for a drain event. A bounded queue exposes it by blocking or rejecting when full. A service client exposes it through queue depth or a rate limit response. Find the signal and respect it.

The common mistake is to ignore the signal and buffer anyway. A Node.js write that returns false but is followed by more writes grows the stream’s internal buffer without limit. The fix is to pause the producer until the drain event, which is the stream’s contract. Every API that offers a backpressure signal expects the producer to honor it, and ignoring it is what turns a fast producer into a memory leak.

import { createReadStream, createWriteStream } from 'node:fs';

const source = createReadStream('big.bin');
const sink = createWriteStream('copy.bin');

source.on('data', (chunk) => {
  if (!sink.write(chunk)) {
    source.pause();               // consumer full: stop producing
    sink.once('drain', () => source.resume()); // resume when it can take more
  }
});
source.on('end', () => sink.end());

Slow down or drop, deliberately

When the consumer is over capacity, choose between slowing the producer and shedding work. If every item must be processed, slow the producer and let a bounded buffer absorb a temporary burst; the producer waits for capacity rather than adding load. If some items are expendable, drop the oldest, the newest, or the least important when the buffer is full, and count the drops.

The choice depends on the domain. A log pipeline can drop low-severity lines under pressure and keep errors; a payment queue must not drop, so it slows the producer or refuses new work with a retryable error. Make the choice explicit in the code and in a metric, so the behavior under overload is a decision rather than an accident.

import asyncio

async def producer(queue: asyncio.Queue, source):
    async for item in source:
        try:
            await asyncio.wait_for(queue.put(item), timeout=1.0)  # bounded wait
        except asyncio.TimeoutError:
            metrics.incr('producer.dropped')                       # explicit drop
            continue                                                # or block, per policy

Bound every buffer

An unbounded queue is not a buffer; it is a promise to use all available memory when the consumer is slower than the producer. Give every queue, every stream buffer, and every in-memory list a maximum size. When the maximum is reached, the producer must slow, drop, or fail, according to the policy. A bound turns an out-of-memory crash into a controlled rejection or a measured slowdown.

Choose the bound from the burst you need to absorb and the memory you can afford. A short burst needs a small buffer; a long outage of the consumer needs either a durable queue outside the process or a policy to reject. For cross-process work, do not buffer a long outage in memory at all: publish to a durable queue with its own bound, so the process does not hold the backlog in the heap.

Propagate backpressure across services

In a chain of services, backpressure must propagate outward. If service B is slow, service A should slow, and if A cannot, it should reject its callers rather than buffering unboundedly. A timeout on the call turns an unresponsive downstream into a fast failure the caller can handle, and a rate limit or a 503 with Retry-After tells the caller to slow down.

Use bounded concurrency rather than unbounded fan-out. Limiting how many in-flight calls A makes to B means A cannot overwhelm B even if A receives a burst. Combine the concurrency limit with a timeout and a retry with backoff, so A applies pressure that B can shed and recovers when B is healthy, rather than queueing an ever-growing backlog.

// bounded concurrency: at most N in-flight calls to the downstream
async function mapLimited<T, R>(items: T[], limit: number, fn: (t: T) => Promise<R>): Promise<R[]> {
  const results: R[] = [];
  let i = 0;
  const workers = Array.from({ length: limit }, async () => {
    while (i < items.length) {
      const idx = i++;
      results[idx] = await fn(items[idx]);
    }
  });
  await Promise.all(workers);
  return results;
}

Test under overload

Drive a producer much faster than the consumer and assert the chosen behavior: memory stays bounded, the buffer never exceeds its maximum, and drops are counted or the producer slows. Assert that a stream producer pauses when the consumer returns a full signal and resumes on drain. Assert that a bounded queue rejects or blocks at its limit rather than growing. Assert that a downstream outage produces fast failures, not a growing backlog.

# producer faster than consumer: memory must stay bounded, drops counted
node -e '
const { Producer, Consumer } = require("./pipeline");
Producer.push(1e6, { fasterThan: Consumer });   // assert heapUsed < budget, drops > 0
'

Common pitfalls

Ignoring the write-returns-false signal and buffering anyway, an unbounded queue that promises to use all memory, no policy for a full buffer, unbounded fan-out to a downstream, and buffering a long consumer outage in memory instead of a durable queue are the recurring mistakes. Respecting the signal, bounding every buffer, an explicit slow-or-drop policy, bounded concurrency, and a durable queue address them.

Conclusion

Backpressure is noticing that a consumer is over capacity and choosing to slow, buffer a bounded amount, or drop. Observe the consumer’s signal, decide the policy explicitly, bound every buffer, propagate pressure across services with concurrency limits and timeouts, and test under overload. Self-check by driving a producer faster than its consumer and asserting bounded memory and a visible drop count. Then a slow consumer slows the system instead of crashing it.

Sources: Node.js: Backpressuring in streams, Reactive Streams: Backpressure, Python: asyncio Queues.

FAQ

What is backpressure?
It is the signal a consumer gives when it cannot keep up, so the producer slows down or drops work instead of piling it up. Without it, the producer keeps producing into a buffer that grows until memory is exhausted, turning a slow consumer into a crash.
Slow down or drop?
If the work must all be done, slow the producer and let the buffer absorb a bounded burst. If some work is expendable, drop the oldest or the least important when the buffer is full. Either way, choose the policy explicitly; the failure mode of doing neither is an unbounded queue.

Related Examples