SSE vs WebSocket trade-offs

Learn how Server-Sent Events and WebSockets differ in direction, handshake, reconnect behaviour and proxies, and how to pick the right one for a job

Server-Sent Events and WebSockets both keep a connection open so a server can push updates to a client without the client asking again. The difference is direction. SSE sends in one direction only, from server to client, over plain HTTP. A WebSocket sends in both directions over its own upgraded connection. Picking between them is picking how much conversation the job needs, and every other difference follows from that one choice.

Where This Fits

The chat endpoint built earlier sends updates one way, from the server to the browser, and the browser never talks back over that same connection. A WebSocket echo server does the opposite job: the client sends a message and the server answers it on the same connection. This page puts the two side by side, using those real servers, and works out when each one fits.

Think of SSE like a radio broadcast. The station transmits, the listeners receive, and a listener who wants to request a song phones the station on a separate line. Think of a WebSocket like a phone call. Either side can speak at any time, and the call stays open until one side hangs up. A broadcast and a phone call are both live, but they are built for different kinds of conversation.

The Smallest Working Version

One server can run both shapes at once, on two routes. The SSE route returns an Sse response that sends a tick every second. The WebSocket route upgrades the connection and echoes every message back. The two handlers sit in the same file so the comparison is direct.

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"
tokio-stream = "0.1"

The ws feature is what turns on WebSocket support in Axum. SSE needs no feature flag at all: the Sse response type is part of Axum itself, and it works with the default features. That asymmetry is the first hint about which one is simpler to reach for.

src/main.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::{
        sse::{Event, Sse},
        Response,
    },
    routing::get,
    Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("tick"))
        .map(Ok)
        .throttle(Duration::from_secs(1));
    Sse::new(stream)
}

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("/events", get(sse_handler))
        .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. Two routes answer on the same server, and each one can be tested with the tool that fits it. The SSE route answers a plain curl request, because it is plain HTTP. The WebSocket route needs a WebSocket client, because a plain request to it is refused.

curl -N --max-time 3 http://127.0.0.1:3000/events
data: tick

data: tick

data: tick

Three ticks arrive, one per second, and curl stops after three seconds because of --max-time 3. No upgrade, no handshake, no special client: an ordinary HTTP request opens the stream.

curl -i http://127.0.0.1:3000/ws
HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
content-length: 43

Connection header did not include 'upgrade'

The same curl against the WebSocket route gets a 400, because the route expects upgrade headers and a plain request has none. That 400 is the correct answer, and it is the proof that the two routes speak different protocols even though they share one server. The WebSocket route answers 101 only when the request carries the four upgrade headers, as the echo server run showed, with sec-websocket-accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= in the reply.

Working Setup:

If curl -N on /events prints ticks one per second and plain curl on /ws prints a 400, both routes are behaving correctly. The 400 is not a failure: it is the WebSocket route refusing a request that never asked to upgrade.

Direction, and Who Speaks First

Direction is the difference everything else hangs from. An SSE stream flows one way. The server sends, the client receives, and the client has no way to send anything back over that same connection. If the client needs to say something, it makes a separate ordinary HTTP request, such as a POST, on a different connection. A WebSocket flows both ways on one connection. Either side can send at any time, and the server can answer a client message on the very connection it arrived on.

Who speaks first follows from direction. On an SSE stream, the server speaks first, because the client has nothing to say over that connection: it opens the stream and waits. On a WebSocket, the client speaks first in practice, because the server has no reason to send before it knows what the client wants, and the connection exists so the client can ask. The echo server is the clearest example: nothing happens until the client sends a message, and then the server answers.

A beginner mistake is to treat an SSE stream as a two-way channel and try to send a message up it. There is no send call on the client side of an EventSource, because the browser API that reads SSE has no way to write to the stream. The fix is to accept the split: SSE carries server-to-client updates, and a separate POST carries client-to-server input. When the job genuinely needs the client to speak over the same connection, that split is the sign to use a WebSocket instead.

The Handshake, Side by Side

