Implementing Real-Time Features
1. Implementing WebSocket Connections
Example: Spring @MessageMapping
@Configuration @EnableWebSocketMessageBroker
public class WsConfig implements WebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(StompEndpointRegistry r) {
r.addEndpoint("/ws").setAllowedOriginPatterns("https://app.acme.com");
}
public void configureMessageBroker(MessageBrokerRegistry b) {
b.enableSimpleBroker("/topic","/queue");
b.setApplicationDestinationPrefixes("/app");
}
}
@Controller class ChatController {
@MessageMapping("/chat") @SendTo("/topic/chat")
public ChatMessage onMessage(ChatMessage msg) { return msg; }
}
2. Implementing Server-Sent Events
Example: SSE endpoint
@GetMapping(value = "/orders/{id}/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter stream(@PathVariable UUID id) {
var emitter = new SseEmitter(0L);
eventBus.subscribe(id, event -> {
try { emitter.send(SseEmitter.event().name("update").data(event)); }
catch (IOException ex) { emitter.completeWithError(ex); }
});
return emitter;
}
3. Implementing Long Polling
| Aspect | Detail |
|---|---|
| Behavior | Server holds request until update or timeout |
| Timeout | 30-60s typical |
| Resume | Client immediately reconnects |
| Use | Fallback when WS/SSE unavailable |
4. Implementing Message Broadcasting
| Pattern | Detail |
|---|---|
| Topic / channel | Subscribers receive all messages |
| User-specific | Per-session destination |
| Broker | Redis pub/sub for multi-node |
| Ordered | Single producer per topic |
5. Handling Connection Lifecycle
| Event | Action |
|---|---|
| Connect | Authenticate, register subscriptions |
| Disconnect | Cleanup subscriptions |
| Heartbeat | Detect dead connections |
| Reconnect | Resume from last seen ID |
6. Implementing Authentication for WebSockets
| Approach | Detail |
|---|---|
| Token in CONNECT | STOMP CONNECT frame header |
| Cookie + Origin check | Same-origin browser auth |
| Query param | Avoid: visible in logs |
| Re-auth on reconnect | Token may have rotated |
7. Implementing Presence Tracking
| Technique | Detail |
|---|---|
| Heartbeat | Refresh TTL key in Redis |
| Connect/disconnect events | Update presence registry |
| Multi-device | Track per-session, aggregate per user |
| Pub/sub | Broadcast presence changes |
8. Implementing Real-Time Notifications
| Pipeline | Detail |
|---|---|
| Event source | Domain event or message |
| Fan-out | To recipients' channels |
| Persistence | Store for offline users |
| Delivery | WS/SSE if online, push if offline |
9. Implementing Pub/Sub Pattern
Example: Redis pub/sub
// Publisher
redis.opsForValue().getOperations()
.convertAndSend("chat:room:42", message);
// Subscriber
@Bean RedisMessageListenerContainer container(RedisConnectionFactory cf) {
var c = new RedisMessageListenerContainer();
c.setConnectionFactory(cf);
c.addMessageListener((msg, pattern) -> broker.convertAndSend("/topic/chat/42", msg.getBody()),
new PatternTopic("chat:room:*"));
return c;
}
10. Handling Reconnection Logic
| Concern | Detail |
|---|---|
| Backoff | Exponential with jitter |
| Resume cursor | Last event ID / sequence |
| Replay | Server sends missed messages |
| Limit attempts | Show offline indicator after N tries |
11. Implementing Message Queuing for Offline Users
| Storage | Detail |
|---|---|
| Per-user inbox | Persistent queue / DB rows |
| TTL | Drop after N days |
| On connect | Drain inbox to client |
| Push fallback | Send mobile push if offline long |
12. Implementing Real-Time Event Filtering
| Layer | Detail |
|---|---|
| Server-side | Subscribe only to permitted topics |
| Per-user filter | Apply preferences before send |
| Authz check | Re-verify on each event for sensitive data |
| Client-side | UI-level filtering only (never security) |