# How to apply backpressure when a client reads your stream slowly

> Make an SSE or NDJSON producer in Node or Go read its source only as fast as each client reads, or drop events for a slow subscriber on purpose.

Source: https://voxgig.com/howto/apply-backpressure-when-producing-a-stream

- Audience: api-producer
- Level: advanced
- Languages: typescript, go
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

In Node, pass an async generator over your cursor to stream.pipeline with the response as the destination. The pipeline asks for the next frame only when the response has room, and returns the generator when the client leaves, so the cursor stops and closes. For a live feed, give each subscriber a bounded queue that drops or coalesces. In Go, write each frame with a deadline set through http.ResponseController.

---
## You will need

Node 22 or later, Go 1.23 or later, and a producer that can outrun a slow client. Verified
2026-11-30 against Node 22.23.5 and Go 1.24.7. The sample sends
[Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html), one row of
about a kilobyte per frame, from a stand-in cursor that counts the rows read from it and records
when it is closed.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Bounded per-subscriber buffer](https://nodejs.org/docs/latest-v22.x/api/stream.html#writablewritableneeddrain) | A live feed, such as telemetry, where a stale event is worth nothing | A slow subscriber loses events, and each feed needs its own drop, coalesce, or close policy | Every row must arrive, as in an export or a query result |
| [Go blocking writes with `http.ResponseController`](https://pkg.go.dev/net/http#ResponseController.SetWriteDeadline) | A Go handler streaming rows that must all arrive | A goroutine and an open cursor per stalled client, until the write deadline fires | One source feeds many clients, so drop with a buffered channel instead |
| [`res.write()` return value and `'drain'`](https://nodejs.org/docs/latest-v22.x/api/stream.html#event-drain) | You frame events by hand, with heartbeats or comments between rows | A second signal to wire, because a client that leaves never sends `'drain'` | A generator can yield the frames, and `pipeline` waits for you |
| [`stream.pipeline` with an async generator](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options) | Node, and every row must reach the client in order | One slow client holds one cursor open for as long as it reads | Many clients share one source, which would run at the slowest one's pace |
| [Web Streams `ReadableStream` with `pull`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController/desiredSize) | Cloudflare Workers, Deno, or code shared between them and Node | A `Readable.fromWeb` bridge on Node, and a queue counted in chunks unless you size it | The code runs on Node only, where `pipeline` is shorter |

`pipeline`, the drain loop, and `pull` all slow the source to the client's pace. That suits a
query result, and fails a feed with thousands of subscribers, where one slow reader would hold the
source for everyone. The bounded buffer keeps the source at full speed and charges the slow
subscriber in lost events. `ReadableStream` costs a bridge on Node, and is the form Workers and
Deno serve.
Go's blocking write costs a goroutine per stalled client until its deadline.

## Pipe the cursor through stream.pipeline

`withPipeline` turns each row into an SSE frame inside an async generator and hands the generator
to `pipeline`, with the response as the destination.

```ts title="producers.mjs"
export async function withPipeline(cursor, res) {
  res.writeHead(200, SSE)
  async function* frames() {
    for await (const row of cursor.rows()) yield frame(row)
  }
  await pipeline(frames, res)
}
```

`pipeline` asks the generator for the next frame only while the response's buffer has room, so
the `for await`, and the cursor under it, waits on the socket. When the client disconnects,
`pipeline` rejects with `ERR_STREAM_PREMATURE_CLOSE` and returns the generator, which runs the
cursor's `finally` block.

## Wait for drain when you write frames by hand

[`res.write()`](https://nodejs.org/docs/latest-v22.x/api/stream.html#writablewritechunk-encoding-callback)
returns false once the response's buffer reaches its `highWaterMark`. The
[`http.createServer` options](https://nodejs.org/docs/latest-v22.x/api/http.html#httpcreateserveroptions-requestlistener)
take that mark from `stream.getDefaultHighWaterMark()`, which returns 65536 on Node 22, and a test
reads it from a running response.[^1] Stop there and wait for `'drain'`.

```ts title="producers.mjs"
export async function withDrain(cursor, res) {
  res.writeHead(200, SSE)
  const gone = new AbortController()
  res.once('close', () => gone.abort())
  for await (const row of cursor.rows()) {
    if (res.destroyed) break
    if (!res.write(frame(row))) {
      try {
        await once(res, 'drain', { signal: gone.signal })
      } catch {
        break
      }
    }
  }
  if (!res.destroyed) res.end()
}
```

The wait goes through [`events.once`](https://nodejs.org/docs/latest-v22.x/api/events.html#eventsonceemitter-name-options)
with an `AbortSignal` that the response's `'close'` event aborts. A client that leaves ends the
loop, and the `break` returns the generator, which closes the cursor.

## Let the stream pull from the cursor

The Web Streams form puts the pacing in `pull`. The stream calls it while its queue is below the
high-water mark, and the loop inside refills the queue only while `controller.desiredSize` is greater
than zero.

```ts title="producers.mjs"
export function webStream(cursor, highWaterMark = 16) {
  const rows = cursor.rows()
  const encoder = new TextEncoder()
  return new ReadableStream(
    {
      async pull(controller) {
        while (controller.desiredSize > 0) {
          const { value, done } = await rows.next()
          if (done) return controller.close()
          controller.enqueue(encoder.encode(frame(value)))
        }
      },
      async cancel() {
        await rows.return()
      },
    },
    new CountQueuingStrategy({ highWaterMark }),
  )
}
```

A Worker returns `new Response(webStream(cursor))`, the pattern the
[Workers streams documentation](https://developers.cloudflare.com/workers/runtime-apis/streams/)
describes for a body sent after the headers, and
[`Deno.serve`](https://docs.deno.com/runtime/fundamentals/http_server/) takes the same `Response`.[^2]
On Node, `withWebStream` bridges the same stream with
`Readable.fromWeb` and `pipeline`. `CountQueuingStrategy` counts frames, so 16 here means 16
frames of whatever size.

## Drop or coalesce for a live feed

A feed publishes each event once, to every subscriber, and never waits. Each subscriber writes
straight to its socket until
[`writableNeedDrain`](https://nodejs.org/docs/latest-v22.x/api/stream.html#writablewritableneeddrain)
is true, then queues up to its limit.

```ts title="feed.mjs"
    sub.offer = (event) => {
      if (sub.closed) return
      if (!res.writableNeedDrain) return res.write(frame(event))
      if (policy === 'coalesce') {
        const i = sub.queue.findIndex((e) => e.key === event.key)
        if (i !== -1) {
          sub.queue[i] = event
          sub.coalesced++
          return
        }
      }
      if (sub.queue.length >= limit) {
        if (policy === 'close') return this.drop(sub, res)
        sub.queue.shift()
        sub.dropped++
      }
      sub.queue.push(event)
      sub.maxQueued = Math.max(sub.maxQueued, sub.queue.length)
    }
```

`drop-oldest` keeps the newest events. `coalesce` keeps one queued event per key, the newest,
which suits a gauge whose last reading is the only one that matters. `close` disconnects the
subscriber, so its client reconnects with
[`Last-Event-ID`](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header)
and you decide what to replay.

## Block on the write in Go, with a deadline

A Go handler has backpressure built in: `Write` blocks while the socket is full, so the cursor
waits. What it lacks is an end. Set one on every write through
[`http.ResponseController`](https://pkg.go.dev/net/http#ResponseController).

```go title="stream/stream.go"
func blocking(w http.ResponseWriter, r *http.Request, cur *Cursor, perWrite time.Duration) error {
	defer cur.Close()
	rc := http.NewResponseController(w)
	w.Header().Set("Content-Type", "text/event-stream")
	w.WriteHeader(http.StatusOK)
	for {
		if err := r.Context().Err(); err != nil {
			return err
		}
		id, ok := cur.Next()
		if !ok {
			return nil
		}
		if perWrite > 0 {
			if err := rc.SetWriteDeadline(time.Now().Add(perWrite)); err != nil {
				return err
			}
		}
		if _, err := io.WriteString(w, frame(id)); err != nil {
			return err
		}
		if err := rc.Flush(); err != nil {
			return err
		}
	}
}
```

The dropping form in `stream.go` publishes into a buffered channel per subscriber, with a
[`select`](https://go.dev/ref/spec#Select_statements) whose `default` case counts a drop instead of
waiting. It drops the newest event, where the Node feed drops the oldest.

## Stall a client against each producer

`slow-client.mjs` opens each route with a client that pauses as soon as the headers arrive, polls
until the cursor stops moving, then disconnects.

```bash
node slow-client.mjs
```

```text output
route           source while paused       queued in res   cursor after the client left
/unbounded      all 50000                 over 10 MB      closed
/pipeline       stopped short of 50000    one buffer      closed
/drain          stopped short of 50000    one buffer      closed
/drain-no-close stopped short of 50000    one buffer      open, parked on drain
/web-stream     stopped short of 50000    one buffer      closed

feed policy  published  most queued  dropped  coalesced  newest of each key
drop-oldest  50000      64           some     none       delivered
coalesce     50000      8            none     some       delivered
close        50000      64           none     none       connection closed
```

`/unbounded` ignores what `write()` returns, so it read all 50,000 rows, about 52 MB of frames,
and kept in the response whatever the socket refused. "One buffer" means at most the
`highWaterMark` plus one frame. The kernel's socket buffers hold the rest, and their size differs
between machines, so the demo prints bounds rather than row counts.

The Go demo runs the same stalled client against the blocking handler twice, once with a deadline
and once without, then against the feed.

```bash
go run ./cmd/slowclient
```

```text output
producer                      source while stalled      how the handler ended         after
blocking, 500ms per write     stopped short of 50000    deadline exceeded             cursor closed
blocking, no deadline         stopped short of 50000    still in Write after 2s       cursor open
  then the client leaves                                client closed the connection  cursor closed
feed, buffer of 64            publisher never waited    deadline exceeded             dropped some, 0 subscribers
```

Without a deadline, a client that keeps its connection open and reads nothing holds the goroutine
and the cursor for as long as it likes.[^3]

## Check it worked

The Node tests resume each paused client and check that every row arrives in order, that a
departed client closes the cursor, and that each feed policy holds its bound.

```bash
node --test backpressure.test.mjs
```

```text output
1..12
# tests 12
# suites 0
# pass 12
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 6351.274122
```

The Go tests run through `check-go.mjs`, which prints one line per test in name order and exits 1
when one fails or none ran.

```bash
node check-go.mjs
```

```text output
pass  TestAReadingClientGetsEveryRowInOrder
pass  TestBlockingWriteStopsTheCursorAndTheDeadlineEndsIt
pass  TestTheFeedDropsForAStalledSubscriberWithoutWaiting
pass  TestWithoutADeadlineTheHandlerWaitsForTheClient
4 tests, 0 not passed
```

## When it goes wrong

Open cursors pile up while traffic looks normal. A drain loop awaits `'drain'` on a response whose
client has gone, which never emits it. The `/drain-no-close` row shows the loop parked with its
cursor open. Cancel the wait on `'close'`, as `withDrain` does, or use `pipeline`.

Memory grows with each slow client. The producer writes without reading what `write()` returns,
as `/unbounded` does, so every frame the socket refuses waits in the response's buffer. Route the
frames through `pipeline`, or stop at false and wait for `'drain'`.

A Go handler never returns for one client. Nothing set a write deadline, so the write blocks until
the client closes the socket. Set one before every write, as `blocking` does.

## When not to do this

Do not slow a shared source to the pace of one subscriber. A feed that fans out to thousands of
clients needs the bounded buffer, because `pipeline` would let the slowest reader set everyone's
rate.

Do not use the bounded buffer for a stream that must be complete, like an export. A dropped row there is lost data, and only a client that checks the event ids for gaps
can see it.

Do not stream at all when the result fits comfortably in a few pages. A paged endpoint keeps the
cursor position in the client's next request, so a slow reader holds no cursor open between
requests.

Do not set the Go write deadline shorter than a real client's longest pause. A phone that loses
signal for a second is disconnected, and its `EventSource` then reconnects and asks for the
stream again.

## Related how-tos

- [Add backpressure to a WebSocket consumer](/howto/add-backpressure-to-a-websocket-consumer)

- [Pick SSE, WebSockets, or long polling for a live endpoint](/howto/choose-sse-websockets-or-long-polling)

- [Consume Server-Sent Events with fetch and custom headers](/howto/consume-sse-with-fetch-and-custom-headers)

- [Retry a streaming response without replaying received data](/howto/retry-a-streaming-response-without-replaying-data)

- [Serve large file downloads without proxying the bytes](/howto/serve-large-file-downloads-without-proxying-bytes)

## Last verified

Verified 2026-11-30 against Node 22.23.5, Go 1.24.7, and Go 1.25.14. Every output block is what
the command preceding it printed. The `ReadableStream` producer ran on Node through
`Readable.fromWeb`, and was not run on Cloudflare Workers or Deno, whose handling of a streamed
`Response` body is read from their documentation.

[^1]: Node 22 raised the default from 16 KiB, which the
[Node 20 stream documentation](https://nodejs.org/docs/latest-v20.x/api/stream.html#new-streamwritableoptions)
gives, to 65536 bytes. The Node 22 page records the change in the history table of the
[`Writable` constructor](https://nodejs.org/docs/latest-v22.x/api/stream.html#new-streamwritableoptions)
in three words, "bump default highWaterMark." The `Readable` constructor's table carries the same
three words for the same release.

[^2]: The [Deno manual's own streaming example](https://docs.deno.com/runtime/fundamentals/http_server/)
builds its `ReadableStream` with `start` and a `setInterval` that adds a 14-byte greeting to the
queue every second, without a look at `desiredSize`. A source that pushes from a timer never
consults the queue, so a client that stops reading leaves the greetings to collect in it at 14
bytes a second.

[^3]: The [`SetWriteDeadline`](https://pkg.go.dev/net/http#ResponseController.SetWriteDeadline)
documentation is brief about what follows a miss. Writes after the deadline "will not block, but
may succeed if the data has been buffered," it says. Setting the deadline again after a miss "will
not extend it," so a deadline, once missed, stays missed.