How to Implement Backpressure in Node.js Streams
Keep a fast producer from exhausting memory by respecting write() return values, using pipeline() and pausing sources when read buffers fill.
On this page
Introduction
Node.js streams move data through a chain of producers and consumers, and the two ends rarely run at the same speed. When a disk read is faster than a network write, or a database cursor is faster than a JSON serializer, data accumulates in memory between them. Without a mechanism to slow the fast side, a busy process can balloon to gigabytes and be killed by the operating system. That mechanism is backpressure: the consumer signals that it is full, the producer pauses, and the flow resumes when there is room. This article explains how Node’s streams signal backpressure, how to respect those signals, and the mistakes that quietly discard them.
The Buffering Problem
Readable and writable streams each keep an internal buffer. A readable stream buffers data that has been read from the source but not yet consumed; a writable stream buffers data handed to write() that has not yet been flushed to the destination. If the consumer is slower than the producer and nothing pauses the producer, the writable buffer grows without bound. In a memory-constrained container that growth ends in an out-of-memory kill, which looks like a random crash rather than a throughput problem.
Backpressure is not an error path; it is the normal way a healthy pipeline regulates itself. The goal is not to never buffer but to keep buffers small and bounded, so the slowest stage sets the pace instead of memory.
write() Returns a Backpressure Signal
The primary backpressure signal in Node is the boolean returned by writable.write(chunk). It returns true when the internal buffer is below the highWaterMark and false when the buffer has exceeded it. A false return does not mean the write failed; it means you should stop writing until the stream emits the drain event. Ignoring the return value, the classic mistake, is what lets the buffer grow without limit.
const { createWriteStream } = require('node:fs');
const out = createWriteStream('output.ndjson');
async function writeAll(rows) {
for (const row of rows) {
const ok = out.write(JSON.stringify(row) + '\n');
if (!ok) {
// Buffer is full: wait for the drain event before producing more.
await new Promise((resolve) => out.once('drain', resolve));
}
}
await new Promise((resolve, reject) => {
out.end((err) => (err ? reject(err) : resolve()));
});
}
Using pipeline() and Async Iteration
For a producer that is itself a Readable stream, the simplest correct approach is the pipeline helper, which connects streams, propagates errors, and manages backpressure automatically. A readable source like fs.createReadStream will not push faster than the destination’s capacity when flowing through pipeline, because the pipe respects the drain events for you. Prefer pipeline over manual pipe chains because it also forwards errors and destroys all streams on failure.
const { pipeline } = require('node:stream/promises');
const { createReadStream, createWriteStream } = require('node:fs');
const { Transform } = require('node:stream');
const upper = new Transform({
transform(chunk, _enc, cb) {
cb(null, chunk.toString().toUpperCase());
},
});
async function run() {
await pipeline(
createReadStream('input.txt'),
upper,
createWriteStream('output.txt'),
);
console.log('pipeline finished');
}
run().catch((err) => console.error('pipeline failed:', err.message));
Reading and Writing with Async Iterators
Readable streams implement the async iterable protocol, which gives a natural for await loop that respects backpressure when you await inside the body. Writing in the loop with write() and awaiting drain when it returns false keeps the buffer bounded. This pattern is clearer than event handlers for sequential transforms, and it makes error handling a normal try/catch.
const { createReadStream, createWriteStream } = require('node:fs');
const readline = require('node:readline');
async function processLines(input, output) {
const rl = readline.createInterface({ input: createReadStream(input) });
const out = createWriteStream(output);
for await (const line of rl) {
const record = { raw: line.trim(), length: line.trim().length };
if (!out.write(JSON.stringify(record) + '\n')) {
await new Promise((resolve) => out.once('drain', resolve));
}
}
out.end();
}
Measuring Buffer Levels
You can observe backpressure through stream.writableLength and stream.readableLength, which report how many bytes are currently buffered. Watching writableLength during a run tells you whether the pipeline is keeping up: a value that climbs steadily toward and past the highWaterMark indicates the producer is outrunning the consumer. Treat these as gauges, not as something to poll in a hot loop; emit them periodically alongside throughput and error counters.
When a pipeline is persistently backpressured, the fix is usually downstream capacity, not a bigger buffer. Raising highWaterMark just delays the problem and increases peak memory. Profile the slow stage: is it synchronous work on the event loop, a slow disk, or a remote call with a fixed latency? Addressing that stage restores flow.
Common Mistakes
The most frequent bug is ignoring the write() return value, or only checking it inside a branch that never awaits drain. The second is doing synchronous CPU work inside a transform callback, which blocks the event loop and defeats backpressure because the pipeline cannot process drain events while the loop is busy. The third is using pipe() without an error handler on every stream; an error on a source in a manual pipe chain is not automatically propagated, and the destination may hang forever.
Another subtle trap is mixing callback style and promise style: ending a stream inside a callback while an outer promise also tries to end it causes a write-after-end error. Pick one style per pipeline, and use pipeline() or finished() so completion and errors are reported in one place. Finally, remember that backpressure only works if the fast side actually listens; if a producer pushes into an array that a consumer later reads, no stream signal can help, and you have a queue with unbounded growth instead of a stream.
Conclusion
Backpressure keeps a streaming pipeline within a bounded memory budget by making the slowest stage set the pace. Respect the boolean returned by write(), await drain when it is false, and prefer pipeline() or async iteration so the plumbing is handled for you. Watch writableLength to confirm the buffer stays bounded, and treat a persistently full buffer as a signal to speed up the consumer rather than to enlarge the buffer. Avoid synchronous work in transforms and unhandled errors in pipe chains, and backpressure becomes the quiet mechanism that prevents a stream from becoming an out-of-memory crash.
Sources: Node.js: Backpressuring in Streams, Node.js: stream API, Node.js: pipeline().
FAQ
- What does write() returning false actually mean?
- It means the writable buffer has exceeded its highWaterMark. The write was accepted, not lost; you should pause producing and resume when the stream emits drain. Continuing to write ignores the signal and lets memory grow without bound.
- Should I just raise highWaterMark instead of handling backpressure?
- Raising it only delays the overflow and increases peak memory. Persistent backpressure means the consumer is too slow, so fix that stage. Keep highWaterMark modest and let the slowest stage set the pace.
Report a problem with this articleOpens a pre-filled issue on GitHub.