Fit for WebSocket Backends

Why Axum is a strong choice for building WebSocket backends, with a complete beginner-friendly echo server example and detailed explanation of the upgrade process, message handling, and common pitfalls.

WebSockets solve a problem that plain HTTP cannot. When you load a normal web page, the browser sends a request, the server sends a response, and the connection ends. If you want live updates - like a chat message appearing without refreshing, a stock ticker, or a multiplayer game state - repeatedly asking the server "anything new?" gets slow and wasteful very quickly. WebSockets keep a single connection open so both the browser and the server can send data in either direction at any time. Axum is exceptionally well suited for building backends that rely on WebSockets, and this page explains exactly why, then walks you through building a working WebSocket server from scratch.

What Is a WebSocket and How Is It Different From HTTP

Think of normal HTTP as sending letters through the post office. You write a letter (the request), put it in an envelope, send it off, and eventually receive a reply (the response). Every exchange requires a new envelope and a new trip. If you want to have a conversation, you end up sending dozens of letters back and forth.

A WebSocket is more like a phone call. You dial once, the line stays open, and then both people can talk and listen at the same time without hanging up. The initial call setup looks a little like an HTTP request - the client asks to "upgrade" the connection - but after that, the connection becomes a persistent two-way channel. Both sides can send messages whenever they need to, and the other side receives them immediately.

This difference matters enormously for certain kinds of applications:

  • Chat applications - a message typed by one user appears on everyone else's screen instantly, without a page reload.
  • Live dashboards - server metrics, stock prices, or sports scores update as they happen.
  • Multiplayer games - player positions and actions are shared in real time with low latency.
  • Collaborative tools - multiple people editing the same document see each other's changes live.
  • Notification systems - a server can push an alert to a browser the moment an event occurs.

In all these cases, the server needs to hold many open connections at once and read and write to them as data becomes available. That is a fundamentally different workload from traditional request-response HTTP, and it requires a backend framework that understands async I/O deeply. Axum does.

Why Axum Fits WebSocket Backends Naturally

Axum is not the only Rust web framework that can do WebSockets, but its design choices line up with the demands of long-lived, bidirectional connections in a way that makes development feel direct and predictable. Here are the concrete reasons.

It Is Built on Tokio

Axum runs on Tokio, which is the most widely used async runtime for Rust. WebSockets are all about managing many simultaneous connections without blocking. Tokio's event loop can juggle thousands of connections on a small number of OS threads by using non-blocking I/O - the same mechanism that makes it excellent for high-concurrency network services. Because Axum inherits Tokio's runtime, a WebSocket handler in Axum is just another async task that Tokio schedules cooperatively. You get the efficiency of an event-driven system without having to manage threads manually.

For a beginner, the important idea is that your WebSocket handler runs as an async function. It can .await incoming messages and outgoing sends without freezing the whole server. While one connection is waiting for a message, other connections continue to be processed.

The WebSocket Extractor Makes Upgrading Painless

In Axum, handling a WebSocket request does not require manually parsing HTTP headers or writing raw upgrade logic. You simply add a parameter of type WebSocketUpgrade to your handler. Axum's type-driven extractor system sees that parameter, recognizes that the client requested a WebSocket connection, and prepares the upgrade. You then call on_upgrade to get a WebSocket object that you can use to read and write messages.

This is the same extractor pattern used for JSON bodies, query parameters, and path segments. It means the compiler checks that your handler signature is correct, and you get a clear error message if you forget something.

Async Streams Feel at Home

WebSockets are a stream of messages over time. Rust's async ecosystem has first-class support for working with streams (think while let Some(msg) = socket.recv().await). Axum's WebSocket type integrates naturally with this pattern. You do not need callback functions, event listeners, or manual polling. You write a loop that awaits the next message, handle it, and continue. The code reads like a straightforward sequential process even though it involves asynchronous I/O.

Tower Middleware Still Applies

Axum is built on Tower, which means you can apply middleware - logging, authentication, rate limiting, compression - to your WebSocket routes just like any other route. The initial HTTP request that initiates the WebSocket handshake goes through the same middleware stack, so you can reject unauthenticated upgrade attempts before the connection is ever established. After the upgrade, the WebSocket is managed by your handler, but the door it came through is the same front door every other request uses.

How the WebSocket Upgrade Happens in Axum

Before writing code, it helps to understand the mechanics of the upgrade. A WebSocket connection starts as an ordinary HTTP GET request with a few special headers. The browser (or any WebSocket client) sends:

  • Connection: Upgrade
  • Upgrade: websocket
  • Sec-WebSocket-Key: some-random-string
  • Sec-WebSocket-Version: 13

If the server agrees, it responds with status code 101 (Switching Protocols) and a Sec-WebSocket-Accept header. At that moment, the HTTP connection stops being HTTP and becomes a raw TCP connection carrying WebSocket frames. The client and server then exchange messages asynchronously.

