WebSocket concurrent connections
Learn how Axum runs each WebSocket connection in its own task, why the handler must never block, and how to share state safely between connections
A WebSocket server never serves one client. It serves many at once, each with its own connection, its own loop, and its own task. A task is a lightweight unit of work that Tokio schedules, and on_upgrade spawns one for every connection, so a slow client cannot stall a fast one. The handler itself returns immediately after the upgrade, and the connection lives on in the task. The rule that makes this work is simple: never block the handler, and never block the loop with work that belongs in a spawned task.
Where This Fits
The previous page built one echo server and proved it with one client. This page connects many clients at once and proves they do not wait for each other. The echo loop does not change. What changes is the understanding of where it runs: one task per connection, all of them alive at the same time, sharing the server.
Think of a restaurant with one waiter per table. Each waiter takes orders, carries food, and clears plates for their own table, and a slow table that takes an hour over dessert does not stop the other tables from eating. The handler is the host who seats each party and sends a waiter over. The host never waits at a table, and the waiters never wait on each other.
The Smallest Working Version
This server is the echo server from the previous page, unchanged. The concurrency is not in the code, it is in how Axum runs it: one task per connection.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
use axum::{
extract::ws::{WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if socket.send(msg).await.is_err() {
return;
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", get(ws_handler));
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 five clients at the same time, each sending its own message, against this exact server in the verification project:
client: handshake status 101 Switching Protocols
client: handshake status 101 Switching Protocols
client: handshake status 101 Switching Protocols
client: handshake status 101 Switching Protocols
client: handshake status 101 Switching Protocols
client 2 received: Text(Utf8Bytes(b"hello from client 2"))
client 3 received: Text(Utf8Bytes(b"hello from client 3"))
client 1 received: Text(Utf8Bytes(b"hello from client 1"))
client 0 received: Text(Utf8Bytes(b"hello from client 0"))
client 4 received: Text(Utf8Bytes(b"hello from client 4"))
multi: all 5 clients echoed
Five handshakes, five echoes, each client receiving its own message and no one else's. The order of the replies is not the order of the clients, because the tasks run in parallel and whichever finishes first prints first. That disorder is the proof: the connections ran at the same time, not one after another.
Working Setup:
If every client receives its own echo, and the replies arrive in a mixed order, the connections are running concurrently. If the replies always arrive in strict client order, the server is somehow serializing them, and the handler is the place to look.
Understanding Where Each Connection Runs
The chain has three links, and each one matters.
on_upgrade spawns the task
on_upgrade does not run the callback in the handler. It spawns it in a background task with tokio::spawn, returns the 101 response, and the handler finishes. The Axum 0.8.9 source does this directly: the callback is moved into a tokio::spawn(async move { ... }) block, and the response is built and returned separately. That spawn is why the handler returns in microseconds even though the connection may stay open for hours, and it is why each connection gets its own task without any code in the handler asking for one.
The task lives until the loop returns
The spawned task runs the callback, which runs the loop, and the task ends when the callback returns. The socket is owned by the task, the loop borrows it, and nothing outside the task can touch it. When the client leaves, recv returns None or an error, the callback returns, the task ends, and Tokio cleans it up. There is no handle to the task, no list of tasks, and no manual cleanup, because the task's lifetime is the connection's lifetime.
The handler must not block
The handler runs on a Tokio worker thread, and a handler that blocks that thread stalls every other connection the thread serves. The handler in the smallest version does nothing but call on_upgrade and return, which is the whole discipline: configure, upgrade, return. Anything slow, a database call, a sleep, or a long computation, belongs inside the callback, where it runs in the connection's own task and stalls only that connection, or in a task spawned from the callback, where it stalls nothing at all.
The Concept Behind One Task Per Connection
A WebSocket connection is a long-lived conversation, and a server that handled connections one at a time would serve exactly one client. The task-per-connection model gives each conversation its own worker, and Tokio schedules thousands of such workers across a few operating system threads. A task that waits on recv costs nothing while it waits: it yields the thread to another task, and Tokio wakes it when a message arrives. A task that works, such as formatting a reply, uses the thread briefly and yields again at the next await. The model scales because waiting is free and working is brief, and it breaks only when a task works without ever awaiting, which is what blocking means.
A Slow Client Must Not Stall a Fast One
The claim that connections are independent is easy to state and worth proving. This server answers immediately, except for messages that start with slow:, which it answers after a three-second sleep. Two clients connect at the same time: the first sends a slow message, and the second sends a fast message a moment later. If the connections are independent, the fast client gets its echo in milliseconds while the slow client is still waiting.
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if let Message::Text(text) = msg {
if let Some(rest) = text.as_str().strip_prefix("slow:") {
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
let reply = format!("slow reply: {rest}");
if socket.send(Message::Text(reply.into())).await.is_err() {
return;
}
} else if socket.send(Message::Text(text)).await.is_err() {
return;
}
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/ws", get(ws_handler));
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();
}
The live run of this exact server, from the verification project, with the slow client starting first and the fast client starting 0.3 seconds later:
slow client A starts at 08:51:22.154432224
fast client B starts at 08:51:22.462255628
client received: Text(Utf8Bytes(b"fast hello"))
fast client B done at 08:51:22.477280070
slow client A log: client received: Text(Utf8Bytes(b"slow reply: big job"))
The fast client finished at 08:51:22.477, about 15 milliseconds after it started, while the slow client's three-second sleep was still running. The slow reply arrived about three seconds after the slow client started, as expected. The two connections never waited for each other, because each one runs in its own task, and the sleep in one task yields the thread to the other.
tokio sleep Yields, Thread sleep Blocks:
The sleep in this example is tokio::time::sleep, which pauses only the task that calls it and lets other tasks run. A std::thread::sleep in the same place would block the whole worker thread for three seconds, and every connection on that thread would stall with it. The two sleeps look similar and behave very differently, and the async one is the only correct choice inside a handler or a socket loop.
Why the Handler Must Not Block
Blocking means running code that never yields to the runtime. A std::thread::sleep, a long loop with no await, or a synchronous file read all block the worker thread they run on, and Tokio has only a few worker threads, one per CPU core by default. A blocked thread serves no other task until the blocking code finishes, so a handler that blocks for three seconds stalls every connection on that thread for three seconds. The symptom is a server that works fine with one client and freezes with many, and the cause is always a blocking call somewhere in the request path.
The fix has three forms, and the right one depends on the work. Work that can wait goes in a spawned task, with tokio::spawn, so the handler returns at once. Work that is asynchronous, such as a database query or a sleep, uses the async form, tokio::time::sleep or an async client, so the task yields while it waits. Work that is genuinely blocking and cannot be made async, such as heavy computation, goes in tokio::task::spawn_blocking, which runs it on a separate thread pool built for blocking work. The three forms cover every case, and none of them is "block the handler and hope".
Spawning Extra Work Per Connection With tokio spawn
Sometimes a connection needs two things at once: reading messages and doing something else, such as sending a periodic update. The socket cannot do both in one loop, so the extra work goes in a task spawned from the callback. This example spawns a task that sends a tick message every five seconds, while the loop keeps echoing:
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
use futures_util::{sink::SinkExt, stream::StreamExt};
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
let tick_task = tokio::spawn(async move {
let mut ticker = tokio::time::interval(std::time::Duration::from_secs(5));
loop {
ticker.tick().await;
if sender.send(Message::text("tick")).await.is_err() {
break;
}
}
});
while let Some(msg) = receiver.next().await {
let Ok(msg) = msg else { break };
println!("received: {msg:?}");
}
tick_task.abort();
println!("connection ended, tick task stopped");
}
socket.split() divides the socket into a sending half and a receiving half, so the two tasks can use them independently. The tick task owns the sender, sends tick every five seconds, and stops when the send fails, which means the client is gone. The loop owns the receiver, prints each message, and breaks when the stream ends. tick_task.abort() cancels the tick task when the loop ends, because the tick task would otherwise keep running after the connection is over, sending into a closed socket forever. The abort is the cleanup: every task spawned per connection must be stopped when the connection ends, or it leaks.
An Aborted Task Is a Leaked Task:
A task spawned from a callback that is never aborted or awaited keeps running after the connection ends. It holds its sender, its timer, and its memory, and a server that leaks one task per connection runs out of memory as clients come and go. Always end the spawned task when the loop ends, with abort, or by letting the task end on its own when its send fails.
Sharing State Between Connections
Connections share state through a value the handler passes into the callback, usually with State. A connection counter is the smallest shared state, and it shows the pattern: an Arc around an AtomicUsize, cloned into each callback, incremented on connect and decremented on disconnect.
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use axum::{
extract::{
ws::{WebSocket, WebSocketUpgrade},
State,
},
response::Response,
routing::get,
Router,
};
#[derive(Clone)]
struct AppState {
connections: Arc<AtomicUsize>,
}
async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> Response {
ws.on_upgrade(|socket| handle_socket(socket, state))
}
async fn handle_socket(mut socket: WebSocket, state: AppState) {
let count = state.connections.fetch_add(1, Ordering::SeqCst) + 1;
println!("client connected, total: {count}");
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { break };
if socket.send(msg).await.is_err() {
break;
}
}
let count = state.connections.fetch_sub(1, Ordering::SeqCst) - 1;
println!("client left, total: {count}");
}
#[tokio::main]
async fn main() {
let state = AppState {
connections: Arc::new(AtomicUsize::new(0)),
};
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();
}
Arc is a reference-counted pointer that lets many tasks share one value, and AtomicUsize is a counter that can be changed safely from many tasks at once, without a lock. fetch_add adds one and returns the old value, so adding one to the result gives the new total. fetch_sub subtracts one on disconnect. Ordering::SeqCst is the strictest memory ordering, which means every task sees the updates in the same order, and it is the safe default while learning. The state is Clone, because Axum clones it into each handler call, and the clone shares the same counter through the Arc. Five clients connecting at once would print totals 1 through 5 in some order, and five disconnecting would print the counts back down to 0.
Variations
Limiting the number of connections
A server that must cap its load can refuse new connections when the counter reaches a limit, by checking the count before the upgrade:
async fn ws_handler(
ws: WebSocketUpgrade,
State(state): State<AppState>,
) -> Result<Response, (axum::http::StatusCode, &'static str)> {
let count = state.connections.load(Ordering::SeqCst);
if count >= 100 {
return Err((axum::http::StatusCode::SERVICE_UNAVAILABLE, "server full"));
}
Ok(ws.on_upgrade(|socket| handle_socket(socket, state)))
}
The handler returns a Result, and the error arm answers 503 Service Unavailable with a plain message. The check happens before on_upgrade, so a refused client never becomes a connection and never takes a task. The limit of 100 is an example: a real limit depends on the server's memory and the work each connection does. The count can drift by one under heavy load, because two connections can read the count at the same moment, and a strict cap needs a semaphore instead of a counter, which is a more advanced shape.
Giving each connection an id
A connection id makes logs readable, because every line can say which connection it belongs to. The counter is the id source, and the callback takes it as an argument:
async fn handle_socket(mut socket: WebSocket, state: AppState) {
let id = state.connections.fetch_add(1, Ordering::SeqCst) + 1;
println!("[{id}] connected");
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { break };
println!("[{id}] received: {msg:?}");
if socket.send(msg).await.is_err() {
break;
}
}
println!("[{id}] left");
}
The id is assigned once, when the connection opens, and it stays with the connection for its whole life. Two connections with ids 3 and 7 produce interleaved log lines that are still easy to follow, because each line carries its id. The id is not reused after disconnect, so the numbers only grow, which is fine for logging.
Moving slow work into spawn_blocking
Work that cannot be made async, such as a heavy computation, goes in spawn_blocking, which runs it on a thread pool that exists for blocking work:
let result = tokio::task::spawn_blocking(|| {
let mut sum: u64 = 0;
for i in 0..10_000_000 {
sum += i;
}
sum
})
.await
.unwrap();
println!("computed: {result}");
The closure runs on a blocking thread, the await waits for it without blocking the worker, and the result arrives when the computation finishes. The loop inside the closure has no await, and that is fine, because it runs on a thread where blocking is allowed. The pattern is the escape hatch for work that cannot yield, and it keeps the worker threads free for connections.
A Plain Text Diagram of Concurrent Connections
Each connection is a task, and the tasks share nothing but the state:
client A connects --> on_upgrade spawns task A --> loop A reads and writes
client B connects --> on_upgrade spawns task B --> loop B reads and writes
client C connects --> on_upgrade spawns task C --> loop C reads and writes
|
v
all three loops run at once, sharing only AppState
|
v
client A leaves --> task A ends, counter drops by one
client B and C keep running, unaffected
A task ending changes nothing for the others. The server's work is the sum of the tasks, and the handler's work is only the spawning.
Testing It
The test below connects five clients at once, has each one send its own message, and asserts each receives its own echo. It needs tokio-tungstenite as a dev-dependency:
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
Router,
};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientMessage};
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle_socket)
}
async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
if socket.send(msg).await.is_err() {
return;
}
}
}
#[tokio::test]
async fn five_clients_echo_at_the_same_time() {
let app = Router::new().route("/ws", get(ws_handler));
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 tasks = Vec::new();
for i in 0..5 {
let url = url.clone();
tasks.push(tokio::spawn(async move {
let (mut ws, response) = connect_async(url).await.unwrap();
assert_eq!(response.status(), 101);
let text = format!("hello from client {i}");
ws.send(ClientMessage::Text(text.clone().into()))
.await
.unwrap();
let msg = ws.next().await.unwrap().unwrap();
assert_eq!(msg, ClientMessage::Text(text.into()));
ws.close(None).await.unwrap();
}));
}
for task in tasks {
task.await.unwrap();
}
}
Run it with:
cargo test --test concurrent_test
test five_clients_echo_at_the_same_time ... ok
The test spawns five client tasks, each connecting and echoing independently, and awaits them all. The assertion inside each task checks that the client received its own message, which proves the server did not mix the connections up. The test mirrors the live five-client run from the start of this page.
Common Beginner Mistakes
Blocking the handler with a sleep
// Wrong - the worker thread sleeps, and every connection on it stalls
async fn ws_handler(ws: WebSocketUpgrade) -> Response {
std::thread::sleep(std::time::Duration::from_secs(5));
ws.on_upgrade(handle_socket)
}
std::thread::sleep blocks the worker thread for five seconds, and every connection that thread serves waits with it. The fix is to move the wait into the callback, where it stalls only that connection, or to use tokio::time::sleep, which yields. The handler should never contain a blocking call of any kind.
Doing heavy work in the loop without yielding
// Wrong - a long loop with no await starves the other tasks
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { return };
let mut sum: u64 = 0;
for i in 0..100_000_000 {
sum += i;
}
println!("sum: {sum}");
let _ = socket.send(msg).await;
}
The computation loop has no await inside it, so the task never yields, and the worker thread runs the loop to completion before any other task gets a turn. A short computation is harmless, and a long one stalls the server. The fix is spawn_blocking for the computation, or breaking the work into chunks with an await between them, such as a tokio::task::yield_now().await inside the loop.
Sharing state with a plain value instead of Arc
// Wrong - a plain counter cannot be shared between tasks
#[derive(Clone)]
struct AppState {
connections: usize,
}
A plain usize in a cloned state gives each connection its own copy, so the counts never agree, and two connections incrementing at once race. The fix is the Arc<AtomicUsize> from the state example, which shares one counter and updates it atomically. Any state that changes needs shared ownership and atomic updates, or a lock, and the atomic counter is the simplest correct form.
Forgetting to abort a spawned task
// Wrong - the tick task keeps running after the connection ends
async fn handle_socket(socket: WebSocket) {
let (mut sender, mut receiver) = socket.split();
tokio::spawn(async move {
loop {
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
if sender.send(Message::text("tick")).await.is_err() {
break;
}
}
});
while let Some(msg) = receiver.next().await {
let _ = msg;
}
}
The tick task in this version stops on its own when the send fails, which happens when the client is gone, so it does end by itself. The real mistake is the version where the spawned task never touches the socket, such as a task that only reads from a channel, and so never learns the connection ended. The fix is to hold the task's handle and call abort when the loop ends, as the tick example does, or to give the task a shutdown signal it checks. A task that outlives its connection is a leak, and leaks add up.
Awaiting a spawned task that never ends
// Wrong - awaiting the tick task blocks the callback forever
let tick_task = tokio::spawn(async move { /* ... */ });
tick_task.await.unwrap();
Awaiting a task that runs forever waits forever, and the callback never reaches its loop. The fix is to run the spawned task in the background and the loop in the foreground, as the tick example does, and to abort the task when the loop ends. Spawned work runs beside the loop, never in front of it.
Final Complete Example
Here is everything from this page put together: the echo loop, the connection counter with shared state, and the test that proves five clients echo at once.
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use axum::{
extract::{
ws::{WebSocket, WebSocketUpgrade},
State,
},
response::Response,
routing::get,
Router,
};
#[derive(Clone)]
struct AppState {
connections: Arc<AtomicUsize>,
}
async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> Response {
ws.on_upgrade(|socket| handle_socket(socket, state))
}
async fn handle_socket(mut socket: WebSocket, state: AppState) {
let count = state.connections.fetch_add(1, Ordering::SeqCst) + 1;
println!("client connected, total: {count}");
while let Some(msg) = socket.recv().await {
let Ok(msg) = msg else { break };
if socket.send(msg).await.is_err() {
break;
}
}
let count = state.connections.fetch_sub(1, Ordering::SeqCst) - 1;
println!("client left, total: {count}");
}
#[tokio::main]
async fn main() {
let state = AppState {
connections: Arc::new(AtomicUsize::new(0)),
};
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 concurrent_test
cargo run
Summary
Concurrency in a WebSocket server comes from the spawn inside on_upgrade: one task per connection, each with its own loop, sharing only the state the handler passes in. The live runs proved the independence twice, five clients echoing at once in mixed order, and a fast client answered in 15 milliseconds while a slow client's three-second sleep was still running. The discipline to carry forward is to keep the handler thin and the loop yielding: configure and return in the handler, await in the loop, spawn what must run beside it, and abort what must end with it. The next page takes the sharing one step further, and turns many separate connections into one room where a message from any client reaches every client.