ReadableStream and WritableStream: Piping, Fetch Bodies, and Large Payloads
How to read, pipe, and stream large request and response bodies with the Web Streams API in browsers and edge runtimes.
The Web Streams API is the standard way to move data in chunks instead of loading entire bodies into memory. Most of the material below comes from Cloudflare Workers runtime documentation; browser behavior for fetch and device APIs is summarized from Chrome developer documentation where it differs.
A readable stream exposes data you pull (getReader, pipeTo, pipeThrough). A writable stream accepts data you push (getWriter, write). A transform stream pairs both sides so you can decode, parse, or reshape bytes in the middle. Fetch Request and Response bodies are often ReadableStream instances, which is why streaming is central to edge workers and modern browsers.
ReadableStream: when to read versus pipe
Section titled “ReadableStream: when to read versus pipe”You need a reader when you want application logic to consume chunks one at a time. You pipe when one stream should feed another without your code handling every chunk.
A reader is used when you want to read from a ReadableStream, rather than piping its output to a WritableStream.
— Cloudflare, ReadableStream DefaultReader
On Workers, ReadableStream also supports pipeTo (end-to-end copy to a writable), pipeThrough (chain through a TransformStream), tee() (two branches with shared backpressure), cancel, async iteration with for await, and ReadableStream.from for async iterables.
How do I read chunks with getReader()?
Section titled “How do I read chunks with getReader()?”Call readable.getReader(), then loop on await reader.read() until done is true. Release the lock with reader.releaseLock() when finished (required before another consumer uses the stream).
The reader’s closed promise fulfills when the stream closes cleanly and rejects on errors — useful for detecting graceful versus abrupt shutdown on protocols built on streams (for example WebTransport receive streams).
What does the locked property mean?
Section titled “What does the locked property mean?”If readable.locked is true, something already holds the stream (a reader or an active pipe). You cannot attach a second reader until the lock is released.
WritableStream and writers: push data and backpressure
Section titled “WritableStream and writers: push data and backpressure”Write through const writer = writable.getWriter() then await writer.write(chunk). Finish with await writer.close() or stop early with await writer.abort(reason).
A writer is used when you want to write directly to a WritableStream, rather than piping data to it from a ReadableStream.
— Cloudflare, WritableStream DefaultWriter
On Cloudflare Workers, you typically obtain a WritableStream from new TransformStream() rather than calling a WritableStream constructor directly (WritableStream). writer.desiredSize reflects how much room remains in the internal queue (1, 0, or null on error/close in the Workers implementation).
Backpressure means a slow consumer signals upstream to slow production. Classic WebSocket.onmessage cannot apply backpressure; buffering can blow memory. WebSocketStream integrates streams so read() and write() naturally pace the pipeline when the browser supports it.
TransformStream: pipeThrough, TextDecoderStream, and custom transforms
Section titled “TransformStream: pipeThrough, TextDecoderStream, and custom transforms”A transform stream’s writable side accepts chunks; its readable side emits transformed chunks.
Writes to the writable side result in new data being made available for reading from the readable side.
— Cloudflare, TransformStream
readable.pipeThrough(transform) returns the transform’s readable side for chaining — the pattern used in streaming large JSON with @streamparser/json-whatwg.
Cloudflare documents IdentityTransformStream and FixedLengthStream ahead of stricter spec alignment (TransformStream). For serial devices, Chrome shows a custom TransformStream (for example line breaking) after TextDecoderStream (Read from and write to a serial port).
pipeTo options: preventClose and preventAbort
Section titled “pipeTo options: preventClose and preventAbort”When concatenating multiple upstream bodies into one response, pass { preventClose: true } to pipeTo so the destination stays open for the next body, then writable.close() once (Workers Best Practices).
| Option | Effect |
|---|---|
preventClose: true |
Source closing does not close the destination writable |
preventAbort: true |
Source errors do not abort the destination; pipeTo may still reject |
Large payloads and memory limits on Workers
Section titled “Large payloads and memory limits on Workers”Workers enforce a 128 MB memory limit. Buffering entire bodies with await response.text() or await request.arrayBuffer() fails on large inputs.
Regardless of memory limits, streaming large requests and responses is a best practice in any language. It reduces peak memory usage and improves time-to-first-byte. Workers have a 128 MB memory limit, so buffering an entire body with await response.text() or await request.arrayBuffer() will crash your Worker on large payloads.
— Cloudflare, Workers Best Practices
The recommended pass-through pattern is return new Response(response.body, response) after fetch, so bytes flow without an extra copy (Workers Best Practices).
Stream large JSON explains parsing and transforming JSON incrementally so multi-gigabyte payloads stay within memory bounds.
Workflows step.do() and streamed step output
Section titled “Workflows step.do() and streamed step output”In Cloudflare Workflows, step.do() can return a ReadableStream directly. Non-stream step outputs remain limited to 1 MiB; streamed outputs can be much larger but still count toward workflow instance storage limits (changelog).
RPC and R2 bodies
Section titled “RPC and R2 bodies”Workers RPC can send ReadableStream and WritableStream with flow control for bodies larger than the typical 32 MiB RPC limit, but only byte-oriented streams (type: "bytes"). Ownership transfers to the recipient; use tee() or clone() if the sender must keep a copy (RPC). R2 GET returns R2ObjectBody.body as a ReadableStream (Workers API reference).
Request and Response bodies: Content-Length versus chunked
Section titled “Request and Response bodies: Content-Length versus chunked”The runtime sets Content-Length from the body source; manual header values in user code are ignored (Request, Response).
To force a specific Content-Length, the body must be a FixedLengthStream or a fixed-length string or TypedArray. Any other ReadableStream on a Request or Response uses chunked encoding.
const { writable, readable } = new FixedLengthStream(11);const enc = new TextEncoder();const writer = writable.getWriter();writer.write(enc.encode("hello world"));writer.end();return new Response(readable);BYOB reading: bring your own buffer
Section titled “BYOB reading: bring your own buffer”BYOB (bring your own buffer) lets you read into a pre-allocated ArrayBufferView, reducing copies. Request a BYOB reader with readable.getReader({ mode: 'byob' }) (ReadableStream BYOBReader, Direct Sockets).
On Workers, read(buffer) may return far fewer bytes than the buffer size — the team notes it often fills only about 1% of a large buffer. readAtLeast(minElements, buffer) is a Cloudflare extension that does not resolve until at least minElements elements (bytes for Uint8Array) are read, with defined behavior at EOF (ReadableStream BYOBReader).
Fetch streaming request bodies in the browser
Section titled “Fetch streaming request bodies in the browser”From Chromium 105, fetch can POST a ReadableStream body so the client starts the request before the full payload exists (Streaming requests with the fetch API).
Requirements and pitfalls:
| Topic | Browser rule |
|---|---|
duplex |
Set duplex: 'half' when body is a stream |
| Redirects | Streaming bodies: redirects other than 303 cause fetch to reject (no body re-send) |
| CORS | Streaming requests trigger preflight; no-cors is not allowed |
| HTTP version | Rejected on HTTP/1.x; HTTP/2 and HTTP/3 carry framed chunks |
| Chunks | Request body chunks must be Uint8Array; use TextEncoderStream for text |
Response bodies have supported response.body.getReader() longer; chunk count and size depend on network speed (fetch streaming requests).
Feature detection can probe whether duplex is honored versus falling back to a string body "[object ReadableStream]" (feature detection).
Compose upload pipelines with an identity TransformStream: write to writable, pass readable as fetch body (Using with writable streams).
WebTransport, TCP sockets, and device I/O on streams
Section titled “WebTransport, TCP sockets, and device I/O on streams”WebTransport exposes unreliable datagram and reliable stream traffic over HTTP/3, with Uint8Array chunks and Streams-compliant interfaces including backpressure. It is not a raw UDP socket API; encryption and congestion control apply.
On Workers, TCP sockets expose readable and writable stream sides; the writable accepts Uint8Array chunks.
Direct Sockets and Web Serial use the same read/write patterns. USB bulk transfer guidance mirrors stream pacing: split payloads into smaller transactions and limit how many are pending at once to avoid OS limits and improve throughput.
Cloudflare Stream transform bindings return .response(), .media() as Promise<ReadableStream<Uint8Array>>, or .contentType() after configuration.
Text encoding, compression, and hashing streams
Section titled “Text encoding, compression, and hashing streams”Workers provide UTF-8 TextEncoder / TextDecoder and standard TextEncoderStream / TextDecoderStream. CompressionStream / DecompressionStream support deflate, deflate-raw, and gzip.
crypto.DigestStream is a WritableStream that computes a digest without retaining all written bytes.
EventSource.from(readableStream) is a Workers-specific helper that attaches Server-Sent Events parsing to an existing readable stream.
Compatibility flag streams_enable_constructors enables new ReadableStream() / new WritableStream() from underlying sources and sinks (compatibility flags).
Common mistakes
Section titled “Common mistakes”- Buffering large bodies —
text(),json(), orarrayBuffer()on hugefetchor R2 objects in Workers. - Forgetting
duplex: 'half'— streamingfetchPOST bodies in Chromium without it. - Following redirects with a stream body — fails except for 303.
- Assuming BYOB fills the buffer — prefer
readAtLeaston Workers when you need minimum byte counts. - Double-consuming a body —
bodyUsedbecomes true after read; useclone()ortee()when two consumers need the same bytes (Response). - Ignoring cancel propagation — canceling a stream returned from a Durable Object can abort the producer on the other side.
- Classic WebSocket message floods — no backpressure on
onmessage; consider WebSocketStream where available or throttle processing.
PWA tooling can concatenate multiple stream sources into one ReadableStream for composite responses; isSupported() checks basic ReadableStream construction.
How to check this on your site
Section titled “How to check this on your site”-
In a Worker or browser console,
fetcha known URL and confirmresponse.bodyis aReadableStreamand incrementalread()receivesUint8Arraychunks before the full download completes (fetch streaming requests). -
In a Worker, replace
await response.text()withreturn new Response(response.body, response)and confirm large upstream responses no longer hit the 128 MB limit (Workers Best Practices). -
For browser streaming uploads, verify the server receives chunked data only over HTTP/2 or HTTP/3, CORS preflight succeeds, and
duplex: 'half'is set (Streaming requests). -
If you rely on a fixed
Content-Length, test withFixedLengthStreamand confirm the runtime sets the header (Response). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about so it can be corrected.