Video in progress

Compare polling, long polling and WebSocket for delivering a new message to the client in a chat app.

With polling, the client asks every few seconds "any new messages?". With long polling, the request stays open until a message appears. A WebSocket is one persistent two-way connection, and the server pushes the message right away. For chat you usually pick WebSocket.

📖 Answer

Plain polling is the simplest, but wasteful. If 1 million online users ask every 3 seconds, that's ~330,000 RPS, and most of the answers are empty: "nothing new". On top of that, a message can be delayed by up to 3 seconds.

Long polling — the server holds the response: it replies when a message arrives or after 30 seconds, and the client immediately opens a new request. Latency is low and there are fewer empty responses. It runs over plain HTTP, so it also gets through old proxies.

WebSocket — one TCP connection stays open and either side sends a message at any time. Latency is minimal, and headers aren't sent every time.

The cost of WebSocket:

  • every connection takes memory on the server, and you end up with a huge number of connections;
  • the load balancer has to support long-lived connections;
  • you need to know which server a user is connected to — a message to a user on another server is relayed through Redis Pub/Sub or a broker.

If you only need a stream from server to client (notifications, prices), Server-Sent Events is also a good and simpler option.