Video in progress
In Spring STOMP, is the order of messages from or to one client preserved?
By default there is no guarantee: clientInboundChannel and clientOutboundChannel use thread pools, and consecutive messages from one session can be processed in parallel on different threads. Since Spring 5.1 setPreservePublishOrder(true), and since 6.1 setPreserveReceiveOrder(true), keep the order per session.
📖 Answer
The symptom: the client sends typing, then message, then read, and the server processes them in the order message, read, typing. Or the server sends prices 100, 101, 102, the client receives 100, 102, 101, and a stale price stays on the screen.
The cause is the thread pool. Two messages from one session land on two different workers, and the second may finish first.
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setPreservePublishOrder(true); // server → client
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws");
registry.setPreserveReceiveOrder(true); // client → server (Spring 6.1+)
}
The cost: messages from one session now run sequentially. If processing one client's message is slow, that client's later messages wait. Other sessions are not affected.
But this is only ordering inside Spring. If messages come from an external broker, from several instances, or from different sources, the overall order is still not guaranteed. So in important places I add a seq or version to the payload, and the client simply ignores an older version. That works in any architecture.
Sign up to mark studied questions and save your progress.