WebSockets

One connection, kept open, where both sides can talk whenever they want — the backbone of real-time features.

WebSockets in 30 seconds

  • Problem: plain HTTP is one-shot (client asks, server answers). The server can't push on its own.
  • WebSocket: a single long-lived, bidirectional connection — either side sends anytime.
  • How it starts: an HTTP request 'upgrades' to a WebSocket (handshake), then stays open.
  • Great for: chat, live dashboards, multiplayer, collaborative editing, notifications.
  • The cost: connections are stateful — the server holds them open, so scaling and load balancing get harder.
  • Alternatives: Server-Sent Events (one-way push) or long polling when you don't need two-way.

A phone call, not a letter

Picture two ways of keeping in touch with a friend. The first is mailing letters: you write, send, and wait for a reply — one round trip per exchange, and nothing reaches you unless you wrote first. The second is a phone call: you dial once, the line stays open, and either of you can speak the instant you have something to say. Plain HTTP is the letter. A WebSocket is the phone call — one connection you open once, then keep live for a free-flowing, two-way conversation.

That one shift — from 'ask and wait' to 'stay connected and talk' — is the whole reason WebSockets exist. Everything else on this page is about why the letter model falls short for live features, and how the open line is set up and operated.

Why plain HTTP leaves a gap

Normal HTTP is request/response: the client asks a question, the server answers, and the connection's job is done. This is perfect for loading a page or saving a form — the browser always speaks first, and it always wants exactly one answer. But a whole class of features needs the server to speak first, unprompted:

  • A new chat message arrives from someone else — your screen should update without you doing anything.
  • A live score or stock price ticks — the server knows before you could ever think to ask.
  • A teammate's cursor moves in a shared document — dozens of tiny updates per second, in both directions.
  • A background job finishes and the UI should react the moment it does.

In every case the information originates on the server, at a time the client can't predict. Plain HTTP has no way to deliver it, because the server can only ever respond — it can't initiate. That missing ability, 'let the server push', is the exact gap WebSockets fill.

The gap polling can't fill

The obvious workaround is to make the client ask over and over: every few seconds, fire a request that says 'anything new?'. This is polling, and it technically works — but it's wasteful and laggy in a way that gets worse the more real-time you want to be. Walk through why:

  • Too slow or too chatty. Poll every 10s and updates lag up to 10s. Poll every 100ms to feel instant and you send 10 requests a second per client, most returning 'nothing new'.
  • Mostly wasted work. Each poll is a full HTTP request — headers, maybe a TLS handshake, a server lookup — just to usually hear 'no change'. Multiply by millions of clients.
  • Still one-directional per request. The client always has to speak first; the server can only answer the poll it was given, never push on its own schedule.
  • The server can't reach you between polls. If something urgent happens 50ms after your last poll, it waits in line until your next one.
Polling: ask again and again, mostly to hear 'nothing new' (javascript)
// The client has to keep asking — it can never just be told.
setInterval(async () => {
  const res = await fetch("/messages?since=" + lastSeenId);
  const updates = await res.json();
  if (updates.length) render(updates);   // usually EMPTY — wasted round trip
}, 3000);  // every 3s: laggy if longer, chatty if shorter — no good answer

// 1M clients polling every 3s = ~330k requests/sec of mostly-empty checks.

Long polling softens this — the server holds the request open and only answers when it has news — but you're still paying to re-open a connection after every message, and it's still fundamentally the client asking. WebSockets remove the asking entirely: open one connection, keep it, and let the server push the instant it has something.

Polling re-asks on a timer; a WebSocket holds one open line for instant two-way pushes.

The idea: one open, two-way line

A WebSocket is a single TCP connection that, once opened, stays open and lets either side send a message at any time — no new request per message, no polling, no waiting your turn. 'Bidirectional' is the key word: unlike a request/response where the client always leads, a WebSocket is symmetric. The server can push a chat message the same moment the client is sending a keystroke, both over the one connection.

Think back to the phone call: dialling (the handshake) happens once and costs a little setup, but after that, talking is free and instant in both directions for as long as the line is up. That's the trade WebSockets make — a bit of setup and the burden of holding the line open, in exchange for instant, cheap, two-way messages.

Start with an HTTP upgrade, then keep one connection open for two-way messages.

How a WebSocket begins — the upgrade handshake

A WebSocket doesn't start from scratch — it starts as an ordinary HTTP request that politely asks to be upgraded into a WebSocket. Reusing HTTP for the opening move is deliberate: it sails through firewalls, proxies, and ports 80/443 that already allow web traffic. Here's the exchange, step by step:

  • The client sends a normal HTTP request with an Upgrade header — 'let's switch this connection to a WebSocket.'
  • The server, if it agrees, replies with 101 Switching Protocols instead of the usual 200.
  • From that moment the same TCP connection is no longer HTTP — it's a WebSocket, and both sides send messages freely with no request/response ceremony.
  • Either side can send a close frame to end it cleanly.
The upgrade handshake (HTTP in, WebSocket out) (http)
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
# connection stays open from here — both sides send whenever they like

Using it from the client

The browser API hides the handshake entirely — you create a socket, then react to a few events. The mental shift from HTTP is that there's no single 'response': messages arrive whenever the server decides to push them.

Client: open once, then react to pushes (javascript)
const ws = new WebSocket("wss://example.com/chat");

ws.onopen = () => ws.send(JSON.stringify({ join: "room-42" }));

// the server pushes anytime — no polling, no new request
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  renderMessage(msg);
};

ws.onclose = () => reconnectWithBackoff();   // a dropped socket must be re-established

Keeping the line alive — heartbeats