The handshake is the second difference, and it is visible in the status codes. An SSE stream starts as an ordinary GET request and is answered with an ordinary 200, plus the text/event-stream content type. Nothing upgrades, nothing switches protocols, and the connection stays plain HTTP for its whole life. A WebSocket starts as a GET too, but it asks to switch protocols, and the server answers 101 Switching Protocols when it agrees. From that moment the connection stops being HTTP and becomes a WebSocket connection, with its own framing for messages.

The two handshakes fail differently as well. A plain request to an SSE route succeeds, because an SSE route is an ordinary GET route. A plain request to a WebSocket route fails with a 400, because the WebSocketUpgrade extractor checks for the upgrade headers and refuses the request without them. That means an SSE endpoint can be tested with curl or a browser address bar, while a WebSocket endpoint cannot: it needs a real WebSocket client, or a curl call that carries all four upgrade headers by hand.

The 101 also changes what sits between the client and the server. Proxies and load balancers understand plain HTTP, so an SSE stream passes through them the way any long HTTP response does. A WebSocket upgrade needs the proxy to understand the upgrade and keep the connection open after switching protocols. Most modern proxies do, but it is one more thing that can go wrong, and an older or stricter proxy in the middle can refuse the upgrade while passing SSE without trouble.

SSE Is Plain HTTP All the Way Down:

An SSE stream never leaves HTTP. The request is a GET, the answer is a 200, and the body is text that keeps arriving. Everything a proxy, a cache, or a firewall knows about HTTP still applies, which is why SSE works in places where an upgrade would be blocked.

Reconnect Behaviour

A dropped connection is where the two shapes differ most in the amount of code the reader has to write. SSE reconnects by itself. The browser's EventSource notices the drop, waits, and opens the same GET again, with no code from the page author. If the server sent event ids, the browser also sends the Last-Event-ID header on the reconnect, so the server can resume where the client left off. The waiting time starts at a few seconds by default, and the server can change it with a retry: field in an event.

A WebSocket does not reconnect by itself. The browser's WebSocket object fires an error and a close, and then it stops. Reconnecting, waiting between attempts, and deciding when to give up are all code the page author writes by hand, in JavaScript, with a timer and a loop. The server side has no part in it: the server only sees a new connection arrive, with no memory of the old one, and no header naming where the old one stopped.

That difference decides whole classes of jobs. A live scoreboard, a progress bar, or a news feed can drop and resume with no client code at all on SSE, because the browser owns the retry. The same feed on a WebSocket needs a reconnect loop before it is reliable, and the loop is code that can itself have bugs, such as retrying forever without waiting, or retrying while the server is down and hammering it. A WebSocket is still the right pick when the job needs two-way traffic, but its reconnect is a cost that has to be paid, and SSE already paid it in the browser.

Proxies, Limits, and Browser Support

Three practical limits shape the choice, and each one favours a different side depending on the deployment.

The first is the per-host connection limit. Browsers cap how many HTTP/1.1 connections they open to one host at the same time, commonly six, and each SSE stream uses one of those connections for as long as it stays open. A page that opens several SSE streams can use up the allowance and stall its own images, scripts, or API calls behind them. WebSockets do not count against that HTTP limit in the same way, because they leave HTTP after the upgrade. HTTP/2 changes the picture, because many streams share one connection there, but the limit is real on HTTP/1.1 and it is the reason a page should open one SSE stream and filter on the client, rather than opening one stream per widget.

The second is proxy buffering. Some proxies hold back a response body until it is complete, which never happens for a stream that stays open. An SSE stream behind such a proxy arrives late or not at all, unless the proxy is told not to buffer it. WebSocket traffic is not an HTTP response body after the upgrade, so the same proxy does not buffer it. This is a deployment detail, not a protocol difference, but it is the one that surprises beginners most: the stream works on a local machine and stalls behind a proxy, and the fix is a proxy setting, not a code change.

