wasAsked.

How would you implement real-time notifications with WebSockets while handling reconnects and authorization?

Swiggy · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Boot, React

Community answers

Posted by wasAsked editorial collection

Real-time notifications need a persistent connection, authentication on connect, authorization per destination, and recovery after disconnects. Spring Boot server - Spring WebSocket with STOMP for topics and per-user queues: @Configuration @EnableWebSocketMessageBroker class WsConfig implements WebSocketMessageBrokerConfigurer { public void registerStompEndpoints(StompEndpointRegistry r) { r.addEndpoint("/ws").setAllowedOrigins("https://app.example.com"); } public void configureMessageBroker(MessageBrokerRegistry r) { r.enableSimpleBroker("/topic", "/queue"); r.setUserDestinationPrefix("/user"); } } - Send to one user: messagingTemplate.convertAndSendToUser(userId, "/queue/notifications", dto) — delivered to every session of that user. - Scaling to several instances: use a broker relay (RabbitMQ or ActiveMQ STOMP) or Redis pub/sub so a message produced on one instance reaches users connected to another. Authentication - Browsers cannot set custom headers on the WebSocket handshake. Options: - Cookie-based session authentication on the handshake (same site), with CSRF considerations. - Send the JWT in the STOMP CONNECT frame headers and validate it in a ChannelInterceptor (preSend on CONNECT), setting the user Principal. - Restrict allowed origins to prevent cross-site WebSocket hijacking. Authorization - Spring Security messaging rules: allow subscriptions to /user/queue/** for authenticated users, and check permissions for topic subscriptions (for example only members of an order or tenant may subscribe to /topic/orders.{id}). Deny everything else by default. - Validate any client-sent messages like normal API input. Reconnects (React client with @stomp/stompjs) - Configure reconnectDelay with backoff and heartbeats (heartbeatIncoming and heartbeatOutgoing) to detect dead connections through proxies and load balancers. - Messages sent while disconnected are lost with a simple broker, so persist notifications in the database with IDs and read status. On (re)connect, fetch missed notifications via REST (GET /api/notifications?after=<lastId>) and then continue live. - Refresh tokens before reconnecting; close sessions when tokens expire or users log out. - Show connection state in the UI ("Reconnecting..."). Infrastructure - Load balancers and ingress must support WebSocket upgrades and long idle timeouts. - Consider Server-Sent Events as a simpler alternative for one-way notifications (standard HTTP, automatic browser reconnection with Last-Event-ID). Keep payloads small (type, ID, summary); the client fetches details through the regular API with normal authorization.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics