WebSocket broadcast channel

Learn how to fan out a message from one WebSocket client to every connected client with a tokio broadcast channel, a per-connection send task, and a live multi-client run

A broadcast channel is how one message reaches every connected client. It is a tokio::sync::broadcast channel: one sender, many receivers, and every message sent into it is delivered to every receiver that is listening. A WebSocket chat room is the shape that needs it: a client sends a line, the server puts it into the channel, and every connection, including the sender's own, receives it and writes it out to its client. The channel is the room, the connections are the people in it, and the message is spoken once and heard by all.

Where This Fits

The previous page proved that connections run independently, each in its own task, sharing only state. This page uses that shared state for its real purpose: a channel that connects the tasks to each other. An echo server talks back to one client, and a broadcast server talks to all of them, and the channel is the one new piece between the two.

Think of a broadcast channel like a loudspeaker in a hall. One person speaks into the microphone, and every speaker in the hall plays the words at once. The speaker does not call each listener in turn, and the listeners do not ask the speaker for the words. The channel is the loudspeaker system, and the message is heard by everyone who is in the hall.

The Smallest Working Version

This server creates a broadcast channel with room for 16 messages, stores its sender in shared state, and gives every connection a receiver. A message from any client goes into the channel, and every connection writes it out to its client.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
futures-util = "0.3"
src/main.rs
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    response::Response,
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use tokio::sync::broadcast;

#[derive(Clone)]
struct ChatState {
    tx: broadcast::Sender<String>,
}

async fn ws_handler(ws: WebSocketUpgrade, State(state): State<ChatState>) -> Response {
    ws.on_upgrade(|socket| handle_socket(socket, state))
}

async fn handle_socket(socket: WebSocket, state: ChatState) {
    let (mut sender, mut receiver) = socket.split();
    let mut rx = state.tx.subscribe();
    let send_task = tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(msg) => {
                    if sender.send(Message::Text(msg.into())).await.is_err() {
                        break;
                    }
                }
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => break,
            }
        }
    });
    let tx = state.tx.clone();
    while let Some(msg) = receiver.next().await {
        let Ok(msg) = msg else { break };
        if let Message::Text(text) = msg {
            let _ = tx.send(text.to_string());
        }
    }
    send_task.abort();
}