The third is browser support. Both are built into every modern browser: EventSource for SSE and WebSocket for WebSockets, with no library needed. The gap is in features, not availability. EventSource sends only GET requests and cannot carry custom request headers, so it cannot send an authorization header the way a fetch call can. A WebSocket client in JavaScript can send headers only during the upgrade in some environments either, but the WebSocket route in Axum can read the query string or a cookie for the same purpose. When the job needs request headers the browser cannot send, the answer is usually a cookie or a query value, not a different protocol.

One Stream Per Page, Not One Per Widget:

Opening a separate SSE stream for every widget on a page can exhaust the browser's per-host connection limit on HTTP/1.1, and the page's other requests then wait. Open one stream for the page and let the client sort the events, or move the page to HTTP/2 where the limit does not apply the same way.

Text Only Against Binary

SSE carries text only. Every event is UTF-8 text, split into lines, and there is no binary frame in the format. A server that needs to send bytes, such as an image or a chunk of audio, has to encode them as text first, usually base64, which grows the payload and costs time to encode and decode. WebSockets carry both text and binary frames natively, and the Axum echo server proves it: five binary bytes, including a zero byte and a 255 byte, round-tripped unchanged. When the payload is binary, or when the payload is large enough that encoding it as text would hurt, the WebSocket is the honest pick.

Text is not a weakness where the payload is already text. JSON, log lines, chat messages, and score updates are all text, and SSE carries them without any encoding step. The choice is about the payload, not about the protocol's quality: text payloads fit SSE, binary payloads fit WebSockets, and a job that mixes the two either encodes the binary or runs both.

The Concept Behind the Trade-off

The trade-off is a choice between a narrow tool that does one job well and a wide tool that does every job with more code. SSE is narrow: one direction, plain HTTP, automatic reconnect, text only. Every limit in that list is also a feature, because each limit removes code the reader would otherwise write. The reconnect is free because the browser owns it. The proxy behaviour is familiar because the stream is plain HTTP. The wire format is readable because it is text.

A WebSocket is wide: two directions, binary frames, no reconnect, its own protocol after the upgrade. Every freedom in that list is also a cost, because each freedom is something the reader must handle. The reconnect loop, the binary handling, and the upgrade all need code, and the code has to be right for the connection to be reliable. The wide tool earns its place when the job needs what the narrow tool cannot do, and it is wasted effort when the job only needs one-way text.

Why One Server Runs Both

Running both routes in one server is not a trick for this page: it is how real applications are built. A dashboard can use SSE for the scoreboard and a WebSocket for the chat, because the scoreboard is one-way text and the chat is two-way. The two routes share the same server, the same state, and the same deployment, and each client uses the route that fits what it does. Splitting by direction keeps each route simple, instead of forcing one protocol to do both jobs badly.

A Richer Example With a Scoreboard and a Chat Room

A realistic server uses SSE where the traffic is one-way and a WebSocket where it is two-way. The scoreboard sends a score every two seconds to every browser watching it, and nobody watching needs to send anything back. The chat room takes messages from any client and sends them to every client, which needs both directions. The two handlers share one broadcast channel for chat, and the scoreboard has its own interval stream.

src/main.rs
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    response::{
        sse::{Event, KeepAlive, Sse},
        Response,
    },
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::{self, Stream}};
use std::{convert::Infallible, time::Duration};
use tokio::sync::broadcast;
use tokio_stream::StreamExt as _;

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

async fn scores_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("home 2 - away 1"))
        .map(Ok)
        .throttle(Duration::from_secs(2));
    Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
}

async fn chat_handler(
    ws: WebSocketUpgrade,
    State(state): State<AppState>,
) -> Response {
    ws.on_upgrade(|socket| handle_chat(socket, state))
}

