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

AspectDetail
BehaviorServer holds request until update or timeout
Timeout30-60s typical
ResumeClient immediately reconnects
UseFallback when WS/SSE unavailable

4. Implementing Message Broadcasting

PatternDetail
Topic / channelSubscribers receive all messages
User-specificPer-session destination
BrokerRedis pub/sub for multi-node
OrderedSingle producer per topic

5. Handling Connection Lifecycle

EventAction
ConnectAuthenticate, register subscriptions
DisconnectCleanup subscriptions
HeartbeatDetect dead connections
ReconnectResume from last seen ID

6. Implementing Authentication for WebSockets

ApproachDetail
Token in CONNECTSTOMP CONNECT frame header
Cookie + Origin checkSame-origin browser auth
Query paramAvoid: visible in logs
Re-auth on reconnectToken may have rotated

7. Implementing Presence Tracking

TechniqueDetail
HeartbeatRefresh TTL key in Redis
Connect/disconnect eventsUpdate presence registry
Multi-deviceTrack per-session, aggregate per user
Pub/subBroadcast presence changes

8. Implementing Real-Time Notifications

PipelineDetail
Event sourceDomain event or message
Fan-outTo recipients' channels
PersistenceStore for offline users
DeliveryWS/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

ConcernDetail
BackoffExponential with jitter
Resume cursorLast event ID / sequence
ReplayServer sends missed messages
Limit attemptsShow offline indicator after N tries

11. Implementing Message Queuing for Offline Users

StorageDetail
Per-user inboxPersistent queue / DB rows
TTLDrop after N days
On connectDrain inbox to client
Push fallbackSend mobile push if offline long

12. Implementing Real-Time Event Filtering

LayerDetail
Server-sideSubscribe only to permitted topics
Per-user filterApply preferences before send
Authz checkRe-verify on each event for sensitive data
Client-sideUI-level filtering only (never security)