#[tokio::main]
async fn main() {
    let (tx, _rx) = broadcast::channel::<String>(16);
    let state = ChatState { tx };
    let app = Router::new()
        .route("/ws", get(ws_handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run it with cargo run. The live run below connects two clients, A and B, to this exact server in the verification project. Client A sends hello from A, and both clients receive it:

client: handshake status 101 Switching Protocols
client: handshake status 101 Switching Protocols
client B received: Text(Utf8Bytes(b"hello from A"))
client A received own broadcast: Text(Utf8Bytes(b"hello from A"))

Client B received the message, which is the broadcast working. Client A received its own message back too, because A is also a subscriber: the sender's own connection receives what it sent, like a speaker hearing their own voice through the hall speakers. That is the normal behaviour of a broadcast channel, and a chat client that does not want to see its own message filters it out on the client side, or the server tags the message with the sender's name so the client can tell.

Working Setup:

If client B receives a message only client A sent, the broadcast works. If only A receives it, the message went back to the sender instead of into the channel, and the tx.send line is the place to look. If neither receives it, the channel or the subscription is missing.

Understanding the New Parts Line by Line

The broadcast server has four pieces that the echo server did not, and each one is explained here.

Creating the channel

let (tx, _rx) = broadcast::channel::<String>(16);

broadcast::channel creates a channel and returns a sender, tx, and a receiver, rx. The type parameter, String, is the type of the messages, and the number, 16, is the capacity, the number of messages the channel can hold at once. The receiver returned here is discarded with _rx, because the server never reads from the channel itself: each connection subscribes with its own receiver. The sender is stored in the shared state, so every connection can send into the same channel. The capacity is a bound on memory: when the channel holds 16 unread messages and a new one arrives, the oldest is dropped, and a slow receiver that falls behind is told it lagged.

Subscribing per connection

let mut rx = state.tx.subscribe();

subscribe creates a new receiver for the channel, and each connection calls it once, when it opens. Every receiver gets every message sent after it subscribes, and none sent before. A client that connects late does not receive the earlier messages, because the channel is a live stream, not a history. The receiver is moved into the send task, which is why it is declared as mut: the task receives from it in a loop.

The send task

let send_task = tokio::spawn(async move {
    loop {
        match rx.recv().await {
            Ok(msg) => {
                if sender.send(Message::Text(msg.into())).await.is_err() {
                    break;
                }
            }
            Err(broadcast::error::RecvError::Lagged(_)) => continue,
            Err(broadcast::error::RecvError::Closed) => break,
        }
    }
});

The send task waits on the channel receiver and writes each message out to the client. rx.recv().await returns a Result: Ok(msg) when a message arrives, Err(Lagged(_)) when the receiver fell behind and messages were dropped, and Err(Closed) when the channel closed because every sender was dropped. The lagged arm continues the loop, which skips the missed messages and waits for the next one, because a chat client that fell behind wants the new messages, not a failure. The closed arm breaks the loop, because there will never be another message. The send arm breaks when the socket send fails, which means the client is gone. The task ends on any of those breaks, and the loop in the callback aborts it when the connection ends, as the next section shows.

The receive loop and the abort

let tx = state.tx.clone();
while let Some(msg) = receiver.next().await {
    let Ok(msg) = msg else { break };
    if let Message::Text(text) = msg {
        let _ = tx.send(text.to_string());
    }
}
send_task.abort();

The loop reads from the socket, and each text message goes into the channel with tx.send. tx is a clone of the shared sender, and cloning a broadcast sender is cheap: the clone points at the same channel. send returns a Result that is an error when there are no receivers left, and the let _ = ignores it, because a message with no listeners needs no handling. When the loop ends, because the client left or the read failed, send_task.abort() cancels the send task, which would otherwise keep waiting on the channel forever. The abort is the cleanup that stops the leak.

The Concept Behind Broadcast

A broadcast channel is a many-to-many pipe with a fixed buffer. One sender puts a message in, and every receiver takes a copy out. The copies are independent: a slow receiver does not slow down a fast one, because each receiver has its own position in the buffer. When the buffer fills, the oldest message is dropped, and the slowest receiver is told it lagged, instead of the whole channel blocking. That is the trade the channel makes: it never blocks the sender, and it tells a receiver when it missed something, instead of pretending nothing happened.

The buffer is the capacity, and it is a promise about memory, not about delivery. A capacity of 16 means the channel never holds more than 16 messages, so a burst of messages cannot grow the server's memory without bound. A receiver that keeps up never notices the bound. A receiver that falls more than 16 messages behind is told it lagged, and it rejoins at the newest message. The capacity is chosen from the expected traffic: 16 is enough for a chat room where messages arrive one at a time, and a busy room with bursts needs more.

Broadcast Is Not a Queue:

A queue delivers each message to one consumer, and the next consumer gets the next message. A broadcast channel delivers each message to every consumer, and every consumer gets every message. The two are easy to confuse, because both move messages between tasks, and the difference is the whole point: a queue shares work, and a broadcast shares news.

Why the Socket Is Split

The socket is split into a sending half and a receiving half because two tasks use it at once: the send task writes, and the loop reads. A whole socket cannot be used by two tasks, because send and recv both need a mutable borrow, and two mutable borrows cannot exist at the same time. The split solves that by dividing the socket into two independent halves, each owned by one task. The sending half implements Sink, so it has send, and the receiving half implements Stream, so it has next. The split is the shape that makes the broadcast server possible, and it is covered in full on the splitting page.

A Richer Example With Names and Join Messages

A chat room is more than a pipe: each client has a name, and the room announces arrivals and departures. This version takes the name from the query string, such as /ws?name=ada, and prefixes every message with it:

src/main.rs
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Query, State,
    },
    response::Response,
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use serde::Deserialize;
use tokio::sync::broadcast;

#[derive(Clone)]
struct ChatState {
    tx: broadcast::Sender<String>,
}

#[derive(Debug, Deserialize)]
struct WsQuery {
    name: Option<String>,
}

async fn ws_handler(
    ws: WebSocketUpgrade,
    Query(query): Query<WsQuery>,
    State(state): State<ChatState>,
) -> Response {
    let name = query.name.unwrap_or_else(|| "guest".to_string());
    ws.on_upgrade(|socket| handle_socket(socket, state, name))
}

async fn handle_socket(socket: WebSocket, state: ChatState, name: String) {
    let (mut sender, mut receiver) = socket.split();
    let mut rx = state.tx.subscribe();
    let send_task = tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(msg) => {
                    if sender.send(Message::Text(msg.into())).await.is_err() {
                        break;
                    }
                }
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => break,
            }
        }
    });
    let tx = state.tx.clone();
    let _ = tx.send(format!("{name} joined the room"));
    while let Some(msg) = receiver.next().await {
        let Ok(msg) = msg else { break };
        if let Message::Text(text) = msg {
            let _ = tx.send(format!("{name}: {text}"));
        }
    }
    let _ = tx.send(format!("{name} left the room"));
    send_task.abort();
}

