Building with WebSockets
What changes on the server when a connection stays open: handling events, pushing messages, broadcasting, and handling clients that drop.
What is it?
A WebSocket connection is a real-time, two-way upgrade of a normal HTTP request. Working with one mostly means understanding what differs from a normal request handler:
- The connection stays open instead of closing after one response.
- Either side can send a message at any moment.
- To reach more than one client, your server must track who's connected.
So a WebSocket route isn't shaped like (req, res) => .... It's shaped like: "a connection opened; here's what to do with each message; here's what to do when it closes."
Explain like I'm 10
A normal API route is a phone call: dial, ask one question, get one answer, hang up. A WebSocket is a walkie-talkie left on: it stays open, either person can talk at any time, and to reach a whole group you must keep a list of everyone whose walkie-talkie is on.
Examples
Connection lifecycle and messages (Node.js, the ws library)
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (socket) => {
console.log("client connected");
socket.on("message", (data) => {
console.log("received:", data.toString());
socket.send("ack: " + data.toString());
});
socket.on("close", () => {
console.log("client disconnected");
});
});The whole lifecycle in one place: 'connection' fires once when a client connects, 'message' fires each time that client sends something, and 'close' fires when the connection ends. There's no single request/response pair.
Broadcasting to every connected client
const clients = new Set();
wss.on("connection", (socket) => {
clients.add(socket);
socket.on("close", () => clients.delete(socket));
socket.on("message", (data) => {
// send this message out to everyone else connected
for (const client of clients) {
if (client !== socket && client.readyState === client.OPEN) {
client.send(data.toString());
}
}
});
});A socket only knows about itself. To reach every client (like a chat room), the server keeps its own list of open connections, loops over it, and adds or removes entries as clients connect and disconnect.
The same lifecycle in FastAPI
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
@app.websocket("/ws")
async def chat(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"ack: {data}")
except WebSocketDisconnect:
print("client disconnected")await websocket.accept() completes the upgrade. The while True loop plays the role of Node's 'message' event, waiting for each message in turn. WebSocketDisconnect is FastAPI's equivalent of the 'close' event.
How it works
Once a WebSocket connection is accepted, the server keeps it open and both sides talk through events instead of one request/response pair: a "connected" event, repeated "message" events in either direction, and a "closed" event. The connection has no idea of "everyone in this chat room", so broadcasting is the server's job: it keeps an in-memory collection of open connections and loops over it.
Reconnection is the client's job, not the server's. A dropped connection (a phone losing signal, a laptop sleeping) just closes the socket. A well-behaved client notices and calls new WebSocket(...) again, usually after a short backoff delay. The server doesn't "resume" the old connection; it just sees a new one arrive.
Scaling is where WebSockets get harder than a stateless HTTP API. If each server keeps its client list only in memory and you run several instances behind a load balancer, a message from a client on server A can't reach a client on server B by looping over A's local list.
Broadcasting becomes a distribution problem: every instance must hear every message. Typically each instance publishes incoming messages to a shared message broker (like Redis pub/sub) that all instances subscribe to, and each re-sends them to its own connected clients.
Why does it exist?
Polling an HTTP endpoint every few seconds ("did anything change?") wastes requests on "no" answers and still isn't fast enough for things that must feel instant. WebSockets let the server push a message the moment something happens, instead of waiting for the client to ask.
When to use it
Use a WebSocket for chat, live notifications, collaborative editing, live dashboards or multiplayer features: anywhere the server often has something to say before the client asks.
When not to use it
For data that changes rarely, or where a few seconds of staleness is fine, a normal request (or occasional polling) is far simpler to build, test and scale. Don't use a persistent connection just because "real-time" sounds appealing.
Common mistakes
Not removing a client from the tracked list on 'close'/WebSocketDisconnect. This leaks references to dead connections and eventually crashes when the server sends to one.
Assuming the server handles reconnection. It doesn't: a dropped connection is gone, and the client must detect that and open a new one.
Keeping the client list only in one server's memory and expecting broadcasts to reach clients on other instances behind a load balancer.
Practice exercises
- Easy:
Using the ws library, write the 'connection' and 'close' handlers to log when clients connect and disconnect.
- Medium:
Extend the broadcasting example so a message is echoed to every connected client, including the sender.
- Hard:
Explain step by step why running three instances of a WebSocket server behind a load balancer breaks naive in-memory broadcasting, and what you'd change to fix it.
Interview questions
Why does broadcasting a message to all connected clients require extra work on the server, when a socket already exists for each client?
Each socket only knows its own connection. To reach every client, the server must keep its own collection of open connections and loop over it.
Whose responsibility is reconnection — the client's or the server's?
The client's. A dropped connection just closes, and a well-behaved client notices and opens a new connection, usually after a short backoff delay.
Why does scaling WebSockets across multiple server instances complicate broadcasting?
Each instance only knows the clients connected to it. A message from a client on one instance can't reach a client on another without a shared mechanism, like a pub/sub broker every instance subscribes to.
What actually happens during the handshake that upgrades a connection from HTTP to a WebSocket?
The client sends a normal HTTP request with an Upgrade: websocket header. If the server agrees, it replies with status 101, and both sides switch the same TCP connection to the WebSocket protocol, which then stays open for two-way messages.
Why can't a WebSocket route be shaped like a typical `(req, res) => ...` handler?
There's no single request producing one response. The connection fires separate events over its life (opened, each message, closed), so the code is organized around those events.
In the ws library example, what does the `'connection'` event handler run for?
It runs once per new client and gives you a socket for that client. Any 'message'/'close' listeners registered inside apply only to that connection.
In the broadcasting example, why does the loop check `client !== socket`?
So the message goes to every other client but not back to the sender. Without it, the sender would get its own message echoed back.
Why does the broadcasting loop also check `client.readyState === client.OPEN`?
A socket can still be in the collection while it's closing or already closed. Sending to it would throw or silently fail, so this check guards against writing to a stale connection.
What would happen if a server never removed a socket from its tracked clients collection on close?
The collection would keep growing with dead connections that never receive anything: a memory leak. Eventually, sending to one of them could throw an error that needs handling.
Debugging: a client disconnects and reconnects, but messages meant for them stop arriving even though the new connection succeeded. What's a likely bug?
The server is probably still tracking the old, closed socket as 'this client' instead of the new socket from the fresh connection. A reconnect is a new connection, not a resumed one.
Why is detecting a dropped connection and reconnecting the client's job, not the server's?
The server can't tell 'still there but quiet' from 'connection quietly died' unless the client notices its own socket closed and acts. The server just sees a close event, or nothing.
Why do reconnection strategies typically use a backoff delay instead of retrying immediately in a tight loop?
Instant, repeated retries, especially from many clients at once (e.g. right after a server restart), could flood the server. A backoff, often growing between tries, spreads the load and gives the server room to recover.
What is a heartbeat (ping/pong) mechanism used for in long-lived WebSocket connections?
Sending a small ping periodically and expecting a pong lets either side detect a silently dead connection (e.g. the network dropped without a clean close), instead of waiting for a TCP timeout.
Why can't a server's in-memory list of connected clients be used directly to reach clients connected to a different server instance?
Each instance's list only holds sockets for connections made to it. A socket object can't be reached from another process or machine, so other instances can't look it up or send to it.
How does a message broker like Redis pub/sub solve the multi-instance broadcasting problem?
Every instance publishes incoming messages to a shared channel and subscribes to it. When any instance publishes, every subscriber, including itself, receives the message and forwards it to the right locally connected clients.
Scenario: with three server instances sharing state via Redis pub/sub, a client on instance A sends a chat message. Trace how a client on instance C receives it.
Instance A publishes the message to the shared channel. Instance C, subscribed to it, receives it, then loops over its own connected sockets and sends it to that client, just like a local broadcast.
Why does a load balancer typically need sticky sessions (session affinity) for WebSocket traffic specifically?
A WebSocket is one long-lived TCP connection to one instance. Unlike stateless HTTP requests that can be routed individually, all its messages must keep reaching that same instance for the connection's life, or it breaks.
What's a practical reason to prefer a normal HTTP endpoint over a WebSocket for data that only changes occasionally?
A WebSocket needs a persistent connection per client plus code to track and clean up connection state. When a few seconds of staleness is fine, a plain request solves it more simply.
Trap: a developer assumes that because a connection is 'always open,' incoming messages don't need their own validation beyond the initial handshake. Why is this risky?
An open connection doesn't make every message trustworthy. Unexpected or malicious content can arrive in any message after connecting, so messages still need their own validation and authorization checks, not just a one-time check at connect.
Why does the FastAPI example use a `while True` loop instead of a `'message'` event listener like the Node.js version?
FastAPI's WebSocket handling uses async/await, not events. await websocket.receive_text() waits for the next message, so the loop handles messages one after another, like a repeatedly firing 'message' event.
What does `WebSocketDisconnect` represent in the FastAPI example, and why catch it with try/except rather than checking a return value?
It's an exception FastAPI raises when the connection closes, e.g. when the client disconnects during receive_text(). Otherwise receive_text() would wait for a message that never comes, so catching it is how the code detects the end and cleans up.
How is a WebSocket connection's statefulness fundamentally different from a typical REST request, beyond just staying open longer?
A REST request is stateless, so in principle any server can handle each request. A WebSocket has real in-memory state tied to one server process for its whole life, which is what makes horizontal scaling harder.
Why would broadcasting via a shared database table be a poor choice for real-time messages, compared to pub/sub?
A database is built for durable storage and queries, not instantly pushing new data to subscribers. Every instance would have to poll the table for new rows, adding latency and load. Pub/sub pushes messages the moment they're published.
Advanced: what additional problem does horizontal scaling introduce for tracking who's currently connected, beyond message delivery?
A client's connected status only lives in the memory of the instance they're connected to. Knowing whether a user is online anywhere means checking all instances or keeping a shared, cross-instance record.
Follow-up: if a WebSocket connection requires authentication, at what point should that be checked?
Once, during the initial handshake, e.g. with a token in the connection request, since the connection's identity lasts its whole life. You don't re-authenticate every message, but you still need a plan for when that identity's permissions change while the connection is open.