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.
Previous
What is Redis Pub/Sub and how does it help with WebSocket scaling?
Next
What is the WebSocket subprotocol?
More WebSockets & Real-time Questions
View all →- Intermediate How do you implement a WebSocket server in Node.js using the `ws` library?
- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate How do you handle WebSocket reconnection logic?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do you authenticate WebSocket connections?