Streams and backpressure in Node

Streams are how Node handles data that's too big to hold in memory at once: big files, CSV exports, uploads, proxied responses.

Streams are how Node handles data that’s too big to hold in memory at once: big files, CSV exports, uploads, proxied responses. They mostly just work, until the thing you’re writing to is slower than the thing you’re reading from. Then memory climbs, and it climbs in production, where the data is bigger and the clients are slower.

That’s backpressure, and the fix is usually a few lines.

What happens when you ignore it

Here’s a writable stream that takes 10 ms per chunk, like a slow disk or a client on a bad connection, and a loop that writes 10,000 rows into it:

const { Writable } = require('stream');

const slow = new Writable({
  write(chunk, encoding, callback) {
    setTimeout(callback, 10);
  },
});

for (let i = 1; i <= 10_000; i++) {
  const ok = slow.write(`row ${i},${'x'.repeat(100)}\n`);
  if (i === 1 || i === 200 || i === 10_000) {
    console.log(`row ${i}: write() returned ${ok}, buffered ${slow.writableLength} bytes`);
  }
}
row 1: write() returned true, buffered 107 bytes
row 200: write() returned false, buffered 21692 bytes
row 10000: write() returned false, buffered 1098894 bytes

By row 200, write() is already returning false. That’s the stream saying “stop, I’m full”. The loop keeps going anyway, so all 10,000 rows end up in memory. That’s 1 MB here. With a few million rows and a few slow clients at once, it’s enough to take a server down.

The limit is the highWaterMark, which is 16 KiB by default for byte streams and 16 objects in object mode. It isn’t a hard cap. It’s the point where write() starts telling you to wait.

Respecting it by hand

When write() returns false, wait for the drain event before writing more:

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

for (let i = 1; i <= 2_000; i++) {
  const line = `row ${i},${'x'.repeat(100)}\n`;
  if (!slow.write(line)) {
    await once(slow, 'drain');
  }
}
slow.end();

With that one if, the buffer never went above 16,351 bytes, just under the 16,384-byte high water mark. Memory stays flat no matter how many rows there are.

pipe() vs pipeline()

pipe() handles backpressure for you, which is why most stream code works. What it doesn’t handle is errors. If the source fails, the destination isn’t closed. If the destination fails, the source keeps reading. You get leaked file handles and requests that hang forever.

pipeline() from node:stream/promises handles both:

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

await pipeline(
  createReadStream('access.log'),
  createGzip(),
  createWriteStream('access.log.gz'),
);

If any step fails, every stream in the chain is destroyed and the promise rejects with the error. With a missing input file, you get a clean ENOENT in your catch instead of a half-written .gz and an open handle. I don’t use .pipe() in new code anymore.

Generating data with async generators

The nicest change in recent Node versions is how well streams work with async generators. Say you’re exporting users page by page from a database into a CSV response:

import { pipeline } from 'node:stream/promises';

async function* fetchRows() {
  let page = 0;
  while (true) {
    const rows = await db.users.findMany({ skip: page * 1000, take: 1000 });
    if (rows.length === 0) return;
    yield* rows;
    page++;
  }
}

app.get('/export.csv', async (req, res) => {
  res.setHeader('Content-Type', 'text/csv');

  await pipeline(
    fetchRows,
    async function* (rows) {
      yield 'id,name,email\n';
      for await (const row of rows) {
        yield `${row.id},${row.name},${row.email}\n`;
      }
    },
    res,
  );
});

pipeline accepts generator functions as steps, and backpressure flows all the way back. If the client reads slowly, the yield pauses, the generator stops asking for the next page, and the database isn’t queried until there’s room. You get a constant-memory export without writing a single Transform class.

In real code, escape the CSV values and wrap this in a try/catch. If the client disconnects halfway, pipeline rejects, and you’ll want to log that rather than crash.

Reading with for await

The same applies when you consume a stream. for await on a readable stream respects backpressure on its own, because the stream only produces the next chunk when your loop asks for it:

import { createReadStream } from 'node:fs';
import readline from 'node:readline';

const lines = readline.createInterface({ input: createReadStream('big.log') });

for await (const line of lines) {
  if (line.includes('ERROR')) await saveError(line);
}

If saveError is slow, reading slows down with it. No buffering surprises.

The short version

Use pipeline() instead of .pipe(). Prefer async generators and for await over hand-written stream classes. And if you ever call .write() in a loop yourself, check what it returns.