Skip to the page

Events, buffers, streams and files · senior

Backpressure

Backpressure is how a fast producer slows down for a slow consumer: writable.write() returns false when the buffer reaches highWaterMark, and the producer must wait for the 'drain' event before writing more; pipeline does this for you.

The notes

What you must know

  • highWaterMark is a threshold, not a hard limit: write() still accepts the chunk but returns false to say 'stop for now'.
  • Ignoring false keeps everything in memory. Memory grows until the process crashes (classic bug: a big loop of res.write()).
  • Correct manual loop: if (!stream.write(chunk)) await once(stream, 'drain').
  • On the read side, pipeline and for await...of only pull more data when the consumer is ready.
  • The Node docs warn that a socket that never drains (a slow or malicious client) can be a remotely exploitable memory problem; set timeouts.
  • If the client disconnects, the response stream is destroyed; pipeline rejects (ERR_STREAM_PREMATURE_CLOSE) and destroys the source too, which closes the file or DB cursor.

The red pen

Common traps: mistake → fix

  • Mistake: write() returning false means the chunk was dropped

    Fix: the chunk is buffered; false means 'pause until drain'.

  • Mistake: Backpressure is automatic everywhere

    Fix: only with pipeline, pipe or async iteration; manual write loops must check the return value.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is backpressure? Explain with a real example.
  2. What does write() returning false mean, and what do you do?
  3. How do pipeline and for await handle backpressure for you?
  4. A download endpoint uses 2 GB of RAM under load. How do you find and fix the cause?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview