BBackend CourseLeroy Labs
0/0
Search the course

Real-time with polling, SSE, WebSockets/STOMP & Web Push

Choosing between polling, Server-Sent Events and WebSockets, STOMP destinations and user queues, authenticating CONNECT frames, heartbeats, presence, VAPID/FCM/Expo push, and why in-memory brokers do not scale out.

● advancedReport-Manager-2Hostel-Web-AppIR3D (Kontentt)

The options

Technique Direction Transport Good for
Polling Client pulls every N seconds HTTP Simple dashboards; wasteful
Long polling Server holds the request until there’s data HTTP Legacy fallback
SSE (Server-Sent Events) Server → client only One long HTTP response (text/event-stream) Notifications, progress bars, live feeds
WebSocket Bidirectional Upgraded TCP connection Chat, typing indicators, presence, collaboration
Web Push Server → device, even when the tab is closed Browser vendor push service Re-engagement, alerts

SSE

private final Map<UUID, SseEmitter> emitters = new ConcurrentHashMap<>();

@GetMapping(path = "/api/notifications/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter stream(@AuthenticationPrincipal User u) {
    SseEmitter em = new SseEmitter(Long.MAX_VALUE);
    emitters.put(u.getId(), em);
    em.onCompletion(() -> emitters.remove(u.getId()));
    em.onTimeout(() -> emitters.remove(u.getId()));
    return em;
}

void push(UUID userId, NotificationDto n) throws IOException {
    SseEmitter em = emitters.get(userId);
    if (em != null) em.send(SseEmitter.event().name("notification").data(n));
}

The browser side is new EventSource('/api/notifications/stream', { withCredentials: true }), and it reconnects automatically.

WebSocket with STOMP

STOMP is a small messaging protocol over WebSocket: CONNECT, SUBSCRIBE /topic/x, SEND /app/y.

@Configuration @EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    public void registerStompEndpoints(StompEndpointRegistry r) { r.addEndpoint("/ws-chat").setAllowedOriginPatterns(frontend); }
    public void configureMessageBroker(MessageBrokerRegistry r) {
        r.enableSimpleBroker("/topic", "/queue");    // in-memory broker
        r.setApplicationDestinationPrefixes("/app");  // client -> @MessageMapping
        r.setUserDestinationPrefix("/user");
    }
    public void configureClientInboundChannel(ChannelRegistration reg) { reg.interceptors(jwtInterceptor); }
}

// interceptor: authenticate the CONNECT frame (browsers can't set headers on the WS upgrade)
public Message<?> preSend(Message<?> m, MessageChannel c) {
    var acc = MessageHeaderAccessor.getAccessor(m, StompHeaderAccessor.class);
    if (StompCommand.CONNECT.equals(acc.getCommand()))
        acc.setUser(jwtService.authenticate(acc.getFirstNativeHeader("Authorization")));
    return m;
}

// send to one user
messagingTemplate.convertAndSendToUser(userId.toString(), "/queue/notifications", dto);

In your projects

Report-Manager-2notification/application/SseEmitterService.java · SseCommittedResponseFilter · SseHeartbeatScheduler

SSE for in-app notifications, using ConcurrentHashMap<UUID, SseEmitter> and new SseEmitter(Long.MAX_VALUE). A heartbeat every 25 seconds keeps proxies and load balancers (which often cut idle connections at 30–60 s) from closing the stream. Client disconnect errors are deliberately ignored in the global handler.

Hostel-Web-AppWebSocketConfig · JwtChannelInterceptor · NotificationService · NotificationConfig

STOMP at /ws with a simple broker. JWT is validated on the CONNECT frame. Notifications go to /queue/notifications via convertAndSendToUser. Web Push (VAPID) goes through nl.martijndwars:web-push: BouncyCastle is registered, PushService(publicKey, privateKey, subject) is created, and messages are sent with Encoding.AES128GCM. Subscriptions that return 404/410 are deactivated, because the user revoked them.

IR3D (Kontentt)shared/config/WebSocketConfig · StompChannelInterceptor · UserPresenceService · AdminUsersLiveBroadcaster · ExpoPushServiceImpl · WebPushServiceImpl

Chat over STOMP at /ws-chat:

  • The JWT is checked on CONNECT, and revoked sessions are rejected (“Session has been revoked”).
  • SUBSCRIBE is authorised, so you can only subscribe to chats you belong to.
  • Typing indicators, presence, and signed delivery-receipt tokens.
  • A 1-second admin live-users broadcast.

Push goes to Expo for the React Native app and FCM for the web. Noisy STOMP rejection logs are silenced (SubProtocolWebSocketHandler: OFF).

Alternatives

  • Managed real-time services: Pusher, Ably, Firebase Realtime/Firestore, Supabase Realtime.
  • Socket.IO: a Node ecosystem library with fallbacks.
  • WebTransport / HTTP/3: emerging.
  • GraphQL subscriptions: real-time over WS for GraphQL APIs.
  • Connection limits. Each SSE or WS connection holds a socket (and a thread, unless async or virtual threads). Plan for 10k+ connections.
  • Reconnect storms after a deploy. Add jitter to client reconnects.
  • Missed messages. Persist notifications (all your projects have a notifications table) and fetch unread items on reconnect; real-time is just a hint.
  • Auth on the upgrade. Browsers can’t set headers on WebSocket, so use the CONNECT frame, a cookie, or a short-lived ticket in the query string.

Check yourself

1. Notifications only from server to browser, simplest robust choice?
2. Why RM’s 25-second SSE heartbeat?
3. Two app instances with enableSimpleBroker. Problem?