Overview
Channels provide WebSocket-backed streams for worker-to-worker data transfer. They enable streaming large payloads, real-time data processing, and bidirectional communication.Creating Channels
create_channel
Create a streaming channel pair with a writer and reader.int
default:64
Optional buffer size for the channel
Channel
Channel object containing writer, reader, and their serializable references
Channel Type
ChannelWriter
WebSocket-backed writer for streaming binary data and text messages.write
Write binary data to the channel.bytes
required
Binary data to write. Large payloads are automatically chunked (64KB per frame)
send_message_async
Send a text message to the channel.str
required
Text message to send
send_message
Fire-and-forget text message (non-async).str
required
Text message to send
close_async
Close the writer connection.close
Fire-and-forget close (non-async).stream Property
Access the writer as aWritableStream interface:
ChannelReader
WebSocket-backed reader for streaming binary data and text messages.Async Iteration
Read binary chunks using async iteration:read_all
Read the entire stream into a single bytes object:bytes
All data from the stream concatenated together
on_message
Register a callback for text messages:Callable[[str], Any]
required
Function called for each text message received
close_async
Close the reader connection.stream Property
Access the reader as aReadableStream interface:
Passing Channels Between Functions
Channels can be passed between functions using their serializable references:Streaming Patterns
Producer-Consumer
Bidirectional Communication
File Upload
Transform Stream
HTTP Response Streaming
Use channels with HTTP triggers for streaming responses:WritableStream
Node.js-style writable stream interface:Usage
ReadableStream
Node.js-style readable stream interface:Usage
StreamChannelRef
Serializable reference to a channel endpoint:ChannelReader or ChannelWriter when passed in function invocations.
Error Handling
Best Practices
- Always close channels: Call
close_async()orclose()when done writing - Handle errors: Wrap channel operations in try-except blocks
- Use appropriate buffer sizes: Larger buffers for high-throughput scenarios
- Chunking: Large payloads are automatically chunked at 64KB per frame
- Text vs Binary: Use
write()for binary data,send_message()for text