Video in progress

How do you track who is online on the site using WebSocket connections?

Spring STOMP publishes connection lifecycle events: SessionConnectedEvent, SessionSubscribeEvent, SessionDisconnectEvent. You listen to them with @EventListener and maintain a map of user to session count; with several instances, this state is kept in a shared place such as Redis.

📖 Answer

@Component
public class PresenceTracker {
    private final Map<String, Set<String>> sessionsByUser = new ConcurrentHashMap<>();
    private final SimpMessagingTemplate messaging;

    public PresenceTracker(SimpMessagingTemplate messaging) { this.messaging = messaging; }

    @EventListener
    public void onConnect(SessionConnectedEvent e) {
        Principal user = e.getUser();
        if (user == null) return;
        String sid = StompHeaderAccessor.wrap(e.getMessage()).getSessionId();
        sessionsByUser.computeIfAbsent(user.getName(), k -> ConcurrentHashMap.newKeySet()).add(sid);
        messaging.convertAndSend("/topic/presence", Map.of("user", user.getName(), "online", true));
    }

    @EventListener
    public void onDisconnect(SessionDisconnectEvent e) {
        if (e.getUser() == null) return;
        String name = e.getUser().getName();
        sessionsByUser.computeIfPresent(name, (k, set) -> {
            set.remove(e.getSessionId());
            return set.isEmpty() ? null : set;
        });
        if (!sessionsByUser.containsKey(name)) {
            messaging.convertAndSend("/topic/presence", Map.of("user", name, "online", false));
        }
    }
}

Counting per session matters: if a person has two tabs open, closing one must not make them "offline".

Things worth knowing:

  • SessionDisconnectEvent can arrive more than once for a single session, so make your code idempotent.
  • If the server itself dies abruptly, no disconnect events arrive at all. If you store this in Redis, put a TTL on the keys and refresh it with the heartbeat, or you'll get "online forever" users.
  • A user on a mobile network drops for 2 seconds and reconnects. Delaying the "offline" message by a few seconds removes flicker in the UI.