#[tokio::main]
async fn main() {
    let (tx, _rx) = broadcast::channel::<String>(16);
    let state = ChatState { tx };
    let app = Router::new()
        .route("/ws", get(ws_handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Query<WsQuery> is an extractor that parses the query string into the struct, and name is an Option<String>, because the client may not send a name. unwrap_or_else supplies guest when there is none. The join message goes into the channel before the loop starts, so everyone already in the room sees it. Each chat line is prefixed with the name, so a client receiving ada: hello knows who spoke. The leave message goes into the channel after the loop ends, so the room sees the departure. The send task is aborted after the leave message, because the leave message must be sent into the channel before the task stops, and the order matters: announce, then abort, never the other way around.

The Name Comes From the Client:

The name in this example is whatever the client puts in the query string, and a client can claim any name, including another user's. It is a display name for a learning example, not an identity. A real chat room takes the name from the authenticated user, which is the shape the auth headers page shows, and never trusts a name the client supplies.

Variations

Broadcasting binary instead of text

A channel can carry Bytes instead of String, and the loop forwards binary messages the same way:

src/main.rs
#[derive(Clone)]
struct BinState {
    tx: broadcast::Sender<bytes::Bytes>,
}

async fn handle_socket(socket: WebSocket, state: BinState) {
    let (mut sender, mut receiver) = socket.split();
    let mut rx = state.tx.subscribe();
    let send_task = tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(msg) => {
                    if sender.send(Message::Binary(msg)).await.is_err() {
                        break;
                    }
                }
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => break,
            }
        }
    });
    let tx = state.tx.clone();
    while let Some(msg) = receiver.next().await {
        let Ok(msg) = msg else { break };
        if let Message::Binary(data) = msg {
            let _ = tx.send(data);
        }
    }
    send_task.abort();
}

The only changes are the channel type and the message kind. The Bytes payload is shared cheaply, because cloning a Bytes shares its storage, so forwarding binary to many clients costs little. The text and binary channels are separate shapes, and a server that needs both runs two channels, one per kind.

Choosing the capacity

The capacity is the number in broadcast::channel::<String>(16), and it trades memory against forgiveness. A capacity of 16 holds 16 messages, which is enough when messages arrive one at a time and every receiver keeps up. A busy room where a burst of 50 messages can arrive at once needs a larger capacity, such as 256, so a slow receiver does not lag on every burst. A capacity that is too large wastes memory when the room is quiet, because the buffer is allocated up front. The right number comes from watching the lagged count in practice, and starting at 16 is reasonable for learning.

Sending only to others

A server that must not echo a message back to its sender can tag the message with the sender's id and have each send task skip its own:

#[derive(Clone)]
struct Tagged {
    from: usize,
    text: String,
}

The channel carries Tagged values, the loop tags each message with its connection id, and the send task compares msg.from with its own id and skips the match. The shape is a small change to the smallest version, and it is worth doing only when the client cannot filter its own messages. Most chat clients filter by name or by id themselves, so the server usually broadcasts to everyone and lets the client decide what to show.

Closing the channel on shutdown

