Video in progress

The number of open WebSocket sessions on the server is far higher than the number of users and keeps growing. What could be going on?

Probably half-open connections: the client vanished from the network (a phone entered a tunnel, Wi-Fi changed), but no FIN arrived over TCP, and the server doesn't know because it isn't writing. Or the code doesn't remove sessions from the registry when they close. The fix is a server-side heartbeat/idle timeout and checking the cleanup in afterConnectionClosed.

📖 Answer

First I work out which of the two it is.

A leak at the code level. Is it your own Map<userId, Session> that's growing, or the open sockets in the container? I compare the number of WebSocketSession objects in a heap dump with the result of ss -tn state established '( sport = :8080 )' | wc -l. If the map is big and the sockets are few, the removal in afterConnectionClosed or SessionDisconnectEvent is missing, or it doesn't run because of an exception.

Half-open connections. If the sockets are many too, the kernel also considers them alive. TCP itself detects such a connection only when it tries to write and gets no reply (when retransmission gives up, which takes 15+ minutes) or through TCP keepalive; on Linux the default keepalive starts after 2 hours.

The fix is an active check at the application level:

  • STOMP heartbeat: if the server receives nothing from the client within, say, 20s, it closes the session;
  • with raw WebSocket, the server sends a ping every 30s and records the time of the last pong; if 2 to 3 pongs are missing, close;
  • trying to write from the server also helps: if the written data doesn't get through, sendTimeLimit closes the session.
@Scheduled(fixedDelay = 30_000)
void reapIdle() {
    long now = System.currentTimeMillis();
    sessions.values().removeIf(s -> {
        boolean dead = now - s.lastSeen() > 90_000;
        if (dead) closeQuietly(s);
        return dead;
    });
}

Keep an eye on this metric: if the gap between "open sessions" and "sessions active in the last 5 minutes" is large, the cleanup isn't working.