Node.js theorytheory 0/50 · 0%
I/O · medium

12. Stream backpressure

Why write() can return false, and why that matters.

Backpressure happens when a Readable produces data faster than a Writable can consume it. `writable.write(chunk)` returns `false` when its internal buffer is full; well-behaved producers should pause until the `"drain"` event fires rather than keep writing and exhausting memory.

js
function writeAll(writable, chunks) {
  let i = 0;
  function next() {
    while (i < chunks.length) {
      const ok = writable.write(chunks[i++]);
      if (!ok) {
        writable.once("drain", next);
        return; // pause until buffer drains
      }
    }
  }
  next();
}

`.pipe()` (and the newer `pipeline()` / `stream/promises`) implements this dance for you automatically, which is why piping is almost always preferred over manually calling `write` in a loop.

Check your understanding

  1. 1. What does writable.write() return when its internal buffer is full?

  2. 2. What event tells a producer it is safe to resume writing?

  3. 3. What handles backpressure automatically for you?