Backpressure and highWaterMark

Advanced · 15 min

How a fast producer is slowed down by a slow consumer in Node streams, what write() returning false means, and why pipeline handles it for you.

Before thisTransform streams and pipeline

Web Dev Journey · 15 min

Backpressure and highWaterMark

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev JourneyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Backpressure is a stream telling its producer to pause because it cannot keep up. Without it, a fast source buffers unlimited data in memory.
  • `writable.write(chunk)` returns `false` once the internal buffer reaches `highWaterMark`. That is a request to stop writing, not an error: the chunk was still accepted.
  • After a `false`, wait for the `drain` event before writing more. `await once(writable, 'drain')` does that.
  • `highWaterMark` is a threshold, not a hard limit: in byte mode it defaults to 65,536 in current Node (16,384 before Node 22), and in object mode to 16 objects.
  • `pipe`, `pipeline` and `for await` obey the protocol for you. You only handle `write()` and `drain` yourself when you call `write` in a loop.

Two speeds, one buffer

Say you copy a file from a fast SSD to a slow network share. Reading is quick, writing is slow. If the code reads as fast as it can and hands every chunk to the writer, the unsent chunks have to live somewhere, and that somewhere is process memory. Read a 20 GB file this way and the process holds most of it.

Backpressure is the fix: the slow side signals “stop sending until I catch up”. It is the same idea as a checkout line with a rope barrier. People are held back until the cashier has room, rather than the shop filling with a crowd.

The protocol: write() and drain

Every Writable has an internal buffer and a highWaterMark. write(chunk) always accepts the chunk, but returns a boolean:

  • true: the buffer is below highWaterMark; keep going.
  • false: the buffer is at or above it; stop and wait.

When the buffer has emptied, the stream emits drain. Run this to see it with a deliberately slow destination:

import { Writable } from 'node:stream';
import { once } from 'node:events';

const slow = new Writable({
  highWaterMark: 4,
  write(chunk, enc, cb) { setTimeout(cb, 10); }, // 10 ms per chunk
});

for (let i = 0; i < 5; i++) {
  const ok = slow.write('ab');
  console.log('write', i, 'returned', ok, 'buffered', slow.writableLength);
  if (!ok) await once(slow, 'drain');
}
slow.end();

Output:

write 0 returned true buffered 2
write 1 returned false buffered 4
write 2 returned true buffered 2
write 3 returned false buffered 4
write 4 returned true buffered 2

Two bytes fits under the threshold of 4. The second write reaches it, so write returns false and the loop waits for drain. The same pattern as a reusable helper:

async function writeAll(dest, rows) {
  for (const row of rows) {
    if (!dest.write(row)) await once(dest, 'drain');
  }
  dest.end();
}

highWaterMark is a threshold

It is not a cap. A single write() of 10 MB into a stream with highWaterMark: 4 is still accepted. The number controls when the stream asks for a pause, so it trades memory against how often the producer stops and starts. In byte mode the default is 65,536 in current Node (16,384 before Node 22). File read streams were already 64 KiB. In object mode it counts objects, defaulting to 16. You can read writable.writableHighWaterMark to check the value in your version.

Raising it reduces stop-and-go for fast destinations. Lowering it lowers peak memory per stream, which matters when you serve thousands of connections at once.

Who handles it for you

readable.pipe(writable), pipeline(), and for await over a Readable all follow the same protocol internally. In pipeline, when a destination’s write returns false, the source is paused; on drain it resumes. This is the main reason to prefer them over a hand-written on('data', chunk => dest.write(chunk)), which ignores backpressure by default:

// Leaks memory when dest is slower than src
src.on('data', (chunk) => dest.write(chunk));

// Correct, and also forwards errors
await pipeline(src, dest);

You handle drain yourself only in code that generates data and calls write in a loop, as above, for example when writing a large export row by row from a database cursor.

What the video covers

Web Dev Journey’s video is titled “Writable Streams & Backpressure” and comes with a public demo repository. It is from January 2021, so the default highWaterMark it quotes may be 16 KiB, as in Node 14; the 64 KiB figure here is current as of Node 22 onwards. I could not read a transcript, so the exact examples are not described here. The code above was run on Node 26.

Where this fits

Backpressure is why pipeline is safe on big data, and it applies the same way to HTTP responses, which are Writable streams. The web-standard version of the same mechanism comes next in web streams.

Check yourself

  1. 01A loop writes a million rows to `res` with `res.write(row)` and ignores the return value. The client is on a slow connection. What happens to memory?

    Each `write` is accepted even after the buffer is over `highWaterMark`, so the unsent rows pile up in the response's internal buffer. Memory grows with the backlog until the process is slow or out of memory. Checking for `false` and awaiting `drain`, or using `pipeline`, keeps it bounded.

  2. 02`write()` returned `false`. Was the chunk lost?

    No. The chunk is queued and will be written. `false` only signals that the buffer is at or above `highWaterMark` and the producer should pause until `drain` fires.

  3. 03What does `highWaterMark: 4` mean for a Writable in byte mode?

    The stream reports `false` from `write()` once 4 or more bytes are buffered and waiting for the underlying write to finish. Writing 2 bytes twice with a destination that completes slowly gives `true`, then `false`, and the next `drain` fires when the buffer empties.

  4. 04Why do you not need to handle `drain` when you use `pipeline`?

    `pipeline` reads from the source only as fast as the next stage accepts data. When a destination's `write()` returns `false`, the pipe pauses the source and resumes it on `drain`, so the buffers between stages stay near `highWaterMark`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark