Video in progress
What happens if two threads call sendMessage() on the same WebSocketSession at the same time?
// called from a separate thread pool for each event
@Async
public void onPriceChanged(Price p) {
for (WebSocketSession s : sessions) {
s.sendMessage(new TextMessage(toJson(p)));
}
}
A standard JSR-356 session doesn't support concurrent sending: you get an IllegalStateException (with a state like "TEXT_FULL_WRITING") or the frames get interleaved. In Spring the fix is to wrap the session in a ConcurrentWebSocketSessionDecorator, or to funnel all sends through a single thread.
📖 Answer
The price changes 50 times a second, and because of @Async several threads write to one session at once. On Tomcat the result is an unexpected IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING]. You won't see it in a local test with one user; it shows up in prod under load.
Spring's ready-made fix:
@Override
public void afterConnectionEstablished(WebSocketSession session) {
WebSocketSession safe = new ConcurrentWebSocketSessionDecorator(
session,
10_000, // sendTimeLimit, ms
512 * 1024); // bufferSizeLimit, bytes
sessions.add(safe);
}
The decorator queues the sends, and only one thread actually writes to the socket at a time. Bonus: if the client is slow and the buffer fills up, it closes the session, so one bad client doesn't slow down the whole server.
If you use STOMP, Spring does this internally. This problem mostly shows up in code written against a raw WebSocketHandler.
Sign up to mark studied questions and save your progress.