Backend & Node.js · APIs, data and failure
How do streams and backpressure work in Node.js?
Short answer
Streams process data incrementally instead of loading it all into memory. Backpressure is the mechanism that slows a fast source when a slow destination cannot keep up, using highWaterMark and pause or drain signals.
A stream is an abstraction over a sequence of data. Readable streams produce chunks, writable streams consume them, and transform streams do both. Because data is processed in chunks, memory stays bounded even for files or responses larger than the heap.
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";
import { pipeline } from "node:stream/promises";
async function compress() {
await pipeline(
createReadStream("access.log"),
createGzip(),
createWriteStream("access.log.gz"),
);
}
compress().catch(console.error);Backpressure
- write returns false when the internal buffer exceeds highWaterMark
- The producer should wait for the drain event before writing more
- readable.pause and resume control flow for manual consumers
- pipe and pipeline manage backpressure automatically
- Ignoring the return value of write can grow memory without bound
The most common production bug is mixing stream modes incorrectly, such as attaching a data listener and also calling read, or writing without awaiting drain. Use pipeline for multi-stage flows because it handles cleanup, errors and teardown across all stages.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens when you ignore the return value of write?
- 2How does pipeline differ from pipe?
- 3What is highWaterMark?
- 4When should you avoid streams?
Say it in the interview
Streams let me process data in chunks so memory stays bounded instead of loading everything at once. Backpressure is how a stream signals that its buffer is full: write returns false and the producer waits for drain. I use pipeline because it wires errors and cleanup across all stages. Streams are a memory and latency win, not a reduction in total work, so for small payloads a normal read is fine.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Backend & Node.js mock interview and get scored feedback on depth, clarity and confidence.