Networking
Intermediate 9 min read

WebSockets & real-time communication

In one line

WebSockets upgrade one HTTP connection into a long-lived, two-way channel so the server can push messages instantly, instead of the client repeatedly asking whether anything changed.

What it is

Plain HTTP is request-response: the server can only answer when the client asks. Real-time features such as chat, live scores, collaborative editing and notifications need the server to push data as soon as it exists.

A WebSocket starts as an HTTP request with an Upgrade header. If the server agrees, it replies 101 Switching Protocols and the same TCP connection becomes a full-duplex channel: either side can send small framed messages (text or binary) at any time, with only a few bytes of overhead each.

Alternatives are short polling (ask every few seconds), long polling (the server holds the request open until there is news), and Server-Sent Events (a one-way stream from server to client over plain HTTP). WebSockets are the usual choice when both sides send frequently.

Why interviewers ask

Interviewers ask about WebSockets in chat, notification and live dashboard designs. They want to see that you can compare polling, long polling, SSE and WebSockets, and that you know the hard parts: scaling millions of long-lived connections, routing a message to the server that holds a user's socket, reconnection and missed messages.

How it works

  1. 1The client sends an HTTP GET with headers Connection: Upgrade, Upgrade: websocket, Sec-WebSocket-Version: 13 and a random Sec-WebSocket-Key (use wss:// so it runs over TLS).
  2. 2The server replies 101 Switching Protocols with Sec-WebSocket-Accept, a hash derived from the client's key, proving it understood the WebSocket request.
  3. 3From now on both sides exchange frames over the same TCP connection. Each frame has a small header (2 to 14 bytes) with the type (text, binary, ping, pong, close) and length; frames from the browser to the server are masked.
  4. 4Ping and pong frames act as heartbeats to detect dead connections and keep proxies and NAT devices from closing idle connections.
  5. 5Either side ends the session with a close frame. If the connection drops, the client reconnects with exponential backoff and asks for messages it missed since its last received id.

Worked example · Two users chatting through two servers

  1. Alice's phone opens wss://chat.app/ws and gets 101. The load balancer placed her on server S1. Bob's laptop is connected to server S2.
  2. S1 and S2 both subscribe to a Redis pub/sub channel per conversation, here room:42.
  3. Alice sends the frame {type: msg, room: 42, text: Hi}. S1 stores it in the database with id 1001, then publishes it to room:42.
  4. S2 receives the published message and pushes a frame to Bob's open socket. Bob sees it about 50 ms after Alice hit send, with no polling.
  5. Bob's Wi-Fi drops for 20 seconds. His client reconnects (now to S1), sends last_seen=1001 and receives messages 1002 to 1005 from the database before live delivery resumes.
  6. With 2-second polling instead, each of 100,000 idle users would send 50,000 requests per second just to hear 'nothing new'.

Picture it

Polling is calling a shop every five minutes to ask whether your order is ready. Long polling is calling and staying on hold until it is. A WebSocket is an open phone line where either of you can speak whenever there is news.

Key patterns

Choose the lightest real-time option

When: Designing push features

How: Rare updates: polling. One-way server stream: SSE. Frequent two-way messages: WebSockets. Media or lossy game state: WebRTC or UDP.

Pub/sub fan-out across servers

When: More than one WebSocket server

How: Servers subscribe to channels for the users they hold; events are published once and delivered by the right server.

Resume from last id

When: Mobile clients with unstable networks

How: Give every message a sequence id; clients reconnect with the last id seen and the server replays the gap.

Heartbeats and backoff

When: Detecting dead connections and avoiding reconnect storms

How: Ping and pong every 20 to 60 seconds; reconnect with exponential backoff plus random jitter.

Real-world use

Chat apps

Slack and Discord keep a persistent WebSocket (Discord calls its connection the gateway) for each client to deliver messages, typing indicators and presence in real time.

Trading and crypto exchanges

Exchanges like Binance and Coinbase stream live prices and order book updates over public WebSocket APIs, because polling would be both slower and far more expensive.

Collaborative tools

Figma, Google Docs-style editors and multiplayer whiteboards send each user's edits and cursor positions over persistent connections so others see changes within milliseconds.

Server-Sent Events for one-way streams

Many AI chat interfaces stream generated text to the browser with Server-Sent Events, since data only flows from server to client and SSE works over normal HTTP with automatic reconnection.

In a project

You are adding live order tracking and support chat to a delivery app with 200,000 users online at peak.

  1. Run a separate gateway service that only holds WebSocket connections, so API deploys do not drop sockets; size it for about 50,000 connections per server and run 6 to 8 servers.
  2. Use a pub/sub layer (Redis or Kafka) keyed by user and order id so any backend event reaches whichever gateway server holds the user's socket.
  3. Store messages durably with increasing ids; on reconnect the client sends its last id and gets what it missed.
  4. Send heartbeats every 30 seconds, reconnect with exponential backoff and jitter, and fall back to SSE or long polling on networks that block WebSockets.
  5. Authenticate on connect with a short-lived token and re-check permissions per subscription.

Impact: Order status and messages appear in under a second instead of on the next 10-second poll, request volume to the API falls sharply, and dropped connections no longer lose messages.

Trade-offs

Use it when

  • Frequent messages in both directions (chat, multiplayer editing, games over TCP)
  • The server must push updates with low latency
  • Many updates per second where per-request HTTP overhead would add up

Avoid it when

  • Data only flows server to client; SSE is simpler and works with standard HTTP tooling
  • Updates are rare (every few minutes); polling is simpler to run and scale
  • Plain request-response APIs; WebSockets lose HTTP caching, status codes and easy load balancing

Cost: One handshake per connection, then 2 to 14 bytes of framing per message. Each open connection costs server memory (often tens of KB), so capacity is planned in concurrent connections, not requests per second.

Common mistakes

  • Ignoring how a message reaches a user connected to a different server; you need pub/sub or a routing table.
  • Assuming connections stay up; mobile networks drop them often, so you need heartbeats, reconnection and replay.
  • Using WebSockets for everything, including simple CRUD calls that are better as normal HTTP.
  • Forgetting authentication and authorisation on the socket and on each subscription.
  • Believing WebSockets run over UDP; they run over TCP (and TLS for wss).

Interview questions

Quick revision

  • WebSocket: HTTP Upgrade, 101 Switching Protocols, then full-duplex frames over TCP.
  • Use wss:// (TLS) in production.
  • Frames: text, binary, ping, pong, close; small 2 to 14 byte headers.
  • Short polling < long polling < SSE (one-way) < WebSocket (two-way).
  • Scale with connection gateways plus pub/sub fan-out.
  • Heartbeats, backoff with jitter, resume from last message id.
  • Capacity is measured in concurrent connections.

Check yourself

1. Which status code does a server send to accept a WebSocket upgrade?

2. A dashboard only needs the server to stream new metrics to the browser. What is the simplest good fit?

3. Alice is connected to server 1 and Bob to server 2. How does Alice's message reach Bob?

4. Which transport protocol do WebSockets use?

Saved on this device. Create a free account to keep it on every device.

Practise this with Sam

A real mock interview, out loud, with an honest scorecard. Free to start.

Start free