Backpressure and drain
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Observe the pressure signal
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';import { once } from 'node:events';const sink = new Writable({highWaterMark:1,write(c,e,cb){setImmediate(cb);}});const accepted = sink.write('x');console.log(accepted);if(!accepted) await once(sink,'drain');sink.end(); await finished(sink,{cleanup:true});console.log('done');Run:
node main.mjsExpected stdout:
falsedoneExit status: 0. Expected stderr: empty.
How it works
Queued writes consume memory. A writable highWaterMark sets when the producer should slow down, rather than a maximum allocation. A false write result is not a rejected chunk: it was accepted for processing. The first example uses a highWaterMark of one and asynchronous completion to make the signal observable. The second explicitly waits for drain before the next write. Production manual writers also need to handle destination errors and premature closure; pipeline is usually simpler.
Wait before sending the next chunk
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';import { once } from 'node:events';let received = '';const sink = new Writable({highWaterMark:1,write(c,e,cb){received += c.toString();setImmediate(cb);}});for(const piece of ['a','b','c']) { if(!sink.write(piece)) await once(sink,'drain'); }sink.end(); await finished(sink,{cleanup:true});console.log(received);Run:
node main.mjsExpected stdout:
abcExit status: 0. Expected stderr: empty.
Common mistake
Do not keep writing after false or resend the same chunk on drain. Ignoring the signal can grow the queue; resending duplicates data.
Practice
Increase highWaterMark to 8 and predict which writes signal pressure. Do not infer a process memory limit from the threshold.
Further reading: Authoritative source 1. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Backpressure and drain — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What does write() returning false mean?
What is highWaterMark?
Which event signals that a paused producer can resume writing?