WebSockets
Live Order status — packing, shipped, delivered — feels best over a persistent connection instead of frantic polling.
Introduction
Live Order status — packing, shipped, delivered — feels best over a persistent connection instead of frantic polling.
Spring Boot supports WebSockets and the STOMP messaging abstraction: clients connect to an endpoint, send to /app/..., and subscribe to /topic/... destinations.
The simple in-memory broker works for one instance. Multiple Orders replicas need an external broker (RabbitMQ, Redis) so broadcasts reach every connected user.
This lesson adds a status feed for TechLearningPRO Orders with Boot 3 and Java 21.
Purpose of this lesson
Expose STOMP-over-WebSocket order status updates and understand broker scaling on Boot 3.
Understanding the topic
WebSockets carry frames; STOMP adds destination-based messaging.
- endpoint: e.g.
/wswith optional SockJS fallback. - application prefix:
/appfor inbound@MessageMapping. - broker: simple broker or external for clusters.
- user destinations: push to a specific principal.
- auth: authenticate the handshake; do not leave origins wide open in prod.
Step-by-step explanation
- Add WebSocket messaging starter and
@EnableWebSocketMessageBroker. - Register
/wsand configure broker prefixes. - Publish
OrderStatusChangedto/topic/orders/{id}from the service. - Restrict allowed origins and require an authenticated principal on connect.
Informative example
STOMP config and order status broadcast.
@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint("/ws").setAllowedOriginPatterns("https://app.techlearningpro.example").withSockJS();}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {registry.enableSimpleBroker("/topic", "/queue");registry.setApplicationDestinationPrefixes("/app");}}@Controllerpublic class OrderStatusController {@MessageMapping("/orders/status")@SendTo("/topic/orders")public OrderStatusMessage publish(OrderStatusMessage msg) {return msg;}}@Servicepublic class OrderStatusPublisher {private final SimpMessagingTemplate template;public OrderStatusPublisher(SimpMessagingTemplate template) {this.template = template;}public void pushed(long orderId, String status) {template.convertAndSend("/topic/orders/" + orderId, new OrderStatusMessage(orderId, status));}}
Real-world use
Support dashboards polled GET /api/orders/{id} every second and overloaded the DB. A STOMP topic per order cut traffic dramatically; moving to RabbitMQ as an external broker kept updates consistent across three API pods.
Security implications
WebSockets bypass some HTTP-only controls if misconfigured.
- Validate JWT/session on connect and bind subscriptions to ownership.
- Tight origin allow-lists for browser clients.
- Do not put secrets in STOMP payloads or destination names.
Best practices
- Authenticate handshake; authorize destination subscriptions.
- External broker for horizontal scale.
- Keep payloads small — ids and status enums, not full entity graphs.
Common mistakes
- Using
setAllowedOriginPatterns("*")in production. - Simple broker with multiple replicas — clients miss messages on other pods.
- Pushing status without checking the subscriber is allowed to see that order.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy use STOMP on top of WebSockets?+
Answer
2IntermediateQuestionWhen is the simple broker insufficient?+
Answer
3AdvancedQuestionHow do you authorize per-order topics?+
Answer
Hands-on exercise
Lab. Enable STOMP at /ws. On order status change, publish to /topic/orders/{id}. Connect a test client and confirm only that topic receives the event. Document what breaks with two app instances on the simple broker.
Summary
WebSockets give TechLearningPRO Orders real-time status channels — STOMP for structure, external brokers for scale, auth on every connect.