Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 53
What is backpressure in Node.js streams?
Direct answer
Backpressure slows a fast producer when the consumer cannot keep up — writable.write() returns false, pause the readable, resume on 'drain'; pipeline handles this automatically; ignoring it causes memory spikes and OOM.
Without backpressure, a fast disk read flooding a slow network response buffers unbounded chunks in RAM — production APIs hit OOM under load.
Why interviewers ask
- write returns false — stop writing until writable emits 'drain'.
- readable.pause() — manual backpressure when not using pipe/pipeline.
- highWaterMark — default 16KB (object mode: 16 objects); tune for throughput vs memory.
- pipeline() — wires pause/resume across the chain correctly.
backpressure.mjs
function writeWithBackpressure(readable, writable) {
readable.on("data", (chunk) => {
const ok = writable.write(chunk);
if (!ok) {
readable.pause();
writable.once("drain", () => readable.resume());
}
});
readable.on("end", () => writable.end());
}
// Prefer:
// import { pipeline } from "node:stream/promises";
// await pipeline(readable, writable);