Skip to content

Lesson 5 of 9 · 25m

Streams Internals: Backpressure, Pipelines, and Memory

Why streams exist, how flowing and paused modes really interact, and how to build pipelines that do not silently buffer a multi-gigabyte mistake.

Streams are not a performance garnish. They are the difference between a service that can process a 20 GB upload and a service that crashes trying to hold it in memory. The failure mode is usually quiet: throughput degrades, RSS grows, the kernel and Node buffers fill, and eventually the process gets OOM-killed. “But we used streams” is not a defense if you destroyed backpressure.

The core contract is demand, not data

A readable stream produces chunks. A writable stream accepts chunks and answers a crucial question through the return value of write():

const canContinue = writable.write(chunk);
if (!canContinue) {
  await once(writable, "drain");
}

write() returning false does not mean failure. It means the internal buffer reached highWaterMark and the producer should stop. Ignoring that signal is unbounded buffering with extra steps.

highWaterMark is not a hard maximum. It is a signaling threshold. That misunderstanding causes many memory bugs because teams expect the stream to enforce a limit it never promised to enforce.

Use pipeline, not handcrafted chaining

import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";

await pipeline(
  createReadStream("exports/ledger.ndjson"),
  createGzip({ level: 6 }),
  createWriteStream("exports/ledger.ndjson.gz"),
);

pipeline propagates errors, destroys the chain, and applies backpressure correctly. Manual .pipe() chains are easy to leak: one middle stream errors, the others remain open, file descriptors accumulate, and cleanup depends on luck.

In modern code, use stream/promises. Callback-era stream composition APIs are correct only in the hands of someone who has already memorized their edge cases.

Object-mode streams are concurrency traps

Object streams count objects rather than bytes:

new Transform({
  objectMode: true,
  transform(row, encoding, callback) {
    callback(null, normalize(row));
  },
});

A highWaterMark of 16 means 16 objects, and each object can be huge. When batching database rows, control both object count and byte size. “We only had ten objects in memory” can still mean a gigabyte if those objects are file payloads or parsed documents.

Async iteration hides flow control if you let it

for await (const chunk of readable) {
  await processChunk(chunk);
}

Async iteration does respect backpressure, but only because the loop awaits consumption. If inside the loop you spawn unbounded promises and keep reading, you have recreated the buffer in userland:

// dangerous: reads everything as fast as possible
for await (const record of input) {
  jobs.push(processRecord(record));
}

Use a concurrency-limited worker pool, count in-flight jobs, and await capacity before pulling the next item.

Fetch, undici, and modern web-aligned APIs use web streams. Node core streams predate them. Conversion exists — Readable.toWeb, Readable.fromWeb — but every conversion layer is a place to lose error propagation or add buffering. Pick the stream model demanded by the API boundary and convert deliberately once.

Field notes

  • Always inspect whether an API returns a stream, a promise for a buffer, or a lazy iterator. They have completely different memory behavior.
  • readable.destroy(error) is how you fail a stream; throwing inside callbacks without cleanup often leaks resources.
  • Log bytes processed and in-flight work for large jobs. Throughput alone hides queue growth.
  • Backpressure must cross process boundaries too. If a TCP peer cannot consume, your process is the buffer unless you stop reading upstream.
  • Test streams with slow consumers and failing middle transforms, not just happy-path local files.

Was this lesson helpful?

Sign in to rate