async fn handle_chat(socket: WebSocket, state: AppState) {
    let (mut sender, mut receiver) = futures_util::stream::StreamExt::split(socket);
    let mut rx = state.chat_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.chat_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 (chat_tx, _rx) = broadcast::channel::<String>(16);
    let state = AppState { chat_tx };
    let app = Router::new()
        .route("/scores", get(scores_handler))
        .route("/chat", get(chat_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();
}

The scores handler is the SSE shape: a repeating stream, throttled to one event every two seconds, with a keep-alive every 15 seconds so idle connections are not cut off. The chat handler is the broadcast shape from the WebSocket chapter: one task per connection, a subscription per connection, a send task that is aborted when the connection ends, and a channel capacity of 16. The split call names its trait in full, futures_util::stream::StreamExt::split(socket), because split lives on the futures stream trait, which this file does not import. The file imports the tokio stream trait instead, for throttle, and naming the trait keeps the two traits from colliding on the methods they both define. A browser watching the scores uses EventSource on /scores and never writes to it. A browser chatting uses a WebSocket on /chat and writes whenever the user types. The two routes never interfere, because each connection gets its own task and its own stream.

The Broadcast Channel Capacity Is 16:

The chat channel is created with capacity 16, the same number the broadcast page used. That number is the count of unread messages the channel holds before the oldest is dropped and a slow receiver is told it lagged. It is a bound on memory, and a slow chat client rejoins at the newest message instead of blocking the room.

Variations

Picking by direction

When the traffic is one-way, from server to client, SSE is the default pick. Live scores, progress bars, build logs, news feeds, and notifications are all one-way, and SSE gives them reconnect and plain HTTP for free. When the traffic is two-way, the WebSocket is the pick. Chat, multiplayer games, collaborative editing, and remote control all need the client to speak over the same connection, and SSE cannot carry that traffic without a second channel.

Picking by reconnect needs

When a dropped connection must resume with no client code, SSE wins, because the browser reconnects and sends Last-Event-ID on its own. When the client already has a reconnect loop, or when a dropped connection is acceptable because the client will simply refresh, the WebSocket's missing reconnect is not a cost. A chat client that reconnects by hand and re-joins the room loses nothing by using a WebSocket, because joining again is part of the chat flow anyway.

Picking by proxies and deployment

When the server sits behind a proxy that the reader does not control, SSE is the safer first try, because it is plain HTTP and the proxy already understands it. If the proxy buffers responses, the stream needs a no-buffering setting, and that setting is a deployment fix. When the proxy is known to pass WebSocket upgrades, the WebSocket is equally safe. The deciding question is not which protocol is better, but which one the proxy in front of the server already passes.

Picking by payload

When the payload is text, SSE carries it directly. When the payload is binary, the WebSocket carries it directly, and SSE would need base64 encoding. A job that sends mostly JSON with an occasional image either encodes the image or runs the image over a WebSocket route and the JSON over SSE. The payload decides, and a mixed job can honestly use both routes, as the richer example does.

The hybrid shape, SSE down and POST up

The most common SSE shape in real applications is a hybrid: SSE carries server-to-client updates, and ordinary POST requests carry client-to-server input. A browser opens an EventSource for the feed and calls fetch with a POST when the user acts. The two halves are separate HTTP requests, and the server ties them together with shared state. This shape fits jobs that are mostly one-way with occasional input, such as a dashboard where the user rarely changes a setting, or a feed where the user occasionally votes. It keeps the automatic reconnect of SSE and avoids the WebSocket entirely, at the cost of one extra request per user action.

src/main.rs
use axum::{
    extract::State,
    response::sse::{Event, Sse},
    routing::{get, post},
    Router,
};
use futures_util::stream::{self, Stream};
use std::{convert::Infallible, sync::{Arc, Mutex}, time::Duration};
use tokio_stream::StreamExt as _;

#[derive(Clone)]
struct Votes {
    count: Arc<Mutex<u32>>,
}

async fn feed_handler(State(votes): State<Votes>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let count = *votes.count.lock().unwrap();
    let stream = stream::once(async move {
        Ok(Event::default().data(format!("votes: {count}")))
    });
    Sse::new(stream)
}

async fn vote_handler(State(votes): State<Votes>) -> &'static str {
    let mut count = votes.count.lock().unwrap();
    *count += 1;
    "vote counted"
}

#[tokio::main]
async fn main() {
    let votes = Votes {
        count: Arc::new(Mutex::new(0)),
    };
    let app = Router::new()
        .route("/feed", get(feed_handler))
        .route("/vote", post(vote_handler))
        .with_state(votes);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The feed handler reads the shared vote count and sends it as one event. The vote handler takes a POST, increments the same count, and answers with a plain message. A browser that votes with fetch and watches with EventSource gets both directions with no WebSocket, and the shared Arc<Mutex<u32>> is the tie between them. The shape is enough when votes are rare and the feed is the main traffic.

A Plain Text Diagram of the Two Shapes

The same update travels differently in each shape:

SSE, one way over plain HTTP:

server sends Event("home 2 - away 1")
        |
        v
plain HTTP 200, content-type text/event-stream
        |
        v
browser EventSource receives it
        |
        v
browser cannot answer on this connection
        |
        v
client input, if any, goes by a separate POST

WebSocket, two ways over an upgraded connection:

client sends Text("hello")
        |
        v
server recv returns Text("hello")
        |
        v
server send delivers Text("hello")
        |
        v
client receives Text("hello")
        |
        v
either side can speak next, on the same connection

The SSE diagram has no return arrow, because there is none. The WebSocket diagram is a loop, because either side can speak next.

Testing It

The tests prove the handshake difference without a browser. The SSE test sends a plain request and asserts a 200 with the right content type. The WebSocket tests send a plain request and assert a 400, then connect with a real client and assert a 101 and an echo. They need tokio-tungstenite and futures-util as dev-dependencies, and tower for the oneshot helper.

Cargo.toml
[dev-dependencies]
tokio-tungstenite = "0.29"
futures-util = "0.3"
tower = { version = "0.5", features = ["util"] }
tests/compare_test.rs
use axum::{
    body::Body,
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    http::{Request, StatusCode},
    response::{
        sse::{Event, Sse},
        Response,
    },
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::{self, Stream}};
use std::{convert::Infallible, time::Duration};
use tokio_stream::StreamExt as _;
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientMessage};
use tower::ServiceExt;

async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("tick"))
        .map(Ok)
        .throttle(Duration::from_secs(1));
    Sse::new(stream)
}

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;
        }
    }
}