When the server shuts down, it drops the sender, and every receiver's recv returns Closed, which ends every send task cleanly. The drop happens naturally when the state is dropped, so a graceful shutdown needs no extra code for the channel itself. The connections still need their close frames, which is the close frame page's shape, and the channel closing is what wakes the send tasks so they can finish.

A Plain Text Diagram of the Broadcast

A message from A travels through the channel to every connection:

client A sends Text("hello from A")
        |
        v
loop A reads it, tx.send puts it in the channel
        |
        v
channel delivers a copy to every receiver
        |
        +-- send task A --> socket A --> client A receives it
        |
        +-- send task B --> socket B --> client B receives it
        |
        +-- send task C --> socket C --> client C receives it

The sender's loop never talks to the other connections directly. It talks to the channel, and the channel talks to every send task. Adding a fourth client adds a fourth receiver and a fourth send task, and the loop that sends the message does not change at all.

Testing It

The test below connects two clients, has A send a message, and asserts both A and B receive it. It needs tokio-tungstenite as a dev-dependency:

Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
tests/broadcast_test.rs
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    response::Response,
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use tokio::sync::broadcast;
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientMessage};

#[derive(Clone)]
struct ChatState {
    tx: broadcast::Sender<String>,
}

async fn ws_handler(ws: WebSocketUpgrade, State(state): State<ChatState>) -> Response {
    ws.on_upgrade(|socket| handle_socket(socket, state))
}

async fn handle_socket(socket: WebSocket, state: ChatState) {
    let (mut sender, mut receiver) = socket.split();
    let mut rx = state.tx.subscribe();
    let send_task = tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(msg) => {
                    if sender.send(Message::Text(msg.into())).await.is_err() {
                        break;
                    }
                }
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => break,
            }
        }
    });
    let tx = state.tx.clone();
    while let Some(msg) = receiver.next().await {
        let Ok(msg) = msg else { break };
        if let Message::Text(text) = msg {
            let _ = tx.send(text.to_string());
        }
    }
    send_task.abort();
}

#[tokio::test]
async fn message_from_a_reaches_both_a_and_b() {
    let (tx, _rx) = broadcast::channel::<String>(16);
    let state = ChatState { tx };
    let app = Router::new()
        .route("/ws", get(ws_handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });
    let url = format!("ws://{addr}/ws");
    let (mut a, _) = connect_async(url.clone()).await.unwrap();
    let (mut b, _) = connect_async(url).await.unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    a.send(ClientMessage::Text("hello from A".into()))
        .await
        .unwrap();
    let msg_b = b.next().await.unwrap().unwrap();
    assert_eq!(msg_b, ClientMessage::Text("hello from A".into()));
    let msg_a = a.next().await.unwrap().unwrap();
    assert_eq!(msg_a, ClientMessage::Text("hello from A".into()));
    a.close(None).await.unwrap();
    b.close(None).await.unwrap();
}

Run it with:

cargo test --test broadcast_test
test message_from_a_reaches_both_a_and_b ... ok

The test connects A and B, waits 200 milliseconds so both subscriptions are in place, has A send, and asserts B receives the message and A receives its own broadcast. The short sleep matters: without it, A can send before B has subscribed, and B misses the message, which is correct channel behaviour and a flaky test. The sleep is a test-only wait, and a real client does not need it, because a real room tolerates a missed message at join time.

The Sleep in the Test Prevents a Race:

The 200 millisecond sleep after connecting is there because the test asserts on the very first message, and a message sent before B subscribes is lost to B by design. The sleep gives both connections time to subscribe before A speaks. A test that skips the sleep fails sometimes and passes sometimes, which is the worst kind of test failure to debug.

Common Beginner Mistakes

Sharing one receiver between connections

// Wrong - one receiver can only be in one task
let mut rx = state.tx.subscribe();

This line is correct when it runs once per connection, inside the callback. It is wrong when it runs once at startup and the same rx is shared between connections, because a receiver can only be used by one task, and the second connection to use it fails to compile with a move error, or receives messages meant for the first. The fix is to call subscribe inside the callback, so each connection gets its own receiver. One receiver per connection is the rule, and the subscription is part of the connection setup, not part of the server setup.

