WebSocket vs plain HTTP
Learn how a persistent WebSocket connection differs from plain HTTP request and response, when each one fits, and what changes for the server
Plain HTTP and WebSocket answer different questions. In plain HTTP the client asks and the server answers, one exchange at a time, and the server never speaks first. In WebSocket the connection stays open after one handshake, and either side can send a message at any moment without waiting to be asked. The difference is not speed. It is who is allowed to start talking, and how long the conversation lasts.
Where This Fits
The previous page showed the handshake that turns an HTTP connection into a WebSocket connection. This page compares the two ways of talking once that choice is made. Think of plain HTTP as sending letters: every letter needs a new envelope, a new address, and a reply that comes back in its own envelope. WebSocket is a phone call: one connection is opened, and then both people just talk until one of them hangs up.
The Smallest Working Version First
The clearest way to feel the difference is to run one server that speaks both ways and watch what happens on each route. Create a project with these files.
# Cargo.toml
[package]
name = "ws-learn"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8.9", features = ["ws"] }
tokio = { version = "1.54.1", features = ["full"] }
// src/main.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::{any, 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 msg = match msg {
Ok(msg) => msg,
Err(_) => return,
};
if socket.send(msg).await.is_err() {
return;
}
}
}
async fn hello() -> &'static str {
"hello, plain HTTP"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/ws", any(ws_handler))
.route("/hello", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run. First, talk to the plain route with curl:
curl -v http://127.0.0.1:3000/hello
The live run of that request returned this:
< HTTP/1.1 200 OK
< content-type: text/plain; charset=utf-8
< content-length: 2
< date: Sat, 14 Nov 2026 08:50:29 GMT
<
ok
The exchange is one request and one response. The client asked, the server answered ok, and the exchange is over. The connection itself may be kept alive by HTTP keep-alive and reused for a later request, but that later request would still be a fresh question from the client. The server cannot use the idle connection to send anything on its own.
Now talk to the WebSocket route. A small client program connects once and then sends three messages over that single connection, reading the echo of each one back.
// src/bin/ws_client.rs
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message};
#[tokio::main]
async fn main() {
let (ws, response) = connect_async("ws://127.0.0.1:3000/ws").await.unwrap();
println!("handshake status: {}", response.status());
let (mut write, mut read) = ws.split();
for text in ["one", "two", "three"] {
write.send(Message::Text(text.into())).await.unwrap();
let reply = read.next().await.unwrap().unwrap();
println!("sent {text}, got back: {}", reply.to_text().unwrap());
}
println!("one connection carried all three exchanges");
}
This client needs two more dependencies in Cargo.toml:
tokio-tungstenite = "0.28"
futures-util = "0.3"
Run it with cargo run --bin ws_client while the server is running. The live run printed:
handshake status: 101 Switching Protocols
sent one, got back: one
sent two, got back: two
sent three, got back: three
one connection carried all three exchanges
One handshake, one connection, three exchanges, and the server answered each message as it arrived. Nobody re-connected between messages. Nobody re-sent headers between messages. That is the whole difference in one run.
Two Routes, Two Styles:
If curl prints ok for /hello and the client prints three echoes for /ws, the server is speaking both styles on the same port. The plain route answers one question and stops. The WebSocket route stays open and keeps answering.
What Plain HTTP Actually Does
Plain HTTP is a strict turn-taking system. The client sends a request: a method, a path, headers, and sometimes a body. The server reads the whole request, runs a handler, and sends back a response: a status code, headers, and a body. Then that exchange is finished.
A TCP connection underneath may stay open after the response. HTTP/1.1 keep-alive lets the client reuse the same connection for its next request instead of opening a new one. That reuse is easy to confuse with a persistent conversation, so the distinction matters: keep-alive reuses the wire, but every request is still a new question, and the server still cannot speak until asked. The connection is idle between requests, and the idle connection carries no meaning. Either side may close it at any time without losing anything, because the next request simply opens a fresh one.
That shape fits most of the web. Loading a page, submitting a form, and fetching an image are all one-question exchanges. The client knows what it wants, asks for it, gets it, and moves on. The server needs no memory of the client between requests, which is why plain HTTP servers scale so well: each request is self-contained, and a load balancer can send each request to a different machine without anyone noticing.
What a WebSocket Connection Actually Does
A WebSocket connection starts with the handshake and then changes character completely. After the 101 response, there are no more requests and responses. There are frames. A frame is a small package with a type and a payload: a text frame, a binary frame, a ping, a pong, or a close frame. Either side can send a frame at any time. Neither side waits for permission.
That freedom is what makes live features possible. A chat server can push a new message to a browser the moment another user sends it, without the browser asking whether anything is new. A game server can broadcast a player position twenty times a second. A dashboard can update the moment a number changes on the server. In plain HTTP, each of those updates would need the client to ask first, and the client would have to guess how often to ask.
The cost of that freedom is state. A WebSocket server holds one open connection per client for as long as the client stays. It must remember which connections exist, notice when they die, and decide what to do with each one. A plain HTTP server forgets each client the moment it answers. That difference in memory is the real price of a persistent connection, and it is why the later pages in this chapter spend so much time on cleanup, keepalive timers, and close frames.
The Two Styles Side by Side
The table below puts the same questions to both styles. Read it as a checklist for choosing, not as a ranking. Neither style wins in general. Each one wins for the shape of traffic it was built for.
| Question | Plain HTTP | WebSocket |
|---|---|---|
| Who can speak first | Only the client | Either side, at any time |
| How long the connection lasts | One exchange, then idle or closed | Open for the whole conversation |
| What travels on the wire | Requests and responses | Frames: text, binary, ping, pong, close |
| Server memory per client | None between requests | One open connection plus whatever the handler holds |
| What happens if the connection drops | The next request opens a new one | The conversation ends and must be re-established |
| Natural fit | Loading pages, forms, one-off data fetches | Chat, live dashboards, games, shared editing |
Two rows deserve a second look because beginners misread them most often.
The row about who speaks first is the decisive one. If the server never needs to send anything unprompted, plain HTTP is enough, and a WebSocket adds machinery for no benefit. If the server must push updates the moment they happen, plain HTTP cannot do it at all, and the choice is made.
The row about dropped connections is the honest cost. A plain HTTP client that loses its connection loses nothing: it retries the request. A WebSocket client that loses its connection loses the conversation: it must reconnect, repeat the handshake, and re-establish whatever state the conversation had, such as which room it was in or where it had read up to. Applications that use WebSocket need a reconnect strategy. That strategy belongs to the application, not to Axum, and it is the first thing to design after the echo server works.
The Concept Behind the Difference
The difference comes down to who holds the initiative. In plain HTTP the client holds it. Every exchange begins with a question, and the server is purely reactive. That is a simple contract, and simple contracts are easy to scale, cache, and reason about.
In WebSocket the initiative is shared. The handshake is the last moment the client is in charge. After the 101, both sides are equals on the wire. The server can push, the client can push, and either side can close. Shared initiative is more powerful and more demanding: the server must now manage long-lived state, notice dead connections, and handle two directions of traffic at once.
A useful mental model is the difference between a vending machine and a phone call. A vending machine takes one request and gives one answer. You cannot ask it to tap you on the shoulder when your favourite snack is restocked. A phone call stays open, and either person can speak whenever they have something to say. The vending machine is cheaper to run and easier to replace. The phone call is the only option when the news has to arrive the moment it happens.
When Each Style Fits
The choice is usually obvious once the traffic shape is written down in one sentence.
Use plain HTTP when the client always asks first. Fetching a user profile, submitting a login form, loading a list of articles, and uploading a file are all client-initiated. The server answers and forgets. Nothing is lost by closing the connection after the answer.
Use WebSocket when the server must speak first, or when messages flow both ways without a question each time. A chat room, a live price feed, a multiplayer game, a shared document, and a build log that streams while a job runs are all server-initiated or continuous. Polling, which means asking the same question again and again on a timer, can imitate this shape, and it is worth naming why that imitation is a poor fit: every poll is a full HTTP exchange with headers, routing, and handler work, most of which return the answer "nothing new", and the update still arrives late, up to one poll interval after it happened. Polling is simple and sometimes good enough for slow updates, but it is not a substitute for a push when the update must arrive at once.
There is a middle shape worth recognising. Some features need live updates in one direction only, from server to client, with no messages going back. That shape is real, and it has its own lighter-weight answer. This page does not teach it, because it belongs to its own part of the curriculum, but knowing it exists keeps the reader from reaching for a full two-way socket when one direction would do.
A Richer Example With a Live Counter and a Plain Counter
The smallest example shows the two styles on separate routes. This version makes the contrast sharper by building the same feature twice: a counter that the client reads, once over plain HTTP and once over a WebSocket that pushes every new value.
// src/main.rs
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
State,
},
response::Response,
routing::{any, get},
Router,
};
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use tokio::time::Duration;
#[derive(Clone)]
struct AppState {
counter: Arc<AtomicU64>,
}
async fn counter_value(State(state): State<AppState>) -> String {
state.counter.load(Ordering::Relaxed).to_string()
}
async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> Response {
ws.on_upgrade(move |socket| handle_socket(socket, state))
}
async fn handle_socket(mut socket: WebSocket, state: AppState) {
let mut ticker = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = ticker.tick() => {
let value = state.counter.fetch_add(1, Ordering::Relaxed) + 1;
let text = format!("counter is now {value}");
if socket.send(Message::text(text)).await.is_err() {
return;
}
}
msg = socket.recv() => {
match msg {
Some(Ok(Message::Text(text))) if text.as_str() == "stop" => return,
Some(Ok(_)) => {}
Some(Err(_)) | None => return,
}
}
}
}
}
#[tokio::main]
async fn main() {
let state = AppState {
counter: Arc::new(AtomicU64::new(0)),
};
let app = Router::new()
.route("/ws", any(ws_handler))
.route("/counter", get(counter_value))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The plain route is a snapshot. curl http://127.0.0.1:3000/counter prints a number, and that number is already old by the time it is read: the counter keeps moving only when a WebSocket client is connected, and each curl call sees whatever the value happens to be at that instant. To watch the counter change over plain HTTP, the reader would have to call curl again and again.
The WebSocket route is a stream. Connect once, and a new message arrives every second with the next value, pushed by the server without any question from the client. Sending the text stop ends the stream from the client side. The tokio::select! block is doing the waiting here: it watches the timer and the incoming messages at the same time, and whichever one is ready first runs. The timer arm increments the shared counter and pushes the value. The receive arm watches for stop or a disconnect. Either arm can end the loop, and ending the loop ends the connection.
The shared counter is an AtomicU64, a number that many tasks can safely increment without a lock, wrapped in an Arc, a shared pointer that lets many tasks own the same value. The plain route reads it. The socket task writes it. Both see the same number because they share the same Arc. That sharing is what makes the two routes show the same feature in two styles.
The Counter Only Moves While a Socket Is Open:
In this example the counter is incremented by the socket task, so it only advances while a client is connected. A real service would advance the counter from its own work, such as completed jobs or new events, and the socket task would only read and push. The shape is the same either way: the server pushes, the client listens.
Two Variations on the Same Server
Asking again and again over plain HTTP
The honest way to watch a changing value over plain HTTP is polling: ask, wait, ask again. A shell loop shows the cost clearly.
while true; do curl -s http://127.0.0.1:3000/counter; sleep 1; done
Each line of output costs a full HTTP exchange: a TCP connection or a reused keep-alive connection, a request with headers, routing, a handler call, and a response with headers. Most answers are numbers the reader has already seen. If the value changes twice between polls, the middle value is never seen at all. Polling works, and for a value that changes once a minute it is often the right answer. For a value that changes every second, it is a busy way to be late.
Letting the server push over one WebSocket
The same watch over the WebSocket route costs one handshake and then one small frame per update. No headers are re-sent. No routing runs per update. No value is skipped, because every increment produces exactly one frame. The client program from the first section, pointed at this server, prints a new line every second until it sends stop. That is the whole economy of the persistent connection: the setup is paid once, and each update is as small as the protocol allows.
The Two Styles as a Diagram
The diagram shows one exchange of each style. The plain HTTP side ends after the response. The WebSocket side keeps going.
Plain HTTP
Client Server
| GET /hello |
| --------------------------> |
| 200 OK "hello, plain HTTP" |
| <-------------------------- |
| (exchange over, |
| next request starts over) |
WebSocket
Client Server
| GET /ws + Upgrade headers |
| --------------------------> |
| 101 Switching Protocols |
| <-------------------------- |
| frame "one" |
| --------------------------> |
| frame "one" |
| <-------------------------- |
| frame "two" |
| --------------------------> |
| frame "two" |
| <-------------------------- |
| (keeps going until |
| either side closes) |
Testing the Difference
A test can pin down the exact property that separates the two styles: one WebSocket connection carries many exchanges, while a plain HTTP route answers one request at a time. The test below connects once and exchanges three messages over that single connection, using the same test pattern as the handshake page: bind to port 0, spawn the server, connect with tokio-tungstenite.
# Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.28"
futures-util = "0.3"
// tests/one_connection_many_messages.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::any,
Router,
};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::connect_async;
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 {
match msg {
Ok(msg) => {
if socket.send(msg).await.is_err() {
return;
}
}
Err(_) => return,
}
}
}
#[tokio::test]
async fn one_connection_carries_three_exchanges() {
let app = Router::new().route("/ws", any(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 (ws, _) = connect_async(&url).await.unwrap();
let (mut write, mut read) = ws.split();
for text in ["one", "two", "three"] {
write
.send(tokio_tungstenite::tungstenite::Message::Text(
text.into(),
))
.await
.unwrap();
let reply = read.next().await.unwrap().unwrap();
assert_eq!(reply.to_text().unwrap(), text);
}
}
Run it with cargo test. The loop is the assertion: a single connection, opened once before the loop, carries all three exchanges. If the server closed the connection after the first reply, the second send would fail and the test would fail with it. A matching plain HTTP test would do the opposite: one request per exchange, each needing its own call. The two tests together are the executable form of the table above.
Common Beginner Mistakes
Treating a WebSocket like a request that returns a value
// Wrong - there is no single response to await
let answer = socket.send(Message::text("hello")).await;
send returns Ok(()) when the frame is accepted for sending, not the reply. The reply arrives later, on the receive side, in whatever order the other side chooses to send it. Code that sends and then immediately expects an answer from the same call is written for HTTP, and it will not compile into a working WebSocket conversation. The receive loop is where answers arrive, and it runs independently of sends.
Polling a WebSocket route with curl
# Wrong - curl speaks HTTP, not WebSocket frames
curl http://127.0.0.1:3000/ws
Curl sends a plain HTTP request with no upgrade headers, so Axum answers 400 Bad Request. That 400 is correct behaviour, not a bug. Curl cannot complete a handshake and cannot speak frames. A WebSocket route needs a WebSocket client, such as the small Rust program in this page or a browser page that uses the WebSocket API.
Keeping a WebSocket open for a one-off question
Opening a WebSocket, sending one question, reading one answer, and closing it works, and it is wasteful. The handshake costs more than the question it carries. A one-off question belongs on a plain HTTP route, where the whole exchange is one request and one response with no setup beyond the connection itself. Reach for a WebSocket when the conversation will have more than one exchange, or when the server must speak first.
Assuming the connection will stay open forever
A WebSocket connection can drop at any time: the client closes its laptop, a proxy times out an idle connection, a network changes. Plain HTTP code rarely thinks about this, because each request is short and a retry is cheap. WebSocket code must think about it from the start, because the whole conversation depends on one long-lived connection. The keepalive timer and the close frame pages in this chapter exist for exactly this reason.
Keep-Alive Is Not a Conversation:
An idle plain HTTP connection held open by keep-alive looks persistent, and it is not. The server still cannot send anything on it, and either side may drop it without warning. If the server must push, the connection has to be a WebSocket, not a reused HTTP connection.
Final Complete Example
Here is everything from this page in one place: the server with both styles, and the client that proves one connection carries many exchanges.
// src/main.rs
use axum::{
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::{any, 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 msg = match msg {
Ok(msg) => msg,
Err(_) => return,
};
if socket.send(msg).await.is_err() {
return;
}
}
}
async fn hello() -> &'static str {
"hello, plain HTTP"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/ws", any(ws_handler))
.route("/hello", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
// src/bin/ws_client.rs
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message};
#[tokio::main]
async fn main() {
let (ws, response) = connect_async("ws://127.0.0.1:3000/ws").await.unwrap();
println!("handshake status: {}", response.status());
let (mut write, mut read) = ws.split();
for text in ["one", "two", "three"] {
write.send(Message::Text(text.into())).await.unwrap();
let reply = read.next().await.unwrap().unwrap();
println!("sent {text}, got back: {}", reply.to_text().unwrap());
}
println!("one connection carried all three exchanges");
}
Run the server, then curl /hello, then run the client. The two outputs side by side are the lesson: one exchange that ends, and one connection that keeps going.
Summary
Plain HTTP and WebSocket are not two speeds of the same thing. They are two contracts about who may speak. Plain HTTP gives the initiative to the client alone, and in return it gives the server freedom from memory: each request stands alone, and a dropped connection costs nothing. WebSocket shares the initiative between both sides, and in return it demands memory: one open connection per client, a reconnect strategy, and attention to cleanup and liveness.
The practical rule follows from the traffic, not from the technology. Write the feature down as a sentence. If the sentence starts with the client asking, use plain HTTP. If the sentence starts with the server announcing, or if messages flow back and forth without a question each time, use a WebSocket. The pages that follow are the cost of that second choice made manageable: how to read and write at the same time, how to notice when a client has gone, how to keep an idle connection alive, and how to close one cleanly.