fn app() -> Router {
    Router::new()
        .route("/events", get(sse_handler))
        .route("/ws", get(ws_handler))
}

#[tokio::test]
async fn sse_plain_request_returns_200_with_event_stream_type() {
    let response = app()
        .oneshot(Request::builder().uri("/events").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "text/event-stream"
    );
}

#[tokio::test]
async fn websocket_plain_request_returns_400() {
    let response = app()
        .oneshot(Request::builder().uri("/ws").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn websocket_upgrade_returns_101_and_echoes() {
    let app = app();
    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 ws, response) = connect_async(url).await.unwrap();
    assert_eq!(response.status(), 101);
    ws.send(ClientMessage::Text("hello test".into())).await.unwrap();
    let msg = ws.next().await.unwrap().unwrap();
    assert_eq!(msg, ClientMessage::Text("hello test".into()));
    ws.close(None).await.unwrap();
}

Run them with:

cargo test --test compare_test
test sse_plain_request_returns_200_with_event_stream_type ... ok
test websocket_plain_request_returns_400 ... ok
test websocket_upgrade_returns_101_and_echoes ... ok

The three tests together are the whole comparison in executable form: SSE answers a plain request with a 200, a WebSocket refuses the same request with a 400, and a real WebSocket client gets a 101 and an echo. The first two tests run without any network, through oneshot, and the third needs a live server on a random port.

Testing a WebSocket Needs a WebSocket Client:

A plain oneshot request can prove the 400, but it can never prove the 101 or the echo, because those need the upgrade handshake and the socket loop. A WebSocket route that is only tested with plain requests is untested where it matters. Use tokio-tungstenite, the same client the echo server page used, for the upgrade test.

Common Beginner Mistakes

Trying to send client messages up an SSE stream

// Wrong - there is no client-to-server call on an EventSource
const source = new EventSource("/events");
// no send method exists, and none can be added

The browser's EventSource has no send method, because SSE is one-way by design. The fix is the hybrid shape: send client input with a separate POST, or switch the route to a WebSocket when the job needs two-way traffic on one connection.

Choosing a WebSocket for a one-way feed

A live scoreboard built on a WebSocket works, but it carries a reconnect loop, an upgrade handshake, and a socket loop, all for traffic that only flows one way. The fix is to use SSE for the feed and save the WebSocket for the routes that genuinely need two-way traffic. The extra code is not harmless: every line of reconnect logic is a line that can break, and SSE already has that logic in the browser.

Assuming a WebSocket reconnects like SSE

// Wrong - this WebSocket stays closed after the first drop
const ws = new WebSocket("ws://127.0.0.1:3000/chat");
ws.onclose = () => console.log("closed");

The onclose handler above only logs. Nothing reconnects, and the chat stays dead until the page is refreshed. The fix is a reconnect loop with a timer, or an SSE stream for the traffic that must resume on its own. The two shapes do not share reconnect behaviour, and code written for one does not transfer to the other.

Opening one SSE stream per widget

A page with five widgets that opens five SSE streams uses five of the browser's per-host HTTP/1.1 connections, and the page's other requests wait behind them. The fix is one stream for the page, with the client sorting events by their event: name, or a move to HTTP/2 where many streams share one connection.

Sending binary over SSE as raw bytes

// Wrong - SSE has no binary frame, so raw bytes corrupt the stream
Event::default().data(String::from_utf8_lossy(&image_bytes))

Lossy-converting bytes to text corrupts them, and a binary payload needs a binary frame. The fix is a WebSocket route for the binary traffic, or base64 encoding when the payload is small and the SSE route must carry it. The encoding is a deliberate choice with a size cost, not something to do by accident.

Final Complete Example

Here is everything from this page put together: the SSE scores route, the WebSocket chat route with its broadcast channel, and the shared state that ties them into one server.

src/main.rs
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    response::{
        sse::{Event, KeepAlive, Sse},
        Response,
    },
    routing::get,
    Router,
};
use futures_util::{sink::SinkExt, stream::{self, Stream}};
use std::{convert::Infallible, time::Duration};
use tokio::sync::broadcast;
use tokio_stream::StreamExt as _;

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