Axum hides most of this handshake from you. Here is the flow when you use the WebSocketUpgrade extractor:

  1. The client sends the upgrade request to a route.
  2. Axum's extractor checks that the request is a valid WebSocket upgrade and captures the necessary information.
  3. Your handler returns a response that tells the client the upgrade is accepted.
  4. The on_upgrade callback receives a WebSocket object once the handshake completes.
  5. Inside the callback, you have full control: read messages, send messages, and close the connection when done.

This separation - extractor first, then on_upgrade - keeps your route handler simple and defers the actual connection handling to a future that runs for the lifetime of the WebSocket.

The Upgrade Is Not Instantaneous:

The on_upgrade callback is not executed until after the HTTP response has been sent back to the client. That means you should not try to send WebSocket messages inside the route handler itself; you must do it inside the closure passed to on_upgrade.

Your First WebSocket Echo Server

Let us build the smallest possible WebSocket backend with Axum. The server accepts a WebSocket connection at the path /ws and echoes back every text or binary message it receives. This is the "Hello, World!" of WebSockets and gives you a foundation for more interesting behavior.

Complete Code

Create a new Rust project and add the dependencies. Make sure your Cargo.toml has axum and tokio with the full feature enabled.

# Cargo.toml
[package]
name = "websocket-echo"
version = "0.1.0"
edition = "2021"
[dependencies]
# `ws` is NOT a default axum feature: without `features = ["ws"]` the
# `axum::extract::ws` module does not exist and this example does not compile.
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }

Now replace src/main.rs with the following:

