Yousef AldabbasSystems & backend engineering
● ENGINEERING NOTESAMMAN, JORDAN
← back to posts

Node.js Internals #3: Streams and Backpressure

2026-11-09 · nodejs

Part 3 of the Node.js Internals series. Part 1: event loop. Part 2: libuv and the thread pool. Every output below was run on Node v26.8.1.

A stream is a way to process data in pieces instead of all at once. The reason it matters in practice is memory: a stream keeps a small, bounded buffer, while the "read it all, then process it" version keeps the whole thing in RAM.

Streams vs reading everything

I created an 800 MB file and read it two ways, measuring the process's memory (RSS):

fs.readFile(big, ...)                 // peak RSS 670 MB
fs.createReadStream(big).on("data")   // peak RSS 118 MB, same 800,000,000 bytes processed

Same bytes, one sixth of the memory. The stream hands you 64 KiB chunks as they arrive (the default for file streams) and forgets them after your handler runs.

The four kinds

type Readable  = { on(e: "data", cb: (chunk: Buffer) => void): void }   // fs.createReadStream, http request body
type Writable  = { write(chunk: Buffer): boolean; end(): void }          // fs.createWriteStream, http response
type Duplex    = Readable & Writable                                     // a TCP socket
type Transform = Duplex  // output computed from input: zlib.createGzip(), a parser

Backpressure: what write() returning false means

Streams have a buffer limit called the highWaterMark (16 KiB for a plain Writable, in bytes). When the buffer holds more than that, write() returns false. It is a request: "stop sending until I say so". When the buffer empties, the stream emits drain.

const slow = new Writable({
  highWaterMark: 16 * 1024,
  write(chunk, enc, cb) { setTimeout(cb, 10); },   // consumer takes 10 ms per chunk
});
for (let i = 1; i <= 5; i++) {
  const ok = slow.write(Buffer.alloc(8 * 1024));
  console.log(`write #${i} -> ${ok}   buffered=${slow.writableLength}`);
}
highWaterMark: 16384 bytes
write #1 -> true   buffered=8192
write #2 -> false   buffered=16384
write #3 -> false   buffered=24576
write #4 -> false   buffered=32768
write #5 -> false   buffered=40960
drain fired, buffered = 0

Note the important part: false is advice, not enforcement. Writes #3 to #5 were still accepted and buffered. A producer that ignores the signal will happily fill memory.

What ignoring it costs

Write 8,000 chunks of 64 KiB (about 520 MB) into a sink that is slower than the producer, once ignoring the return value and once pausing until drain:

// ignore the return value
for (let i = 0; i < N; i++) sink.write(makeChunk());          // peak RSS 591 MB

// respect it
(function pump() {
  while (i < N) {
    i++;
    if (!sink.write(makeChunk())) { sink.once("drain", pump); return; }
  }
})();                                                          // peak RSS 104 MB

591 MB versus 104 MB for the same data. The "ignore" version buffered nearly everything before the sink got through it. (An early version of my test reused one chunk object and showed no difference at all, because the buffer then holds references to the same memory. Backpressure bugs only hurt when each chunk is distinct, which is what real data is.)

Let pipeline do it for you

You rarely write that pump loop. pipe and stream.pipeline implement it. Prefer pipeline, because it also handles errors and cleanup, which plain .pipe() does not:

const { pipeline } = require("stream/promises");

// source emits a b c d; the Transform throws on "c"
try { await pipeline(src, upper, sink); }
catch (e) { console.log("pipeline rejected:", e.message); }
sink closed
source closed
pipeline rejected: boom at c
received: [ 'A', 'B' ]

The error in the middle stage destroyed both the source and the sink, so no file handle or socket is left dangling, and you get a single rejection to catch. With a.pipe(b).pipe(c), an error in one stream leaves the others open.

Streams and the event loop

A file read stream is driven by the thread pool from Part 2: each chunk is a pool task. Chunks surface in the loop's I/O phase, and a Transform's callbacks run as ordinary JavaScript on the loop thread, so a slow Transform blocks the loop like any other synchronous code. Streams give you bounded memory, not free CPU.

Cheatsheet

SituationDo
File larger than a few MBcreateReadStream, not readFile
Connecting streamspipeline from stream/promises, not .pipe()
Writing in a loop by handIf write() is false, stop and wait for drain
Tuning chunk sizehighWaterMark (bytes, or object count in object mode)
Slow stage in the middleIt sets the speed of the whole chain; backpressure propagates upstream

Conclusion

A stream is a buffer with a limit and a polite way of saying "slow down". The memory numbers above are the whole argument for using them: 118 MB versus 670 MB for reading, and 104 MB versus 591 MB for writing, on identical data.

References

Node.js Internals: Part 1 · Part 2 · Part 3 · Part 4 · Part 5