How do you implement presence (online/offline) with WebSockets?

Answer

Presence tracking with WebSockets follows this pattern: (1) On connection — when a user's WebSocket connects, the server records them as online (onlineUsers.set(userId, ws)) and broadcasts a "user-online" event to relevant users; (2) On disconnect — when the connection closes (close event), remove from the map and broadcast "user-offline"; (3) Heartbeat for ghost detection — users can disconnect without a clean close (network drop). Implement ping/pong: the server pings every 30s; if no pong within 5s, mark as offline. In multi-server environments, store presence in Redis with TTL: SET user:123:online 1 EX 35 (expires after 35s, refreshed by each pong). This prevents phantom-online users if a server crashes. For group chat, broadcast presence only to users sharing a conversation to avoid broadcasting to all connected users.