Your Server-Sent Events endpoint reads rows from a database cursor and writes each one to the response as soon as the cursor yields it. A client on a slow link reads one event a second. Every frame it has not read waits in your process, the cursor keeps advancing, and the heap grows until the process is killed.
What you get
You will end up with a producer that reads its source only as fast as a client reads, or drops events for a slow subscriber by a stated policy. Tests count both. This is for you if you stream from Node or Go.
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, 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 | 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 | 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' | 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 | 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 | 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.
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()
returns false once the response’s buffer reaches its highWaterMark. The
http.createServer options
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'.
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
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.
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
describes for a body sent after the headers, and
Deno.serve 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
is true, then queues up to its limit.
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
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.
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 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.
node slow-client.mjs
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.
go run ./cmd/slowclient
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.
node --test backpressure.test.mjs
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.
node check-go.mjs
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
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.
Footnotes
-
Node 22 raised the default from 16 KiB, which the Node 20 stream documentation gives, to 65536 bytes. The Node 22 page records the change in the history table of the
Writableconstructor in three words, “bump default highWaterMark.” TheReadableconstructor’s table carries the same three words for the same release. ↩︎ Back to text -
The Deno manual’s own streaming example builds its
ReadableStreamwithstartand asetIntervalthat adds a 14-byte greeting to the queue every second, without a look atdesiredSize. 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. ↩︎ Back to text -
The
SetWriteDeadlinedocumentation 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. ↩︎ Back to text