Sub topic 18
When to use WebSockets instead of SSE
This chapter assumes you have read the earlier chapters on Server-Sent Events (SSE), fetch streaming, and cancellation. It also assumes you can read Python and JavaScript, and that you know basic asyncio and promises. By the end you should be able to decide which transport a streaming LLM feature needs, and say what a WebSocket costs you.
The default is SSE
A chat completion stream has a simple shape. The client sends one request. The server answers with a long sequence of small events, then stops. Data flows in one direction after the request.
SSE fits this shape. It is plain HTTP, so it passes through most proxies, authentication layers, and logging tools. If you use EventSource, the browser reconnects for you. If you use fetch, you get the same HTTP semantics as any other request, and AbortController handles cancellation. Every major LLM provider streams this way for the same reasons.
Choose WebSockets only when SSE's one-way shape becomes a real limit, not because WebSockets feel more modern.
What a WebSocket is
A WebSocket is a long-lived, two-way connection between client and server. It starts as an ordinary HTTP request with an Upgrade: websocket header. If the server agrees, it replies with status 101 Switching Protocols. After that, the connection no longer follows request and response rules. Either side can send a message at any time. Messages travel as frames, and a frame can carry text or binary data.
| Property | SSE | WebSocket |
|---|---|---|
| Direction | Server to client, after one request | Both directions, at any time |
| Underlying protocol | HTTP response that never ends | Upgraded connection, its own framing |
| Data types | Text only (UTF-8) | Text and binary |
| Reconnection | Built into `EventSource`; manual with `fetch` | Manual, including resending state |
| Custom headers in browser | Yes with `fetch`; no with `EventSource` | No. The browser API cannot set them |
| Proxy and CDN support | Good, if buffering is disabled | Varies. Needs explicit upgrade support |
| Server state | Usually none between requests | One open connection per client |
When WebSockets are the better choice
The client must talk while the model is talking
Cancellation is the common example. With SSE, you close the connection. The server notices the disconnect and stops generation. That works, but it uses the connection itself as the signal, and you cannot send anything else.
Now suppose the user can do more than stop. They might steer the model, send a correction, or change settings, all within one ongoing session. A WebSocket lets you send a cancel message or an update message and keep the connection open for what comes next.
Audio or other binary data flows both ways
Voice assistants stream microphone audio up and synthesized speech down, at the same time. SSE cannot carry binary data without base64 encoding, which inflates payloads by about a third. It also cannot carry the upstream audio at all. This is why real-time voice APIs from LLM providers use WebSockets (or WebRTC), while text chat APIs use SSE.
Many small messages in both directions
Collaborative editors, multiplayer tools, and agents that push progress while receiving user input all send frequent small messages. With SSE, every upstream message is a separate HTTP request with its own headers and its own authentication check. A WebSocket pays the connection cost once.
Several streams share one session
If one page runs several generations at once, such as a chat reply, a summary, and a suggestion list, a WebSocket can carry them over one connection. Each message carries an id so the client can tell them apart. Browsers also limit the number of simultaneous HTTP/1.1 connections per host, which can hurt many parallel SSE streams. HTTP/2 mostly removes that limit.
When SSE is still enough
- A single prompt gets a single streamed reply.
- Stop is the only upstream action, and closing the request handles it.
- You want it to work behind ordinary load balancers and API gateways without special configuration.
- You want requests to be stateless so any server instance can handle any request.
A "Stop" button alone does not justify WebSockets. Many production chat UIs use SSE and AbortController for exactly this.
A WebSocket version with cancellation
The server below streams tokens for a start message. It cancels the matching task when it receives a cancel message. It uses the websockets package (pip install websockets, version 10.1 or later).
import asyncio
import json
import websockets
async def generate(prompt):
for token in ["Streaming", " over", " WebSocket", "."]:
await asyncio.sleep(0.3)
yield token
async def stream_reply(ws, request_id, prompt):
async for token in generate(prompt):
await ws.send(json.dumps({"type": "delta", "id": request_id, "text": token}))
await ws.send(json.dumps({"type": "done", "id": request_id}))
async def handler(ws):
tasks = {}
try:
async for raw in ws:
msg = json.loads(raw)
if msg["type"] == "start":
task = asyncio.create_task(stream_reply(ws, msg["id"], msg["prompt"]))
task.add_done_callback(lambda _, i=msg["id"]: tasks.pop(i, None))
tasks[msg["id"]] = task
elif msg["type"] == "cancel":
task = tasks.pop(msg["id"], None)
if task:
task.cancel()
await ws.send(json.dumps({"type": "cancelled", "id": msg["id"]}))
finally:
# The client left. Stop any generations still running.
for task in list(tasks.values()):
task.cancel()
async def main():
async with websockets.serve(handler, "localhost", 8765):
await asyncio.Future() # run until interrupted
asyncio.run(main())The browser client sends start, appends deltas for its own request id, and sends cancel when the user presses Stop.
const ws = new WebSocket("ws://localhost:8765");
const id = crypto.randomUUID();
let text = "";
ws.addEventListener("open", () => {
ws.send(JSON.stringify({ type: "start", id, prompt: "Hello" }));
});
ws.addEventListener("message", (event) => {
const msg = JSON.parse(event.data);
if (msg.id !== id) return; // ignore messages for other requests
if (msg.type === "delta") {
text += msg.text;
console.log(text);
} else if (msg.type === "done" || msg.type === "cancelled") {
ws.close();
}
});
// Call stop() from a "Stop" button.
function stop() {
ws.send(JSON.stringify({ type: "cancel", id }));
}Notice what you wrote yourself. SSE gave you the event framing, and data: lines and blank-line boundaries. Here you invented a message format with type and id fields. A WebSocket message arrives whole, so you no longer split events across chunk boundaries. You do own the protocol design.
What WebSockets cost you
- Authentication. The browser
WebSocketconstructor cannot set anAuthorizationheader. Common workarounds are a short-lived token in the query string, a cookie, or an auth message sent first. Query strings can end up in logs, so use tokens that expire quickly. - Reconnection. Nothing reconnects for you. After a drop, your code must reconnect, decide which in-flight generations are lost, and possibly resend. SSE's
Last-Event-IDmechanism has no equivalent here. - Keep-alive. Idle connections get closed by load balancers. Use ping and pong frames, or application-level heartbeats.
- Infrastructure. Proxies and gateways must support the upgrade. Each connection holds server memory for its lifetime, so scaling means counting open connections, not requests per second.
- Backpressure. If the client reads slowly, outgoing data queues up. In browsers, check
ws.bufferedAmountbefore sending large uploads. Server libraries expose their own flow-control settings. - Mid-stream errors. There are no HTTP status codes after the upgrade. Send an explicit
errormessage, and use close codes for connection-level failures.
Decision checklist
- Does the client need to send more than the initial request while the model generates? If not, use SSE.
- Is there binary data in either direction? If yes, lean toward WebSockets.
- Can your gateway and load balancer proxy upgrades and hold long-lived connections? If not, stay on SSE.
- Can you afford to build reconnection, heartbeats, and a message protocol? If not, stay on SSE.
Exercise
A team builds a text chat assistant. Each user sends one prompt, sees a streamed reply, and can press Stop. A product manager proposes moving from SSE to WebSockets "for real-time." Give a recommendation and name two costs of switching.
Show answer
Keep SSE. The data flows one way after the request, and Stop works by aborting the fetch with AbortController, so no two-way channel is needed. Switching would cost reliable authentication (the browser WebSocket API cannot set an Authorization header) and manual reconnection, since there is no Last-Event-ID or EventSource retry. Other valid costs are load balancer upgrade support, heartbeats, per-connection server state, and designing your own message format.
Exercise
In the server code above, why does the handler's finally block cancel the remaining tasks?
Show answer
When the client disconnects, the generation tasks would otherwise keep running and trying to send on a closed connection. Cancelling them stops wasted model work and prevents errors from tasks that write to a dead socket.