In Node.js, what does writable.write() returning false mean, and what must the code writing to that stream do next?
answer
- a request, not an error
- the chunk was still accepted
- internal buffer versus highWaterMark
- an event that means resume
basics
~20 sfalse means the stream's internal buffer has reached its highWaterMark after accepting the chunk. Nothing is lost, but the writer should stop calling write() and resume on the 'drain' event, or memory grows without limit.
solid answer
~40 s`write()` always accepts the chunk into the stream's internal buffer; the boolean only says whether that buffer is still below `highWaterMark`. `false` is a request to pause: stop writing and resume when the stream emits `'drain'`, which fires once the buffered data has been flushed. Nothing enforces it. Node keeps buffering whatever you write, so a producer that ignores `false` turns a slow destination into growing memory, heavier garbage collection and eventually a crash. `highWaterMark` is a threshold, not a cap: one large chunk can push the buffer well past it. In Node 24 the default is 64 KiB for byte streams (16 KiB on Windows) and 16 objects in object mode. In practice I only hand-roll this loop when I must; `stream.pipeline` does the pausing for me.
code
javascript · 18 linesimport http from 'node:http';
import { once } from 'node:events';
http.createServer(async (req, res) => {
const ac = new AbortController();
res.once('close', () => ac.abort()); // completion or a dropped connection
res.writeHead(200, { 'content-type': 'text/csv' });
try {
for (let i = 1; i <= 2_000_000; i++) {
if (!res.write(`${i},customer-${i}\n`)) {
await once(res, 'drain', { signal: ac.signal });
}
}
res.end();
} catch (err) {
console.error('export stopped:', err.name); // AbortError if the client left
}
}).listen(8080);go deeper
Recall that false means slow down and that 'drain' means you may write again; the chunk you just wrote was not lost.
Explain highWaterMark as a threshold measured in bytes or objects, its Node 24 defaults, and the write-check-wait-resume loop.
Show the production failure: a slow or stalled client, unbounded buffering, climbing RSS, and a drain wait that hangs after a disconnect. Know when pipeline replaces the loop.
Argue for a team rule that response bodies of data-dependent size go through pipeline rather than hand-written write loops, with review checks for ignored write() results.
## The contract A **Writable** stream in Node.js (a file stream, a socket, an HTTP response, the writable side of a gzip Transform) has an internal buffer. `writable.write(chunk)` puts the chunk in that buffer and returns a boolean: - **`true`**: after admitting this chunk, the buffer is still below the stream's **`highWaterMark`**. Keep writing. - **`false`**: the buffer has reached or passed `highWaterMark`. The chunk was **still accepted**; Node is asking the caller to stop until the stream emits **`'drain'`**. `'drain'` is emitted when the buffered chunks have been handed on (for a socket, accepted by the operating system), meaning it is appropriate to resume writing. This pair, a `false` return and a later `'drain'`, is how Node expresses **backpressure**: the consumer telling the producer to slow down. ## What highWaterMark measures `highWaterMark` is set per stream when it is created, and its unit depends on the stream's mode: | Stream kind | Unit | Default in Node 24 | |---|---|---| | Byte stream (Buffers) | Bytes | 65536 (64 KiB); 16384 on Windows | | Object mode | Number of objects | 16 | | String stream that does not decode | UTF-16 code units | Same number as for bytes | `stream.getDefaultHighWaterMark(objectMode)` returns the current default, and the defaults were raised in Node 22.0.0. Older guides that quote 16 KiB describe the earlier value. Crucially, `highWaterMark` is a **threshold, not a limit**. It decides when `write()` starts returning `false`; it does not refuse data. Write one 5 MB chunk to a stream with a 64 KiB threshold and the whole 5 MB is buffered. ## What happens when you ignore false Nothing stops a caller from writing after `false`. Node documents the consequence plainly: it will buffer every written chunk until memory runs out, at which point the process aborts. Before that point: - the heap grows, so the garbage collector does more work and pauses get longer; - **RSS** (the process's resident memory) climbs and is often not given back to the system even after the data is sent; - for a TCP socket whose peer simply stops reading, the buffer may never drain, so a remote client can make your process hold unbounded data. Node's documentation calls this a potentially remotely exploitable vulnerability. The bug is invisible in testing on a fast local network, because the destination keeps up and `write()` keeps returning `true`. ## Honouring it by hand When a loop must call `write()` itself, the shape is: 1. Call `write(chunk)` and keep its return value. 2. If it returned `true`, continue with the next chunk. 3. If it returned `false`, stop and wait for one `'drain'` event, for example with `await once(stream, 'drain')` from `node:events`. 4. Resume the loop; call `end()` after the last chunk so the stream can flush and emit `'finish'`. Two traps sit next to that loop: - **A destination that goes away never drains.** If an HTTP client disconnects, the response will not emit `'drain'`, and `events.once()` only rejects on `'error'`. Give the wait an `AbortSignal` that you abort on the response's `'close'` event, or the handler waits forever. - **A Transform that nothing reads never drains either.** A Transform's readable side is paused until something consumes it, so writing into one with no consumer fills both of its buffers and then never drains. ## When not to hand-roll it The loop above is correct but easy to get subtly wrong. Node offers two better shapes: - Model the data as a source (a Readable or an async generator) and connect it with **`stream.pipeline`**, which waits for `'drain'` at every stage and also handles errors and cleanup. - `writable.writableNeedDrain` tells you whether a stream is currently waiting to drain, which helps when several pieces of code share one writer. ## Observing it in a running service Backpressure problems are easier to prove than to guess at: - `writable.writableLength` is the number of bytes (or objects) currently queued; compare it with `writable.writableHighWaterMark`. - A queue that sits far above the threshold on one stream means its producer is ignoring `false`. - Process memory that climbs only while slow clients are connected, and falls when they leave, points the same way. ## Summary `false` from `write()` is advisory and is the only signal Node gives. Code that respects it keeps memory near `highWaterMark` per stage; code that ignores it moves the whole data set into memory whenever the destination is slower than the source.
- Why can await once(res, 'drain') hang forever in an HTTP handler, and how do you prevent it?If the client disconnects, the response will never drain, and `events.once()` only rejects early on `'error'`, which a dropped client does not necessarily emit on the response. Pass an `AbortSignal` that you abort on the response's `'close'` event, or move to `stream.pipeline`, which notices the premature close and tears the chain down.
- In object mode, what does a highWaterMark of 16 mean?Sixteen objects, not sixteen bytes. In object mode the buffer counts items, so 16 large row objects can hold far more memory than 64 KiB. If each object is big, lower the threshold or batch differently; the count says nothing about each object's size.
- Does write() returning true guarantee the data reached the client?No. `true` only means the stream's buffer is still under `highWaterMark`. The data may still be queued in Node or in the kernel. Use the `write()` callback, or wait for `'finish'` after `end()`, to know when Node has flushed it; delivery to the remote application is beyond what a socket write can confirm.
A supermarket checkout belt has a line painted on it. The customer keeps loading until items reach the line, then waits for the cashier to clear space. An item set down past the line still goes on the belt; the line tells you when to stop, it does not stop you.
- write() returning false means the chunk was rejected and must be resent
- highWaterMark is a hard memory limit that Node enforces
- Node throws an error if you keep writing after write() returns false
- In object mode highWaterMark is still counted in bytes
- You should poll write() in a loop until it returns true again
Assumes Node.js 24; the default highWaterMark for byte streams was raised from 16 KiB to 64 KiB (16 KiB still on Windows) in Node 22.0.0, while the write()/'drain' contract itself is unchanged.