Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 57

    WebSockets

    Live Order status — packing, shipped, delivered — feels best over a persistent connection instead of frantic polling.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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. /ws with optional SockJS fallback.
    • application prefix: /app for 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

    1. Add WebSocket messaging starter and @EnableWebSocketMessageBroker.
    2. Register /ws and configure broker prefixes.
    3. Publish OrderStatusChanged to /topic/orders/{id} from the service.
    4. Restrict allowed origins and require an authenticated principal on connect.

    Informative example

    STOMP config and order status broadcast.

    java
    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws")
    .setAllowedOriginPatterns("https://app.techlearningpro.example")
    .withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic", "/queue");
    registry.setApplicationDestinationPrefixes("/app");
    }
    }
    @Controller
    public class OrderStatusController {
    @MessageMapping("/orders/status")
    @SendTo("/topic/orders")
    public OrderStatusMessage publish(OrderStatusMessage msg) {
    return msg;
    }
    }
    @Service
    public 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.

    3 questions
    1BeginnerQuestionWhy use STOMP on top of WebSockets?+

    Answer

    STOMP adds destination routing, subscription semantics, and broker integration instead of raw frame handling.
    2IntermediateQuestionWhen is the simple broker insufficient?+

    Answer

    When multiple application instances must share subscriptions/broadcasts — use an external broker.
    3AdvancedQuestionHow do you authorize per-order topics?+

    Answer

    Authenticate the handshake and intercept subscribe frames to ensure the principal owns the order id in the destination.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.