Backpressure Explained
Learn what backpressure is in streams and async code, how a fast producer overwhelms a slow consumer, and how Node.js and Web Streams signal it.

A producer that makes data faster than a consumer can use it has to put the extra somewhere, and the somewhere is memory. A script that reads a 10 GB file as fast as the disk allows and writes it to a slow network connection will buffer most of the file in RAM, and then the process runs out of memory. Backpressure is the mechanism that prevents this: a signal that travels from the slow consumer back to the fast producer and says "wait". Every stream implementation has one, and most memory problems in stream code come from code that ignores it. This post explains the idea with a failing example, shows how Node.js streams signal backpressure through the return value of write() and the drain event, how Web Streams signal it through queue sizes and promises, how pipeline does all this for you, and how to spot missing backpressure in your own code. The measurements use counts, not timings.
The problem, without streams
Start with the plainest version. A loop produces items and pushes them into a queue that a slow consumer drains.
const queue = [];
function produce(n) {
for (let i = 0; i < n; i++) queue.push(`item ${i}`);
}
async function consume() {
while (queue.length > 0) {
queue.shift();
await new Promise((resolve) => setTimeout(resolve, 1));
}
}
produce(5000);
console.log("queued before consuming:", queue.length);
await consume();
console.log("queued after consuming:", queue.length);queued before consuming: 5000
queued after consuming: 0The producer finished in no time, and 5,000 items sat in memory while the consumer worked through them at one per millisecond. With 5,000 small strings, this is harmless. With a million large buffers, it is the out-of-memory crash. The queue is unbounded, and nothing tells the producer to slow down.
Backpressure as a rule
The fix is a limit and a signal. The queue gets a maximum size, called the high-water mark. When the queue reaches it, the producer is told to pause. When the consumer drains the queue below the mark, the producer is told to resume. Every stream API is a version of this.
async function producerWithLimit(items, push, limit) {
for (const item of items) {
while (push.size() >= limit) {
await new Promise((resolve) => setTimeout(resolve, 1));
}
push.add(item);
}
}That polling loop is crude, and real stream implementations use events or promises instead, but the logic is the same: check the room, wait if there is none.
Node.js streams: write() and drain
A Writable has an internal buffer and a highWaterMark, 16 KiB by default for byte streams and 16 objects in object mode. write(chunk) returns true while the buffered amount is under the mark and false once it is at or over. A false means "stop writing until drain is emitted".
import { Writable } from "node:stream";
import { once } from "node:events";
const slowSink = new Writable({
highWaterMark: 8,
write(chunk, encoding, callback) {
setTimeout(callback, 5);
},
});
let pausedCount = 0;
for (let i = 0; i < 6; i++) {
const ok = slowSink.write("1234"); // 4 bytes each
if (!ok) {
pausedCount += 1;
await once(slowSink, "drain");
}
}
slowSink.end();
console.log("paused", pausedCount, "times");paused 3 timesEach write adds 4 bytes. The buffer reaches the mark of 8 bytes on every second write, so write returns false there, and the code waits for drain before sending more. In this run it paused after the second, fourth and sixth write. The wait is what keeps the buffer bounded: at no point does it hold more than the mark plus one chunk. If you ignore the return value, write still accepts everything, and the buffer grows without bound, which is a memory leak with no error.
Readable streams and pausing
On the reading side, a Readable stops pulling from its source when its own buffer is full, and pipe plus pipeline connect the two: when the destination returns false, the source is paused, and on drain it resumes. That is the entire reason pipe() exists.
import { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
let produced = 0;
const source = new Readable({
highWaterMark: 2,
objectMode: true,
read() {
produced += 1;
this.push(produced <= 10 ? produced : null);
},
});
const sink = new Writable({
objectMode: true,
highWaterMark: 2,
write(chunk, encoding, callback) {
setTimeout(callback, 5);
},
});
const timer = setTimeout(() => {
console.log("produced after 12 ms:", produced < 10);
}, 12);
await pipeline(source, sink);
clearTimeout(timer);
console.log("all produced:", produced);produced after 12 ms: true
all produced: 11After 12 ms, the slow sink had consumed only a couple of items, and the source had produced fewer than all ten, because it was paused by backpressure. The final count of 11 includes the call to read that pushed null to end the stream. A producer without backpressure would have finished all ten within the first millisecond.
Web Streams: queue size and promises
Web Streams express the same thing through a queuing strategy. A readable's controller.desiredSize says how many more chunks it wants, and the stream calls pull only when desiredSize is positive. A writable's writer.ready promise resolves when there is room, and write() returns a promise that settles when the sink has taken the chunk.
const sink = new WritableStream(
{
async write() {
await new Promise((resolve) => setTimeout(resolve, 5));
},
},
{ highWaterMark: 2 },
);
const writer = sink.getWriter();
console.log("desiredSize at start:", writer.desiredSize);
writer.write("a");
console.log("after one write:", writer.desiredSize);
writer.write("b");
console.log("after two writes:", writer.desiredSize);
writer.write("c");
console.log("after three writes:", writer.desiredSize);
await writer.ready;
console.log("ready resolved, desiredSize:", writer.desiredSize > 0);
await writer.close();desiredSize at start: 2
after one write: 1
after two writes: 0
after three writes: -1
ready resolved, desiredSize: trueA chunk counts against the queue until the sink finishes writing it, so three quick writes push desiredSize below zero. A well-behaved producer stops at zero and awaits writer.ready, which resolves once the sink has caught up and there is room again. The pattern is therefore: check desiredSize, await writer.ready if there is no room, then write. Piping with pipeTo does all of this automatically.
Where backpressure goes missing
Event listeners that write. readable.on("data", (chunk) => writable.write(chunk)) ignores the return value of write, so a fast source overruns a slow sink. Use pipeline.
Promise-based loops that start everything. A loop that calls an async function for each of a million items without awaiting creates a million pending promises at once. Await inside the loop, or use a limiter, so only a bounded number are in flight.
async function processAll(items, worker, limit) {
const inFlight = new Set();
for (const item of items) {
const task = worker(item).finally(() => inFlight.delete(task));
inFlight.add(task);
if (inFlight.size >= limit) await Promise.race(inFlight);
}
await Promise.all(inFlight);
}
const seen = [];
await processAll([1, 2, 3, 4, 5, 6], async (n) => seen.push(n), 2);
console.log(seen);[ 1, 2, 3, 4, 5, 6 ]The set never holds more than limit tasks, so a million items do not mean a million promises. The Promise.race waits until one finishes before starting the next, which is backpressure for a loop.
Message queues and sockets. A WebSocket's send() queues data in the browser's buffer, and bufferedAmount tells you how much is waiting. Code that sends in a tight loop without checking it grows the buffer.
Unbounded in-memory queues. An array or a Map that grows when producers are faster than consumers is a hand-written version of the same bug.
How to check your own code
Log the buffer sizes. For Node.js streams, writable.writableLength shows the buffered bytes, and writable.writableNeedDrain says whether the writer should wait. For Web Streams, desiredSize is the signal. In a running service, watch the process's resident memory while a slow consumer is attached: steady growth during a long transfer means something is buffering. Then try the slow consumer deliberately, for example by piping a large file to a destination you throttle, and see whether memory stays flat. Flat memory is what correct backpressure looks like.
Backpressure across a whole system
The same principle applies beyond a single process. A web server that accepts requests faster than its database can answer builds a queue of waiting requests, and the queue shows up as rising latency and then timeouts. The equivalent of write() returning false is a server that returns an HTTP 503 or 429 when its queue is full, and the equivalent of drain is a client that backs off and retries later. Load shedding, bounded queues and rate limits are all backpressure at a different scale.
The design lesson is the same at every scale. Every queue needs a limit, every limit needs a defined behavior when it is reached, and the choices are few: block the producer, drop the newest item, drop the oldest item or fail with an error. Write down which one your system uses at each boundary. A queue without a decision about what happens when it is full has made a decision anyway, and it is usually "run out of memory".


