What is backpressure in Node.js streams?
Backpressure is when a writable cannot consume data as fast as a readable produces it. The writable signals this, and the reader should pause, otherwise memory fills up with unwritten data.
Explain it simply
A tanker fills a small water tank faster than the tank can be emptied into the house. If nobody closes the tanker's valve, water overflows. Backpressure is the signal that says, "Tank is full, slow down." In streams, the "overflow" is memory: unwritten chunks pile up in RAM.
Example
const fs = require("fs");
const src = fs.createReadStream("big-video.mp4");
const dst = fs.createWriteStream("copy.mp4");
src.on("data", (chunk) => {
const ok = dst.write(chunk); // false means the internal buffer is full
if (!ok) {
src.pause(); // stop reading
dst.once("drain", () => src.resume()); // continue when emptied
}
});
src.on("end", () => dst.end());How it works:
write()returnsfalseonce the writable's internal buffer exceeds itshighWaterMark(16 KB by default for most streams).- The
drainevent fires when the buffer has emptied.
You rarely code this by hand. readable.pipe(writable) and stream.pipeline() handle pausing and resuming for you, as does for await over a stream. Backpressure is a main reason to use these instead of manual data handlers.
What to say in the interview
"Backpressure is the flow-control mechanism where a slow consumer tells the producer to pause. write() returning false plus the drain event implement it, and pipe or pipeline handle it automatically."
Common mistakes
- Ignoring the return value of
write()in a loop, which grows memory without limit. - Writing a custom copy loop when
pipelinewould do.