Skip to content

Lesson 5 of 9 · 27m

Streams and Backpressure Under the Hood

Trace readable, writable, transform, object-mode, highWaterMark, corking, and pipeline behavior so flow control becomes a design tool instead of a mystery.

Streams are one of Node's best ideas and one of its most abused APIs. Teams use them because copying large payloads is expensive, then accidentally turn them back into in-memory arrays by ignoring backpressure. The point of a stream is not merely chunking. It is flow control: the consumer can tell the producer to slow down before memory becomes the overflow buffer.

The core contract

A readable produces chunks. A writable accepts chunks and returns whether it can accept more immediately:

if (!writable.write(chunk)) await once(writable, 'drain');

The boolean return value is not a courtesy. false means internal buffering reached the configured watermark. If you keep writing, memory grows inside the stream machinery.

highWaterMark is a buffering threshold

The readable watermark bounds buffered input before reads pause; the writable watermark determines when write() returns false. In object mode it counts objects, not bytes. Large values increase memory and burstiness; small values increase wakeups. Tune with production-sized payloads, not unit-test fixtures.

.pipe() and pipeline() are not equivalent

The modern default should be stream/promises pipeline:

import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
await pipeline(createReadStream('/var/log/app.log'), createGzip(), createWriteStream('/tmp/app.log.gz'));

pipeline propagates errors, destroys participants, and waits for completion. Manual .pipe() chains historically leaked sockets and file descriptors because errors in one branch did not clean up the rest.

Transform streams are where state hides

A transform receives input chunks and produces output chunks. Compression, encryption, parsing, batching, and framing are common examples:

class LineSplit extends Transform {
  constructor() { super(); this.tail = ''; }
  _transform(chunk, encoding, callback) {
    const lines = (this.tail + chunk.toString()).split('\n');
    this.tail = lines.pop();
    lines.forEach(line => this.push(line + '\n'));
    callback();
  }
}

The callback is flow control. Calling it means the transform is ready for more input. Holding it indefinitely stalls upstream; calling it before flushing pushed output can overproduce downstream.

Backpressure is an architectural boundary

Flow control can cross process and service boundaries. TCP receive windows, HTTP/2 flow control, database cursors, and message queue prefetch settings all interact with Node streams. A missing slow-consumer signal in any one layer moves buffering elsewhere. Memory tells you where the pain landed, not necessarily where the design failed.

Field notes

  • Never ignore a false return from .write() in high-throughput code.
  • readable.on('data') switches the stream into flowing mode; attaching it can change when data starts moving.
  • Object-mode streams can retain arbitrarily large objects even when object counts look small.
  • end() means finish writing; it does not guarantee all data has been flushed until finish or pipeline completion.

Was this lesson helpful?

Sign in to rate