How-To Guide

How to Implement Async Generators for Streaming

Stream data with async generators: yield items as they arrive, apply backpressure by awaiting the consumer, and bound memory per chunk.

On this page

  1. Introduction
  2. Yield items instead of building a list
  3. Let the consumer pull for backpressure
  4. Batch to amortize overhead
  5. Handle cleanup on early exit
  6. Test incremental arrival and bounded memory
  7. Common pitfalls
  8. Conclusion

Introduction

Producing a stream of items as an array forces the whole set into memory before the consumer sees the first one, which is wasteful for a large set and delays every consumer behind the first. An async generator yields items as they are produced, so the consumer processes each while the producer continues, memory stays proportional to one item, and the first item arrives immediately. It is the natural way to stream data from a source that is itself incremental.

This tutorial covers yielding rather than collecting, how the consumer’s pull provides backpressure, batching to amortize overhead, and testing that items arrive incrementally and memory stays bounded. The examples use async generators, and the corresponding constructs exist as async iterators in modern runtimes.

Yield items instead of building a list

An async generator function yields each item as soon as it is produced, and the consumer receives it with for await. The generator suspends at each yield until the consumer asks for the next item, so the two run in lockstep. A database cursor that returns rows one at a time, a file read line by line, and a paginated API that returns pages all map naturally to this shape.

The memory benefit is that only the current item is held, not the whole result. The latency benefit is that the consumer starts on the first item instead of waiting for the last. These two together are why streaming is the right shape for large or incremental data, and why collecting into an array first is the anti-pattern.

async function* readRows(cursor) {
  for await (const batch of cursor) {
    for (const row of batch) yield row;   // one row at a time to the consumer
  }
}

for await (const row of readRows(cursor)) {
  await process(row);   // the generator pauses here until this completes
}

Let the consumer pull for backpressure

The consumer pulls each item with await, and the generator does not advance until that pull returns. If the consumer is slow, the generator waits, so the production does not outpace the processing. This is backpressure by construction: the rate is set by the consumer, not by an eager producer filling a buffer.

For this to hold, the producer must not prefetch beyond one item. A generator that fetches the next ten pages into a buffer reintroduces the memory problem the generator was meant to solve. Fetch the next page only when the current page is exhausted, and yield each row before fetching more, so the buffer stays at one page. Measure the peak memory to confirm the prefetch is not growing.

Batch to amortize overhead

Yielding one item at a time can be inefficient when the consumer can process a batch, or when the source returns batches anyway. Yield a batch rather than a row, sized to bound memory and to amortize the per-item overhead. The batch size trades off: smaller batches give lower latency and lower memory, larger batches give higher throughput and fewer round trips.

Choose the batch from the consumer’s processing and the source’s natural unit. A database cursor often returns a batch already, so yielding that batch aligns with the source. A file read returns lines, so a batch of lines amortizes the write. Expose the batch size as a parameter and measure the throughput and memory at a few sizes to pick one.

async function* fetchPages(url: string, pageSize = 100) {
  let cursor: string | null = null;
  do {
    const res = await fetch(url + '?limit=' + pageSize + (cursor ? '&cursor=' + cursor : ''));
    const page = await res.json();
    yield page.items;              // one batch per pull: bounded memory
    cursor = page.nextCursor;
  } while (cursor);
}

Handle cleanup on early exit

A consumer may break out of the loop early, or an error may cancel the stream. The generator should release its resources when that happens: close the cursor, destroy the read stream, abort the request. A for await loop calls the generator’s return on early exit, so put the cleanup in a finally inside the generator, which runs on normal completion, an early break, and an error.

Without the finally, an early break leaves the cursor open or the request in flight, leaking a resource per cancelled stream. The finally is where the generator releases what it acquired, and it runs because the loop’s break invokes the generator’s return. This is the same resource-release discipline as in cancellation, applied to the streaming generator.

async function* streamWithCleanup(source) {
  const handle = await source.open();
  try {
    for await (const item of handle) yield item;   // yields to the consumer
  } finally {
    await handle.close();   // runs on completion, an early break, or an error
  }
}

Test incremental arrival and bounded memory

Test that the first item arrives before the source is exhausted, by timing the first yield against the completion of the source. Test that a slow consumer slows the producer, by asserting the producer does not advance while the consumer is processing. Test that peak memory stays flat as the number of items grows, which proves the generator is not buffering the whole set.

node --expose-gc -e '
const before = process.memoryUsage().heapUsed;
let first = null;
for await (const item of readRows(source)) { if (!first) first = Date.now(); }
const after = process.memoryUsage().heapUsed;
console.log("peak delta MB:", ((after - before) / 1e6).toFixed(1));  // stays flat
'

Common pitfalls

Collecting the whole result into an array before yielding, prefetching many items so the buffer grows, no finally so an early break leaks the source, a batch size that buffers more than intended, and an unchunked read that holds the whole input in memory are the recurring mistakes. Yielding one item at a time, pulling the next batch only when needed, a finally for cleanup, a sized batch, and chunked reads address them.

Conclusion

An async generator streams data by yielding each item as it is produced, with the consumer’s pull providing backpressure and memory bounded to one item or one batch. Yield rather than collect, do not prefetch beyond the batch, clean up in a finally for an early exit, and size the batch to the consumer. Self-check by asserting the first item arrives early and peak memory stays flat as the set grows. Then a large stream is processed without being held whole.

Sources: MDN: async function* and for await…of, MDN: Async iterators and generators, Python: Async generators.

FAQ

Why use an async generator over an array?
An array requires producing the whole result before the consumer sees the first item, which holds the entire set in memory and delays the first item. An async generator yields each item as it is produced, so memory is bounded and the consumer starts immediately.
Does an async generator apply backpressure?
It applies natural backpressure through the pull: the consumer's await on the next item means the producer does not advance until the consumer is ready. If the consumer is slow, the producer waits, so the work does not outpace the processing.

Related Examples