Building Chat & Presence Systems
You'll learn to
- -Explain how presence (online/offline) is tracked at scale
Chat is the canonical WebSockets use case: genuinely bidirectional, genuinely latency-sensitive. But a subtlety shows up the moment you have more than one WebSocket server: Client A might be connected to Server 1 while Client B is connected to Server 2, so Server 1 needs a way to tell Server 2 "forward this message to your client."
A message from Client A must be broadcast through a pub/sub layer to reach Client B, who is connected to a different WebSocket server instance.
Presence: Tracking Online/Offline at Scale
Presence (who's online right now) is usually tracked with a short-TTL key per user in a fast store like Redis, refreshed by a heartbeat from the client's open connection. If the heartbeat stops (connection dropped, tab closed), the TTL simply expires and the user is treated as offline: no explicit "goodbye" message required.
Why use a TTL-based heartbeat for presence instead of just marking a user offline the moment their WebSocket closes?
"A heartbeat is more accurate since it checks continuously."
"A clean disconnect event is not guaranteed: a phone losing signal or an app crashing never sends a 'goodbye,' it just vanishes. A TTL-based heartbeat handles both cases uniformly: a clean disconnect can proactively clear the key, but even if it doesn't, the TTL expires on its own within a few seconds either way. Relying only on an explicit disconnect event would leave crashed clients stuck showing 'online' forever."