Video in progress

The app was scaled to two instances, and some chat messages aren't reaching some users. How do you explain the cause, and what do you do?

registry.enableSimpleBroker("/topic");

@MessageMapping("/room.{id}.send")
public void send(@DestinationVariable String id, ChatMessage m) {
    messaging.convertAndSend("/topic/room." + id, m);
}

The simple broker lives in each instance's memory. A message goes only to subscribers on the instance the writer is connected to; those on other instances never see it. The fix is a shared channel between instances: a STOMP broker relay, or fan-out to every instance through Redis pub/sub or Kafka.

📖 Answer

The load balancer spread the clients round-robin: of the 10 people in a room, 5 are on A and 5 on B. When someone on A writes, convertAndSend goes to A's local broker, and only the 5 people on A receive it. That is exactly the "some don't get it" symptom.

Two main routes:

1. Broker relay (RabbitMQ / ActiveMQ STOMP). Subscriptions live in the external broker, and Spring is only a proxy. The code barely changes. The downside is a TCP connection to the broker for every client session.

2. Your own fan-out. Each instance keeps a local simple broker, but a message is first published to a Redis channel, and every instance listens to it and distributes to its own local clients:

public void send(String room, ChatMessage m) {
    redis.convertAndSend("chat:" + room, m);          // to all instances
}

// on every instance
public void onRedisMessage(String room, ChatMessage m) {
    messaging.convertAndSend("/topic/room." + room, m); // to local clients only
}

With this option the number of connections on the broker equals the number of instances, not the number of clients, which is much cheaper for a large audience.

Redis pub/sub is fire-and-forget: if an instance happens to be disconnected at that moment, the message is lost. If the chat history is in the database and the client fetches it on reconnect, that is acceptable. If you need a guarantee, use Redis Streams or Kafka.

Also check this: convertAndSendToUser has the same problem. Spring has the settings setUserDestinationBroadcast and setUserRegistryBroadcast for it (they work only with the relay).