Video in progress

Do you need sticky sessions on the load balancer for WebSocket? What about when SockJS is used?

For pure WebSocket, usually not: the connection is a single TCP connection, so it stays on the server where it was opened. With SockJS's HTTP fallback transports, one session consists of many separate HTTP requests, and they must land on the same server, so sticky sessions are required.

📖 Answer

With WebSocket, whichever backend gets the handshake serves the whole life of the connection. The load balancer can't move a TCP connection to another server midway. So the "stickiness" is built in.

With SockJS the situation is different. In the xhr-polling transport the client sends each message as a new POST and waits with a new GET. The URL contains a server and session ID (/ws/123/abcxyz/xhr), but the load balancer doesn't know that. If the next request lands on a different instance, it doesn't recognize the session and returns 404. So you need:

  • sticky sessions based on a cookie (for example JSESSIONID or the LB's own cookie);
  • or routing by a hash of the session ID in the URL.

But don't mix up one thing: sticky sessions don't solve the problem of "a message reaches a user on another instance". They only pin one client's requests to one server. Fan-out between instances is still done through a broker relay or pub/sub.

Another practical aspect is uneven distribution. WebSocket connections live for hours. If you add a new instance, the old connections stay where they are and the new server sits almost empty. A "least connections" algorithm instead of round-robin, plus occasionally and carefully redistributing connections, softens this problem.