A WebSocket that's open but silent is indistinguishable, to the network, from one that's quietly dead — and idle connections get culled by proxies and load balancers. The fix is a heartbeat: the server periodically sends a tiny ping frame and expects a pong back. No pong within a timeout means the connection is gone, so the server frees it and the client reconnects.

Server-side heartbeat to detect dead connections (javascript)
// Mark every socket alive on each pong; ping on an interval.
wss.on("connection", (ws) => {
  ws.isAlive = true;
  ws.on("pong", () => { ws.isAlive = true; });   // client answered — still here
});

setInterval(() => {
  for (const ws of wss.clients) {
    if (!ws.isAlive) return ws.terminate();  // missed last pong -> it's dead, drop it
    ws.isAlive = false;                      // reset; expect a pong before next tick
    ws.ping();                               // tiny keep-alive probe
  }
}, 30000);  // every 30s: frees zombie connections and keeps proxies from idling us out

When to reach for it (and when not to)

NeedBest fitWhy
Two-way, high-frequency, real-timeWebSocketBoth sides push instantly over one open connection
Server → client only (live updates)Server-Sent EventsSimpler; runs over plain HTTP; auto-reconnect
Occasional updates, simple setupLong pollingNo persistent infra; works everywhere
One-off request/responsePlain HTTPNo reason to hold a connection open

The honest default is: don't use a WebSocket unless you truly need the server to push, often, and in both directions. If updates only flow server→client, Server-Sent Events give you most of the benefit with far less operational weight — they run over ordinary HTTP and reconnect automatically. Reserve WebSockets for the genuinely interactive cases: chat, collaborative editing, multiplayer, live trading.

The gap a single server can't fill

Here's where WebSockets get genuinely hard, and it's worth seeing why rather than just memorizing the fix. One server can hold maybe tens of thousands of open sockets. The moment you need more, you add servers — and now users who want to talk to each other are connected to different machines.

Imagine Alice is connected to server A and Bob to server B, both in 'room-42'. Alice sends a message. Server A has the socket to Alice, but it has no socket to Bob — Bob lives on server B. So how does Bob's screen update? Server A can't reach him directly. This is the central scaling problem of WebSockets: a message's destination is almost never on the same box as its source.

The fix is a shared backplane — a pub/sub layer every connection server subscribes to. Server A publishes 'room-42: hello' to the backplane; every server (including B) is subscribed to room-42, so B receives it and pushes it down its socket to Bob. No server needs to know which box holds which user; they just publish and subscribe through the shared channel.

Backplane: publish to a shared channel, every server fans out locally (javascript)
// Alice's message arrives on server A. A does NOT know Bob is on server B.
onMessage(ws, msg) {
  redis.publish("room:" + msg.room, JSON.stringify(msg));  // hand to the backplane
}

// EVERY connection server subscribes and pushes to its OWN local sockets.
redis.subscribe("room:42", (payload) => {
  const msg = JSON.parse(payload);
  for (const ws of socketsInRoom("42")) {  // only the sockets THIS server holds
    ws.send(payload);                       // Bob gets it on server B this way
  }
});

Scaling WebSockets

  • Connection tier: dedicated servers whose job is just holding sockets (one box handles ~tens of thousands).
  • Sticky routing: the load balancer keeps a connection on its server for its lifetime (see Load balancing).
  • A registry: track which server holds which user's connection so you can route a message to the right place (see Service discovery).
  • A backplane: to broadcast to users across many servers, publish through a shared pub/sub layer.
Scaling challengeWhy it hurtsThe fix
Load balancer breaks connectionsA normal round-robin LB may send WebSocket frames to a server with no matching socketSticky / connection-aware routing pins each socket to its server
A server diesEvery socket it held drops at onceClients reconnect with backoff; a registry re-routes them
Users spread across serversThe recipient's socket is on a different box than the sender'sA pub/sub backplane fans messages to all connection servers
Memory per connectionOpen sockets consume RAM even when idleA dedicated connection tier sized for socket count, not CPU

WebSockets are the enabling technology for 'live' on the web — the shift from request/response to a persistent conversation.

Why it matters

  • They make real-time features (chat, collaboration, live data) possible at all.
  • They force you to confront stateful servers — a sharp contrast to the stateless tiers everywhere else.
  • They're the concrete mechanism behind the 'push, don't poll' principle.

If ignored

  • You resort to polling for real-time needs — laggy and wasteful.
  • You treat WebSocket servers as stateless and the load balancer sends messages to the wrong box.
  • You forget the backplane and can't broadcast to users spread across servers.

Where it fits

  • A dedicated, stateful connection tier in front of stateless services.
  • Behind a load balancer configured for sticky, long-lived connections.
  • Paired with a registry and pub/sub backplane for routing and broadcast.

Related topics

Interview lens

Questions it unlocks

  • How would you build live updates / real-time features?
  • WebSocket, SSE, or long polling — which and why?
  • What makes WebSockets hard to scale?

60-second answer

Plain HTTP can't let the server push, so for real-time I use WebSockets — one long-lived, bidirectional connection started by upgrading an HTTP request. I'd reach for them when I need high-frequency two-way communication like chat or collaboration, use Server-Sent Events when it's one-way server push, and long polling only as a fallback. The catch is that connections are stateful: I need a dedicated connection tier, sticky load balancing, a registry to route messages to the right server, and a pub/sub backplane to broadcast across servers. The protocol's easy; scaling the open connections is the real work.

Common traps

  • Reaching for WebSockets when one-way SSE would be simpler.
  • Treating WebSocket servers as stateless and breaking message routing.
  • Forgetting the backplane needed to broadcast across many connection servers.

Search topics

↑↓ to move · Enter to open · Esc to close