Forgetting to subscribe before the loop

// Wrong - the send task has no receiver to read from
async fn handle_socket(socket: WebSocket, state: ChatState) {
    let (mut sender, mut receiver) = socket.split();
    let send_task = tokio::spawn(async move {
        loop {
            // rx is missing, this does not compile
        }
    });
}

The send task needs a receiver, and the receiver must be created before the task is spawned, because the task moves it in. The fix is the let mut rx = state.tx.subscribe(); line before the spawn, as the working version shows. A connection without a subscription receives nothing, and a send task without a receiver does not compile, so the error points straight at the missing line.

Breaking the send task on Lagged

// Wrong - a slow client kills its own send task on the first lag
Err(broadcast::error::RecvError::Lagged(_)) => break,

A lagged receiver has missed messages, and breaking the task ends the connection for a client that only fell behind. The fix is continue, which skips the missed messages and waits for the next one. The lagged case is a normal event in a busy room, and the correct response is to rejoin at the newest message, not to give up. A server that breaks on lagged drops its slowest clients first, which is the opposite of what a chat room should do.

Sending into the channel with unwrap

// Wrong - send fails when no receivers are left, and that is normal
tx.send(text.to_string()).unwrap();

send returns an error when there are no receivers, which happens when the last other client left and only the sender remains, or when the sender is the only connection. Unwrapping that error panics the connection task for an event that is completely normal. The fix is let _ = tx.send(...), which ignores the result. A message with no listeners is not an error, it is a room with one person in it.

Forgetting to abort the send task

// Wrong - the send task waits on the channel after the client left
while let Some(msg) = receiver.next().await {
    let Ok(msg) = msg else { break };
    if let Message::Text(text) = msg {
        let _ = tx.send(text.to_string());
    }
}
// no abort here, the send task leaks

The send task waits on rx.recv(), and the channel never closes while the server runs, so the task waits forever after the connection ends. Each leaked task holds its sender and its receiver, and a server that leaks one task per connection runs out of memory as clients come and go. The fix is the send_task.abort() after the loop, which cancels the task at once. The abort is the last line of every broadcast callback, and forgetting it is the most common leak in a broadcast server.

Final Complete Example

Here is everything from this page put together: the channel, the subscription, the send task with its lagged handling, the receive loop, and the test that proves a message from A reaches both A and B.

src/main.rs
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    response::Response,
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use tokio::sync::broadcast;

#[derive(Clone)]
struct ChatState {
    tx: broadcast::Sender<String>,
}

async fn ws_handler(ws: WebSocketUpgrade, State(state): State<ChatState>) -> Response {
    ws.on_upgrade(|socket| handle_socket(socket, state))
}

async fn handle_socket(socket: WebSocket, state: ChatState) {
    let (mut sender, mut receiver) = socket.split();
    let mut rx = state.tx.subscribe();
    let send_task = tokio::spawn(async move {
        loop {
            match rx.recv().await {
                Ok(msg) => {
                    if sender.send(Message::Text(msg.into())).await.is_err() {
                        break;
                    }
                }
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => break,
            }
        }
    });
    let tx = state.tx.clone();
    while let Some(msg) = receiver.next().await {
        let Ok(msg) = msg else { break };
        if let Message::Text(text) = msg {
            let _ = tx.send(text.to_string());
        }
    }
    send_task.abort();
}

#[tokio::main]
async fn main() {
    let (tx, _rx) = broadcast::channel::<String>(16);
    let state = ChatState { tx };
    let app = Router::new()
        .route("/ws", get(ws_handler))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run the checks with these commands:

cargo check
cargo test --test broadcast_test
cargo run

Summary

A broadcast channel turns many separate connections into one room: a sender puts a message in once, every receiver takes a copy out, and the send task in each connection writes its copy to its client. The live run proved it with two clients, where B received what only A sent, and A received its own message back as well. The discipline to carry forward is the pair of lines that make the shape safe: subscribe once per connection, and abort the send task when the connection ends, with the lagged case continuing instead of breaking, so a slow client rejoins instead of being dropped. The next page takes the room and locks its door, checking who may enter before the connection is upgraded at all.