← All chapters
Chapter 23· 7 min read · illustrated

WebSockets

A persistent, two-way channel for real-time apps

Plain HTTP can only answer when asked — the server cannot start a message on its own. For chat, live dashboards, and multiplayer games that is a problem. WebSockets solve it with a persistent, full-duplex connection.

01

HTTP cannot push

In classic HTTP the client must initiate everything. To get updates, apps resort to polling — asking "anything new?" over and over. It is wasteful and laggy: most requests return nothing, and real updates wait until the next poll.

Tap to enlarge
02

What is a WebSocket?

A WebSocket is a single, long-lived connection that stays open and allows full-duplex communication — both client and server can send messages at any time, independently. No repeated requests, no waiting for a poll.

Tap to enlarge
03

It starts as HTTP

A WebSocket begins life as a normal HTTP request with an Upgrade: websocket header. If the server agrees, it responds with 101 Switching Protocols, and that same TCP connection is now a WebSocket. Reusing HTTP for the handshake means it works through existing web infrastructure.

Tap to enlarge
04

Both sides push

Once open, either side can send whenever it wants. The server can push a new chat message, a price tick, or a game state the instant it happens — no request required. This is what makes truly real-time experiences possible.

Tap to enlarge
05

Where WebSockets fit

  • Chat and messaging apps.
  • Live dashboards, scores, and notifications.
  • Multiplayer games and presence.
  • Collaborative editors (shared cursors, live edits).
Tap to enlarge
06

WebSocket vs polling

Compared with polling, a WebSocket is far more efficient and lower-latency: one open connection instead of a flood of near-empty requests, and updates arrive the moment they occur. The trade-off is that long-lived connections need managing (reconnects, scaling), which is why simple cases may still use polling or Server-Sent Events.

Tap to enlarge