async fn scores_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let stream = stream::repeat_with(|| Event::default().data("home 2 - away 1"))
        .map(Ok)
        .throttle(Duration::from_secs(2));
    Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
}

async fn chat_handler(
    ws: WebSocketUpgrade,
    State(state): State<AppState>,
) -> Response {
    ws.on_upgrade(|socket| handle_chat(socket, state))
}

async fn handle_chat(socket: WebSocket, state: AppState) {
    let (mut sender, mut receiver) = futures_util::stream::StreamExt::split(socket);
    let mut rx = state.chat_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.chat_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 (chat_tx, _rx) = broadcast::channel::<String>(16);
    let state = AppState { chat_tx };
    let app = Router::new()
        .route("/scores", get(scores_handler))
        .route("/chat", get(chat_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 compare_test
cargo run

Summary

The choice between SSE and WebSocket is a choice about direction first and everything else second. One-way text over plain HTTP with a free reconnect is SSE, and the live runs proved it: a plain curl gets ticks at 200, and the browser would resume on its own after a drop. Two-way traffic, binary frames, or a conversation where either side speaks first is a WebSocket, and the live runs proved that too: a plain request gets a 400, an upgrade gets a 101, and the echo comes back on the same connection. The decision framework is three questions in order: does the client need to speak on this connection, is the payload binary, and must the stream survive a proxy the reader does not control. A yes to the first two points to a WebSocket, a no to all three points to SSE, and a job with both kinds of traffic runs both routes in one server, as the final example does. The habit to carry forward is to let direction decide, because every other difference, the handshake, the reconnect, the proxy behaviour, and the payload, follows from it.