Video in progress

What does WebSocket being stateful mean for the server side?

From the moment a client connects until it disconnects, it is tied to one specific server instance, which holds its session, buffers and socket. So the simple REST model, "every request can go to any instance", doesn't work.

📖 Answer

In REST a request comes in, a response goes out, and the server remembers nothing, so the load balancer can spread requests around however it likes.

With WebSocket:

  • if 10,000 users are connected, the server holds 10,000 open sockets and WebSocketSession objects;
  • if the server restarts, everyone is disconnected and tries to reconnect at the same moment;
  • if user A is on server-1 and B is on server-2, delivering a message from A to B needs some shared channel between the servers (Redis, RabbitMQ, Kafka);
  • during a deploy you have to think about how to move connections over gracefully.

In practice, this is why the WebSocket service is often split out into its own service: it only holds the connections, while the business logic stays in ordinary stateless services.