Skip to content

Web Streams

A customer posts a 400 MB NDJSON body of jobs to Relay. await request.text() loads all of it into memory, split("\n") makes a second copy, and JSON.parse on each line makes a third. Ten such requests in parallel and the process is gone.

Web Streams process the body chunk by chunk and apply backpressure for you: the source is paused when the next stage is busy. The same API exists in browsers, Bun and Node, so what you learn here is not Relay-specific. It is the standard version of the channel from the last lesson.

  • ReadableStream<T> produces chunks. fetch bodies and Bun.file(...).stream() are readable streams.
  • WritableStream<T> consumes chunks, like a file or a socket.
  • TransformStream<I, O> is both: you write I into its writable side and read O out of its readable side.
const source = new ReadableStream<string>({
start(controller) {
controller.enqueue("a\n")
controller.enqueue("b\n")
controller.close()
},
})
async function readAll(stream: ReadableStream<string>): Promise<string[]> {
const out: string[] = []
const reader = stream.getReader()
for (;;) {
const { done, value } = await reader.read()
if (done) return out
out.push(value)
}
}

reader.read() resolves { done: false, value } or { done: true }. If the stream errored, it rejects with that error. Releasing a reader that you do not finish with (reader.releaseLock()) matters, since a locked stream cannot be read by anyone else.

pipeThrough(transform) connects a readable to a transform and returns the transform’s readable. pipeTo(writable) ends the chain. Errors travel down the chain, and cancelling travels back up:

declare const body: ReadableStream<Uint8Array<ArrayBuffer>>
const lines = body
.pipeThrough(new TextDecoderStream()) // bytes to text, also across split multi-byte characters
.pipeThrough(new TransformStream<string, number>({
transform(chunk, controller) {
controller.enqueue(chunk.length)
},
}))

Always decode with TextDecoderStream, and never call .toString() on each chunk. A UTF-8 character can be split between two chunks, and decoding each half alone gives garbage characters.

A chunk is a slice of bytes, and nothing aligns it to a line. A job’s JSON can end in one chunk and continue in the next. A transform keeps the unfinished tail between calls, and flush handles whatever is left when the input ends:

function lines(): TransformStream<string, string> {
let tail = ""
return new TransformStream<string, string>({
transform(chunk, controller) {
const parts = (tail + chunk).split("\n")
tail = parts.pop() ?? "" // the last piece may be incomplete
for (const line of parts) controller.enqueue(line)
},
flush(controller) {
if (tail !== "") controller.enqueue(tail) // a last line without a newline
},
})
}

Forgetting flush loses the final job whenever the body does not end with a newline, which is common, and it only shows up in production.

Throwing inside transform errors the stream. The reader sees the rejection, and the source is cancelled so it stops producing. That is how a size cap works: stop reading a body that is too large, instead of buffering it and checking afterwards.

function limit(maxBytes: number): TransformStream<Uint8Array, Uint8Array> {
let seen = 0
return new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
seen += chunk.byteLength
if (seen > maxBytes) throw new Error(`body too large: limit is ${maxBytes} bytes`)
controller.enqueue(chunk)
},
})
}

Check against the declared Content-Length first as well. A client can lie, and a chunked body has no length. The stream cap is the check that cannot be fooled.

Each stream has a queue and a high-water mark: how many chunks (or bytes, depending on the strategy) it will hold before it asks the source to stop. controller.desiredSize is the room left: positive means “keep producing”, zero or below means “wait”. A source with a pull method is called again only when desiredSize is positive, which is how a slow reader pauses a fast file read:

const stream = new ReadableStream<string>(
{
start(controller) {
controller.desiredSize // 2: room for two chunks
controller.enqueue("a")
controller.desiredSize // 1
controller.enqueue("b")
controller.desiredSize // 0: the queue is full, stop producing
},
},
new CountQueuingStrategy({ highWaterMark: 2 }),
)

desiredSize is advice. enqueue still accepts the chunk when it is zero, so a source that ignores it fills memory just like the array in the last lesson.

Write the two transforms. ndjsonJobs turns text chunks into Job values and handles lines split across chunks, CRLF, blank lines and bad input with the line number. byteLimit errors past a cap. The tests build the streams from small hand-made chunks, so no network is involved. The starter parses each chunk as one whole line and never limits anything.

  • Streams process data chunk by chunk, so memory use stays flat for any body size.
  • pipeThrough chains a readable through transforms. Errors go down, cancellation goes up.
  • Chunks do not line up with lines or characters. Keep the tail between transform calls, finish in flush, and decode with TextDecoderStream.
  • Throwing in transform fails the stream and stops the source, which makes a byte cap cheap.
  • desiredSize tells a source whether to keep producing. It is advice, so sources must honour it.