// src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::IntoResponse,
    routing::get,
    Router,
};
async fn websocket_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_socket(socket))
}
async fn handle_socket(mut socket: WebSocket) {
    while let Some(Ok(msg)) = socket.recv().await {
        match msg {
            Message::Text(text) => {
                if socket.send(Message::Text(text)).await.is_err() {
                    // The client disconnected; stop the loop.
                    break;
                }
            }
            Message::Binary(bin) => {
                if socket.send(Message::Binary(bin)).await.is_err() {
                    break;
                }
            }
            Message::Ping(payload) => {
                // Answer a ping with a pong carrying the same payload.
                if socket.send(Message::Pong(payload)).await.is_err() {
                    break;
                }
            }
            Message::Pong(_) => {}
            Message::Close(_) => break,
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/ws", get(websocket_handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("WebSocket echo server listening on ws://localhost:3000/ws");
    axum::serve(listener, app).await.unwrap();
}

Run the server with cargo run. To test it, you need a WebSocket client. If you have websocat installed, you can connect with websocat ws://localhost:3000/ws, type a message, and see it echoed back. In a browser, you can use the JavaScript console:

const socket = new WebSocket("ws://localhost:3000/ws");
socket.onopen = () => socket.send("Hello from browser");
socket.onmessage = (event) => console.log("Received:", event.data);

When you send a message, the server receives it and sends the identical message back. You will see it appear in the client's console.

Walking Through the Code Step by Step

Let us break down exactly what happens, because a few details are easy to miss on a first read.

The route is defined with get(websocket_handler). The handler takes a WebSocketUpgrade extractor. Axum knows that when a request with the proper WebSocket headers arrives at /ws, it should call this function.

Inside websocket_handler, we call ws.on_upgrade(...). This method returns a response that Axum will send to the client to confirm the upgrade. The closure we pass - move |socket| handle_socket(socket) - will be executed later, after the handshake is complete. Notice the move keyword: it moves ownership of the closure into the future that runs on the Tokio runtime. That is necessary because the handler function returns before the connection is actually established.

handle_socket receives a WebSocket object, which we bind as mut socket because we need to call methods that change its internal state. The loop while let Some(Ok(msg)) = socket.recv().await does three things each iteration:

  1. socket.recv().await waits asynchronously for the next incoming message. If the connection closes cleanly, it returns None and the loop ends.
  2. Ok(msg) destructures the result. If an error occurs, the pattern fails, and the loop ends. Errors usually mean the connection dropped or a protocol violation.
  3. msg is the actual WebSocket message.

Inside the match, we handle each message type. Message::Text contains a Utf8Bytes (or String) that we send back unchanged. Message::Binary contains raw bytes, also sent back unchanged. Message::Close tells us the client wants to close; we break out of the loop. There is no catch-all arm: Ping is answered with a Pong carrying the same payload, and a Pong (the reply to a ping we sent) is ignored. If you leave Ping unhandled, the connection still works - the underlying tungstenite layer answers pings itself - but answering explicitly makes the keep-alive behaviour visible in your code instead of hidden in a library.

When we send a message with socket.send(...).await, we check the result. If sending fails, the client has likely disconnected, so we break. This is important: if you ignore send errors and keep looping, you may spin forever on a dead connection.

Echo Server Works:

If you see your message printed back in the client after starting this server, you have successfully built a WebSocket backend with Axum. The core pattern - extract WebSocketUpgrade, call on_upgrade, then loop over recv and send - is the same pattern you will use for nearly every WebSocket feature you build.

Handling Different Kinds of WebSocket Messages

The Message enum is your window into what the client sends. Understanding each variant helps you write robust handlers.

  • Text - UTF-8 encoded text data. Use this for JSON payloads or plain messages.
  • Binary - raw bytes. Useful for file transfers, serialized binary formats, or compressed data.
  • Ping - a control frame asking if the other side is still alive. Axum automatically responds with a Pong when you use the default WebSocket type, so you rarely need to handle this yourself.
  • Pong - a response to a Ping. If you send a Ping manually, you will receive a Pong.
  • Close - the client or server wants to close the connection. Always handle this and break out of your loop, otherwise you risk leaking the task.

Here is a slightly more interesting handler that converts text messages to uppercase and ignores binary messages entirely:

async fn handle_socket(mut socket: WebSocket) {
    while let Some(Ok(msg)) = socket.recv().await {
        match msg {
            Message::Text(text) => {
                let uppercased = text.to_uppercase();
                if socket.send(Message::Text(uppercased.into())).await.is_err() {
                    break;
                }
            }
            Message::Close(_) => break,
            _ => {}
        }
    }
}

The text variable inside Message::Text is of type Utf8Bytes (in Axum 0.8). Calling to_uppercase() gives a String, which we convert back into a Utf8Bytes with .into() before sending. If you only care about text, ignoring binary messages is perfectly fine.

You might also want to send your own Ping frames to keep the connection alive if your application has long idle periods. While Axum automatically responds to incoming Pings, it does not automatically send them. You can send one manually:

if socket.send(Message::Ping(vec![].into())).await.is_err() {
    return; // the client is gone; stop the handler
}

The bytes argument is the ping payload; an empty payload is acceptable.

Sending Messages From the Server Without a Client Request

The echo pattern only sends a message after receiving one. But many real-world WebSockets require the server to push data proactively - for example, when a stock price changes or a new chat message arrives from another user. The natural way to do that in one handler is tokio::select!: wait, in a single task, for either the next incoming message or the next thing to push, and handle whichever arrives first.

Here is an example that sends the current server time every second, while also still echoing any text messages from the client. It needs no extra crates - just tokio::select! and tokio::time::interval:

use axum::extract::ws::{Message, WebSocket};
use tokio::time::{interval, Duration};

async fn handle_socket(mut socket: WebSocket) {
    let mut ticker = interval(Duration::from_secs(1));
    loop {
        tokio::select! {
            // Push: once a second, send the server time.
            _ = ticker.tick() => {
                let now = format!("Server time: {:?}", std::time::SystemTime::now());
                if socket.send(Message::Text(now.into())).await.is_err() {
                    break;
                }
            }
            // Pull: echo back any text message from the client.
            msg = socket.recv() => {
                match msg {
                    Some(Ok(Message::Text(text))) => {
                        if socket.send(Message::Text(text)).await.is_err() {
                            break;
                        }
                    }
                    Some(Ok(Message::Ping(payload))) => {
                        if socket.send(Message::Pong(payload)).await.is_err() {
                            break;
                        }
                    }
                    Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
                    Some(Ok(_)) => {}
                }
            }
        }
    }
}

Why one task and select!, rather than splitting the socket into a sender and a receiver task? Splitting is possible - socket.split() gives you a sender half and a receiver half - but it is easy to get wrong: if you move the sender into one spawned task, you cannot also use it in the other task, because the value has been moved. The code that did that does not compile (sender used after being moved). With select! there is only one owner of the socket, no shared state, and no sibling task to abort when the client disconnects: when recv() returns None or an error, the loop breaks and the ticker is dropped with it.

If you genuinely need two tasks - for example, one task reading from a broadcast channel and another reading from the socket - split the socket and share the sender half behind an Arc<tokio::sync::Mutex<_>>, or send outbound messages through an mpsc channel that a single writer task drains. Either way, make sure that when one side ends, the other side is aborted: keep both JoinHandles, wait for the first to finish with tokio::select!, and call abort() on the survivor.

Ping, pong, and closing gracefully

Ping and pong are the WebSocket keep-alive mechanism. A peer that has not heard from you can send a Ping frame; you answer with a Pong carrying the same payload, which proves the connection is still alive. Axum's Message enum has both variants (Message::Ping(Bytes) and Message::Pong(Bytes)), and the payload must be under 125 bytes. You can also send a ping yourself when a connection has been idle for a while:

// Send a ping; the client answers with a pong. An empty payload is fine.
if socket.send(Message::Ping(vec![].into())).await.is_err() {
    return; // the client is gone; stop the handler
}

To close a connection gracefully, send a Close frame and then stop reading - do not just drop the socket mid-conversation if the client is expecting a goodbye:

use axum::extract::ws::CloseFrame;
if socket
    .send(Message::Close(Some(CloseFrame {
        code: 1000,
        reason: "done".into(),
    })))
    .await
    .is_err()
{
    // The client is already gone; nothing more to do.
}

Code 1000 is the normal-closure code. After you send it, break out of your loop; the client's own close reply (or the dropped connection) ends the task. And always handle the Message::Close you receive the same way: break out of the loop instead of waiting for more messages on a connection the client has already closed.

Message-size limits

There is a message-size limit, and it matters for production. WebSocketUpgrade defaults to a maximum message size of 64 MB and a maximum frame size of 16 MB - a message larger than that is rejected before your handler sees it. You can lower (or raise) the limit on the upgrade extractor, before calling on_upgrade:

use axum::extract::ws::WebSocketUpgrade;

async fn websocket_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
    ws.max_message_size(1024 * 1024) // 1 MB, instead of the 64 MB default
        .max_frame_size(256 * 1024) // 256 KB per frame, instead of 16 MB
        .on_upgrade(move |socket| handle_socket(socket))
}

Choose the limit from what your application actually sends: a chat message needs kilobytes, not megabytes. A low limit is cheap insurance against a buggy or malicious client filling your server's memory with one huge message.

Common Mistakes When Building WebSocket Backends

Even with Axum's clean design, there are a few traps that catch beginners.

Forgetting to Handle the Close Message

If your match on Message does not include a Message::Close(_) arm that breaks out of the loop, your handler will keep waiting for messages on a connection that the client has already closed. recv().await will eventually return an error or None, so it is not infinite, but it wastes time and can hold resources longer than necessary. Always break on Close.

Blocking Inside the Async Loop

Do not call blocking functions - like std::thread::sleep, heavy file I/O, or CPU-intensive computation - directly inside your WebSocket handler loop. Because Tokio uses a small number of OS threads, blocking one of those threads stalls every task on that thread. If you must perform a blocking operation, use tokio::task::spawn_blocking.

Blocking the Runtime Freezes All Connections:

The most severe mistake in an async WebSocket server is blocking the Tokio runtime. A single std::thread::sleep(Duration::from_secs(10)) inside a handler does not just delay that one connection; it can freeze the entire server. Always use asynchronous timers (tokio::time::sleep) and offload CPU-bound work.

Ignoring Send Errors

When you call socket.send(...).await, the result tells you whether the message was actually written. If the client has disconnected, sending fails. If you ignore the error and keep looping, you may repeatedly try to send to a closed socket, generating warnings and wasting CPU. Always check the result and break on error.

Not Setting a Maximum Message Size

Axum does impose a limit: the default maximum message size is 64 MB (and 16 MB per frame). That is far larger than any chat message or notification needs, so a malicious or buggy client could still send a huge message and consume a lot of memory before the limit bites. Lower it with the max_message_size method on WebSocketUpgrade before calling on_upgrade. For production, choose a sensible limit based on your application - kilobytes for chat, not megabytes.

Assuming WebSockets Are Always Available

Some corporate networks and proxies block WebSocket upgrade requests. Always provide a fallback - such as HTTP long-polling or Server-Sent Events - if your users might be behind such restrictions. Axum makes it easy to serve both from the same application, but the fallback logic belongs to your application design, not the framework.

When WebSockets Might Not Be the Right Fit

WebSockets are powerful but not always the best tool. If your client only needs occasional updates and you do not mind a short delay, polling a normal HTTP endpoint every few seconds is simpler to implement, easier to cache, and works through more proxies. If the server needs to push updates but the client never sends anything back, Server-Sent Events (SSE) provide a one-way stream over plain HTTP and are simpler than WebSockets. Axum supports both, so you can choose the right tool for the job.

For true bidirectional, low-latency communication with many concurrent connections, WebSockets remain the standard choice, and Axum's design makes them a first-class citizen rather than an afterthought.

Summary

Axum earns its reputation as a great framework for WebSocket backends because its core building blocks - Tokio's async runtime, Tower's middleware layer, and the type-driven extractor system - combine to make long-lived, bidirectional connections straightforward to implement and efficient to run. The WebSocketUpgrade extractor hides the low-level handshake, the WebSocket type provides a familiar async stream interface, and the entire mechanism runs on the same battle-tested infrastructure that powers the rest of the Rust async ecosystem.

If you are building a service that requires real-time interaction - a chat backend, a live notification system, or a collaborative tool - starting with the echo server pattern on this page gives you the exact shape you will extend. The next step beyond echo is to share connections among multiple users, which involves shared application state and broadcast channels - topics that build directly on the foundation you have just laid.