Video in progress
Can one slow client make the server run out of memory? How do you handle backpressure in WebSocket?
Yes. The server writes fast, the client reads slowly, and messages pile up in the session buffer on the server. The defense: a buffer and time limit per session, closing the session or dropping old messages when it fills up, and sending data as "the latest state" rather than "every change".
📖 Answer
The WebSocket protocol itself has no application-level backpressure. TCP has it: if the client doesn't read, the TCP window fills up and the server can't write to the socket. But the server code keeps calling send anyway, and messages queue up in memory.
In Spring, for a raw handler:
WebSocketSession safe = new ConcurrentWebSocketSessionDecorator(
session, 5_000, 256 * 1024,
ConcurrentWebSocketSessionDecorator.OverflowStrategy.DROP);
TERMINATE(the default): when the limit is exceeded, the session is closed. The client reconnects and gets the state from scratch. Right for chat and orders: no message is silently lost.DROP: the oldest messages in the buffer are dropped. Good for things like exchange prices or GPS coordinates, where the old price isn't needed anyway.
In STOMP the same thing is controlled with setSendBufferSizeLimit and setSendTimeLimit, and a session that goes over the limit is closed.
Even more effective is changing the data design. If a price changes 100 times a second, don't send every change: on the server, send only the last value within a 200 ms window (conflation). The load drops 20 times and the user doesn't notice the difference.
For monitoring I export the per-session buffer size, or the reasons sessions were closed (CloseStatus.SESSION_NOT_RELIABLE), as a metric. That shows the share of users on bad networks.
Sign up to mark studied questions and save your progress.