Skip to content

Backpressure with async iterators

Relay accepts 2,000 events per second, and the notifier handles 300. The intake code pushes each event into an array and the notifier drains it. The array grows by 1,700 items every second until the process is killed for memory. Nothing failed along the way. The producer just never had a reason to slow down.

Backpressure is the signal that flows backward from a slow consumer to a fast producer: “wait”. This lesson shows two ways to get it with async iterators, and builds a channel where a full buffer makes send wait.

In a push design, the producer calls the consumer, or appends to a list, whenever it has data. The consumer has no say. In a pull design, the consumer asks for the next item and the producer runs only to answer. With for await, the loop body finishes before the next item is requested, so the consumer sets the pace:

interface Event {
readonly id: string
}
declare function readEvents(): AsyncIterable<Event>
declare function notify(event: Event): Promise<void>
async function pump() {
for await (const event of readEvents()) {
await notify(event) // the next event is not requested until this is done
}
}

An async generator is the simplest producer, because it pauses at every yield. This is the same laziness as in generators, with await allowed in between:

async function* fromQueue(poll: () => Promise<readonly string[]>): AsyncGenerator<string, void, unknown> {
for (;;) {
const batch = await poll() // runs only when the consumer asked for more
if (batch.length === 0) return
yield* batch
}
}

If the consumer stops reading, poll is not called again. No queue grows.

A generator has one producer and one consumer, joined at one call. Relay’s intake is different: HTTP handlers produce events whenever requests arrive, and a worker consumes them. The producers cannot be paused by being “asked”. They need something to wait on: a bounded buffer between them.

A channel has a capacity. send stores the value and resolves, unless the buffer is full, in which case the promise stays pending until a receiver takes something. receive takes a value, or waits for one. close ends the stream:

type Received<T> = { readonly done: false; readonly value: T } | { readonly done: true }
declare class Channel<T> implements AsyncIterable<T> {
constructor(capacity: number)
send(value: T): Promise<void> // pending while the buffer is full
receive(): Promise<Received<T>> // pending while the buffer is empty
close(): void
[Symbol.asyncIterator](): AsyncGenerator<T, void, unknown>
}
async function intake(channel: Channel<string>, events: readonly string[]) {
for (const event of events) await channel.send(event) // slows down with the consumer
channel.close()
}
async function worker(channel: Channel<string>) {
for await (const event of channel) {
event // string
}
}

The key line is await channel.send(event). A producer that forgets the await bypasses the whole mechanism and floods the buffer with pending sends, so treat an unawaited send as a bug.

The state is three lists: the buffer, the senders waiting for room, and the receivers waiting for data. At most one of the last two is ever non-empty:

class Mailbox<T> {
readonly #buffer: { readonly value: T }[] = [] // boxed, so T may include undefined
readonly #waitingSenders: { readonly value: T; readonly resolve: () => void }[] = []
constructor(readonly capacity: number) {}
trySend(value: T): "accepted" | "full" {
if (this.#buffer.length < this.capacity) {
this.#buffer.push({ value })
return "accepted"
}
return "full"
}
take(): { readonly value: T } | undefined {
const slot = this.#buffer.shift()
const sender = this.#waitingSenders.shift()
if (slot !== undefined && sender !== undefined) {
this.#buffer.push({ value: sender.value }) // a blocked sender takes the freed slot
sender.resolve()
}
return slot
}
}

take is where backpressure is released: removing one value from a full buffer moves one blocked sender in and resolves its promise. That is the moment the producer is allowed to continue.

Write Channel<T> with send, receive, close and [Symbol.asyncIterator]. One test runs a producer against a channel of capacity 2 and checks its log: it must be stuck after two sends until the consumer takes one. The starter has an unbounded buffer, so the producer never waits.

  • Without backpressure a fast producer fills memory. Signal the producer to wait.
  • for await is pull-based: the body finishes before the next item is requested.
  • A bounded channel makes send wait when the buffer is full and receive wait when it is empty.
  • Taking a value from a full buffer is what lets one blocked sender continue.
  • close delivers what is buffered, ends waiting receivers and rejects blocked senders.