Websockets and load balancing

html, java, javascript, spring, websocket

Solution

The message brokers can be used without STOMP, take for example the RabbitMQ broker, it can be used with several other protocols; HTTP, AMQP, MQTT, AMQP. You can use them as a JMS implementation.

As there are several instances of the application, the best alternative is really having a central messaging broker for handling messages that need to be published to the clients of all applications.

Any alternative would imply doing something similar by hand, the servers in the backend need to communicate and notify each other of those events in some way. An alternative would be to write to the database certain events and have each server poll some table, but that is the type of design we try to avoid.

Also concerning load balancing and web sockets, the load balancer needs to be configured to allow forwarding of the HTTP Upgrade headers, which is usually off by default. For example nginx needs some configuration to allow forwarding of the these headers, otherwise Websockets won't work.

In that case SockJS will automatically use some of the fallback options that kick in when web sockets are not possible.

Problem

Spring and Java EE have nice support for websockets. For example in Spring you can have: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new MyHandler(), "/myHandler") .addInterceptors(new HttpSessionHandshakeInterceptor()); } } ``` And with `MyHandler` class you can send and listen for messages to HTML5 websocket. ``` var webSocket = new WebSocket('ws://localhost:8080/myHandler'); webSocket.onmessage = function(event) { onMessage(event) }; ``` The problem is if you run multiple servers behind a load balancer. The clients of server A will not be notified for events on server B. This problem is solved in Spring by using message broker with Stomp protocol (http://assets.spring.io/wp/WebSocketBlogPost.html) Since using the handler and "native" html5 websockets looks easier to me then the Stomp way, my questions are: - Is it posible to use the message broker without the Stomp protocol? - Are there any other options to overcome the load balancing issue?

Original source