Card 05/ 10

ConceptDifficulty: Intermediate1 min

WebSockets: A Two-Way Connection That Stays Open

Either side can send at any moment, which is what chat and games need.

A WebSocket is one long-lived connection between a client and a server that carries messages both ways, at any moment, without a new request for each. It begins as an HTTP request asking to upgrade, and once the server agrees, the same connection stops speaking HTTP and carries small messages in either direction until one side closes it.

Who starts, and which way. The client opens the connection. After that, either side sends whenever it has something, and neither waits for the other.

From the upgrade request to messages both ways

What it costs the server. One open connection per client, for as long as the client stays, and memory for each. Because a connection belongs to one server, a message for a user must reach the server that holds their connection, often through a shared message channel between servers. A deploy or restart drops every connection on that server, and all of those clients reconnect at once.

What it does not do for you. Unlike server-sent events, a WebSocket has no built-in resume. If it drops, the client must reconnect and ask for what it missed, which the application has to design.

WebSockets

Use it when

  • Both sides send often, such as chat, collaborative editing or multiplayer games
  • Messages are small and frequent, so a request for each would cost more than the message

Avoid it when

  • Only the server sends, where server-sent events do the job with less to build
  • Updates are rare, so an open connection per client buys little

One product that uses it. Slack's Socket Mode delivers events to an app over a WebSocket the app opens, so the app needs no public address.

So choose WebSockets when both sides talk often, and plan for reconnection and for routing messages to the server that holds each connection.