WebSockets explained: how they work and when to use them
3 min readGuides · Networking · Infrastructure
Plain HTTP is a question-and-answer protocol. The browser asks, the server answers, and the conversation is over. That is the wrong shape for a chat window, a live dashboard or a multiplayer game, where the server needs to speak first. A WebSocket fixes that by keeping one connection open and letting both sides send messages whenever they like.
What a WebSocket actually is
WebSocket is its own protocol, standardised in RFC 6455, that starts life as an ordinary HTTP request and then switches. After the switch there are no more requests and responses. There is a persistent TCP connection carrying small frames in both directions.
- Full duplex: client and server can send at the same time, with no polling.
- Low overhead: after the handshake, a message carries a few bytes of framing instead of a full set of HTTP headers.
- Text or binary: frames can hold JSON strings or raw bytes.
- Built-in control frames: ping, pong and close are part of the protocol.
The handshake
The connection begins with a normal GET request that asks to upgrade. The server agrees with status 101, and from that point the same socket speaks WebSocket.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The key and accept headers are not encryption. They only prove that the server understood the WebSocket protocol and is not a confused HTTP cache. Security comes from the URL scheme: ws:// is unencrypted, wss:// runs over TLS, the same way https:// does. Use wss:// for anything real, and pages served over HTTPS will not be allowed to open plain ws:// connections anyway.
A minimal client and server
The browser API is small and built in. On the server, Node needs a library such as ws.
// client (browser)
const socket = new WebSocket("wss://example.com/chat");
socket.addEventListener("open", () => socket.send("hello"));
socket.addEventListener("message", (e) => console.log(e.data));
socket.addEventListener("close", () => console.log("closed"));
// server (Node, using the ws package)
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
ws.on("message", (data) => {
for (const client of wss.clients) {
if (client.readyState === 1) client.send(data.toString());
}
});
});That is a working broadcast chat. It is also missing authentication, validation, reconnection and every other thing a production service needs, which is where the real work is.
WebSocket vs polling vs SSE
- Short polling: the client asks every few seconds. Easy, wasteful, and always a little stale.
- Long polling: the server holds the request until it has something to say. Better latency, but still one request per message.
- Server-Sent Events (SSE): one-way stream from server to browser over plain HTTP, with automatic reconnect. Ideal for notifications, feeds and progress bars.
- WebSocket: two-way and low latency. Worth it when the client also sends frequent messages, such as chat, collaboration, games and trading screens.
My rule: if data only flows server to client, try SSE first. It is simpler to run behind ordinary infrastructure. Reach for WebSockets when you really need traffic in both directions.
Putting it behind Nginx
A reverse proxy will not forward the upgrade unless you tell it to. Missing these headers is the classic reason a WebSocket works locally and fails in production.
location /chat {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 300s;
}Where it bites
- Connections drop. Phones sleep, networks change, proxies time out idle sockets. Build automatic reconnect with backoff, and send periodic pings so idle connections are not cut.
- Idle timeouts. Nginx closes a proxied connection after 60 seconds of silence by default, so raise the timeout or keep traffic flowing.
- Scaling is stateful. Each connection lives on one server. With several servers you need a shared pub/sub layer such as Redis so a message reaches clients on other machines.
- Authentication is awkward. The browser API cannot set custom headers on the handshake, so tokens usually go in a cookie, a short-lived ticket in the URL, or the first message. Never trust the Origin header alone.
- Serverless platforms often cannot hold long-lived connections. Check before you design around them.
- Backpressure. A slow client can make the server buffer messages until memory runs out. Watch the send buffer and drop or disconnect slow consumers.
The short version
A WebSocket is an HTTP request that never ends and becomes a two-way pipe. It is the right tool for real-time features that talk both ways, and the wrong tool for anything you could solve with a normal request or a plain event stream. Use wss://, plan for disconnects from day one, and treat the connection as something that will break.

Written by
Shihab Hossain — Full-Stack Developer
I build thoughtful digital products from Bangladesh — fast web experiences with Next.js, Android apps with Flutter, and the infrastructure behind them.
Work with me