How WebSockets differ from polling

· 2 min read

#how-it-works#web

A WebSocket is one connection between a client and a server that stays open and carries messages in both directions. The idea to keep: with polling the client has to ask every time, and with a WebSocket either side can speak once the connection is open.

The short version

With polling, the client keeps asking the server whether there is something new, and the server answers with an empty reply when there is not. Long polling makes the server hold each request until it has something to say, but every message is still a full HTTP request and response. A WebSocket starts as one HTTP request. After that the same TCP connection stays open, and both sides send small frames whenever they like.

Polling compared with a WebSocket Top row, polling: the client asks the server and gets an empty reply, then asks again. Bottom row, WebSocket: the client sends a GET with an Upgrade header, the server answers 101 Switching Protocols, then frames travel in both directions. Polling Client Server 1 ask 2 empty reply, ask again WebSocket Client Server 1 GET + Upgrade 2 101 Switching Protocols 3 frames both ways
Simplified: polling repeats the ask and the reply, a WebSocket does the handshake once and then talks both ways.

Step by step

  1. The client sends an HTTP GET request with an Upgrade: websocket header.
  2. The server answers 101 Switching Protocols. Any other status means the handshake did not complete.
  3. The TCP connection stays open.
  4. Either side sends messages, each made of one or more frames, whenever it wants.
  5. Either side can end the connection with a Close frame.
Short polling Long polling WebSocket
Who starts an exchange the client the client either side, after the handshake
Empty replies yes, when nothing is new no, the server waits for an event or a timeout no requests to answer
Headers on every message full HTTP headers full HTTP headers small frame fields

Why it matters

Polling is simple but most questions can come back empty, while a WebSocket pushes data at once, and MDN notes that its API has no backpressure, so messages that arrive faster than the app can handle them can fill memory.

Sources