Node.js Developer interview question
How do you handle backpressure in Node.js streams?
Backpressure prevents a fast producer from overwhelming a slow consumer. Respect writable.write returning false, wait for drain, or use pipeline so flow control, error propagation, and cleanup are handled together.
Direct answer
What a strong answer covers
How it works
A readable source that produces faster than a writable sink consumes will buffer in memory until the process dies unless the producer slows down. Writable.write returns false when its internal buffer passed the highWaterMark; the producer must then stop and resume on the drain event. pipe and pipeline implement this handshake automatically, and pipeline additionally propagates errors and destroys every stream in the chain on failure. Transform streams in the middle inherit the same contract, and async iteration with for await over a readable respects it as well.
Example
Copying a 10 GB file to S3 with readStream.on('data', chunk => upload.write(chunk)) grew memory to several gigabytes because the disk read faster than the network; replacing it with pipeline(readStream, gzip, uploadStream) kept memory flat at the buffer size. A CSV import that inserts rows uses a Transform with an async write that awaits the database, so the file reader pauses when the database falls behind.
Common mistakes
- Ignoring the return value of write and letting the buffer grow.
- Using pipe without an error handler so a failure leaves streams open.
- Reading a whole file with readFile when a stream would keep memory bounded.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.