How to Implement Backpressure with Async Iterators
Use async iterators to let a slow consumer pull from a fast producer, so memory stays bounded and pressure propagates upstream.
On this page
Introduction
A fast producer and a slow consumer are a memory leak waiting to happen: the producer keeps reading and buffering, the consumer falls further behind, and eventually the process runs out of memory. Backpressure is the signal that tells the producer to slow down, and async iteration is the natural way to express it in JavaScript and TypeScript. An async iterator inverts control: the consumer pulls the next value when it is ready, so a slow consumer naturally applies pressure to a fast producer, and buffering stays where you explicitly put it, not in an unbounded queue.
Pull Versus Push
A push interface, like an event emitter or a stream in flowing mode, delivers data as fast as it arrives and relies on the consumer keeping up. If the consumer is slower, the data piles up in the emitter’s or the stream’s internal buffer. A pull interface, the async iterator, hands over the next value only when the consumer asks, so the producer cannot outrun the consumer.
The inversion is what makes backpressure automatic. With a pull interface, a slow consumer simply takes longer between next() calls, and the producer waits. No explicit queue bounds are needed at the interface, because the consumer defines the pace.
This is the same relationship as a bounded buffer, expressed differently: the buffer depth is implicit in how far ahead the consumer is willing to read. If the consumer reads one value, processes it, then reads the next, the effective buffer is one. If it pulls a batch and processes the batch, the batch size is the buffer.
// A pull-based source: the consumer requests each value.
async function* readLines(path: string): AsyncGenerator<string> {
const stream = createReadStream(path, { encoding: 'utf8' });
let buffer = '';
for await (const chunk of stream) { // awaits the underlying backpressure
buffer += chunk;
let idx: number;
while ((idx = buffer.indexOf('\n')) >= 0) {
yield buffer.slice(0, idx); // yield = pull point
buffer = buffer.slice(idx + 1);
}
}
if (buffer) yield buffer;
}
Consuming with for await
The consumer uses for await…of, which awaits each value before asking for the next. Processing time becomes the pace: if handling one record takes ten milliseconds, the iterator delivers at most a hundred a second, and the producer upstream is throttled to match. The loop body is where backpressure is applied.
If you want concurrency, you must add it deliberately, for example by pulling N values and processing them in parallel with a bounded pool. Unbounded parallelism defeats backpressure, because the consumer then consumes as fast as it can and buffers the work. Choose a bound equal to the downstream’s capacity.
async function process(file: string, concurrency = 4) {
const iterator = readLines(file)[Symbol.asyncIterator]();
const inFlight = new Set<Promise<void>>();
for (;;) {
const next = await iterator.next();
if (next.done) break;
const p = handle(next.value).finally(() => inFlight.delete(p));
inFlight.add(p);
if (inFlight.size >= concurrency) {
await Promise.race(inFlight); // bounded concurrency, still pull-based
}
}
await Promise.all(inFlight); // drain the tail
}
Composing Transforms
Async generators compose: a map, a filter and a batch stage each pull from the previous and yield to the next, and backpressure flows through the whole chain. A consumer that pauses pauses every stage, because each stage only produces when its downstream asks. This is the same composability as synchronous iterators, extended with the await that the underlying I/O requires.
Composition keeps each stage small and testable: the transform knows nothing about the source or the sink, only about its input iterator and its output. Because the pipeline is lazy, a consumer that stops after ten records never pulls the rest, which is exactly what you want for early termination.
async function* map<I, O>(src: AsyncIterable<I>, f: (i: I) => O): AsyncGenerator<O> {
for await (const item of src) yield f(item);
}
async function* batch<T>(src: AsyncIterable<T>, size: number): AsyncGenerator<T[]> {
let buf: T[] = [];
for await (const item of src) {
buf.push(item);
if (buf.length >= size) { yield buf; buf = []; }
}
if (buf.length) yield buf;
}
for await (const rows of batch(map(readLines('data.csv'), parseRow), 500)) {
await insertBatch(rows); // slow sink throttles the whole pipeline
}
Bridging Node Streams and Iterators
Node.js readable streams are already async iterable, so for await…of on a stream gives you backpressure for free: the stream only advances when the loop asks for the next chunk. Writable streams accept a return value from the iterator callback to signal backpressure, and pipelines handle it automatically.
When you must connect a push source, such as a WebSocket message event, to a pull consumer, adapt it with a bounded queue. The queue holds the pressure: the producer blocks or drops when the queue is full, and the iterator pulls from it. Never adapt with an unbounded array, which simply reintroduces the memory leak.
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';
// Streams: pipeline propagates backpressure through every stage.
await pipeline(
createReadStream('big.log'), // source honours pause/resume
createGzip(),
createWriteStream('big.log.gz'),
);
// for await over a readable stream is equally backpressure-aware:
// for await (const chunk of createReadStream('big.log')) { ... }
Error Handling and Cleanup
An error thrown inside an async generator propagates to the consumer’s for await loop, and the iterator should release its resources in a finally block, closing files and streams. A consumer that breaks out of the loop early triggers the generator’s return method, which is where the cleanup runs; if cleanup is skipped, descriptors leak.
Handle the case where the consumer stops early, times out or is cancelled. Use a signal-aware source so a cancelled pipeline closes the underlying stream promptly. The combination of pull semantics, finally cleanup and cancellation is what makes the pipeline safe to stop mid-stream without leaking.
async function* safeLines(path: string): AsyncGenerator<string> {
const stream = createReadStream(path, { encoding: 'utf8' });
try {
let buffer = '';
for await (const chunk of stream) {
buffer += chunk;
let i: number;
while ((i = buffer.indexOf('\n')) >= 0) { yield buffer.slice(0, i); buffer = buffer.slice(i + 1); }
}
if (buffer) yield buffer;
} finally {
stream.destroy(); // runs on early break/throw/return: no leaked fd
}
}
Common Pitfalls and Conclusion
Do not collect an async iterator into an array before processing; that discards backpressure entirely. Do not add unbounded parallelism, which has the same effect. Do not forget cleanup in a finally, or early termination leaks resources. And do not assume push sources respect backpressure; adapt them with a bounded queue rather than trusting them.
Async iterators make backpressure a property of the code rather than something you remember to implement. A pull consumer sets the pace, async generators compose transforms, streams are already iterable, and a bounded queue adapts the push sources that cannot be pulled. The result is a pipeline that stays bounded in memory no matter how fast the producer runs.
Sources: Node.js: Streams and backpressure, MDN: Async iteration, TC39: Async generators proposal.
FAQ
- How does for await apply backpressure?
- It awaits each value before requesting the next, so the loop body defines the pace. If handling a value is slow, the next value is not pulled until the previous one is handled, and that pressure propagates back to the source.
- What do I do with a push source like a WebSocket?
- Adapt it with a bounded queue: the producer blocks or drops when the queue is full, and the async iterator pulls from the queue. An unbounded array does not adapt it and reintroduces the memory growth you were trying to avoid.
Report a problem with this articleOpens a pre-filled issue on GitHub.