CSE Roadmap

Core tier · about 5 hours · 8 parts

Part 6 of 8 · 2 min read

Presence

Heartbeats and fanout.

An online presence indicator shows whether a user is active, often as a green dot.

Login. After the WebSocket is open, the presence server stores "online" and a last-active time in the key-value store.

Logout. The status is set to offline.

Disconnection. Networks drop often, for example in a tunnel. If every drop flipped the status, the dot would flicker. The book's answer is a heartbeat: the client sends a small signal at a fixed interval. If the server hears nothing for a set time, the user counts as offline. In the book's example the client sends one every 5 seconds, and a gap of 30 seconds means offline (numbers chosen only to show the idea).

A worked example (made up). With 5 million online users and a heartbeat every 5 seconds, the presence servers receive 5,000,000 / 5 = 1,000,000 heartbeats per second. That is a large number, so presence must be cheap to handle. Keep the last heartbeat time in memory, and write to disk only when the status changes.

Telling friends. The book uses publish and subscribe (Level 6). Each pair of friends has a channel. When A's status changes, the presence server publishes to A's channels, and each friend, subscribed, gets the update through their WebSocket. A user with 100 friends causes 100 events per change.

This works for small friend groups. For a group of 100,000 members, one change would cause 100,000 events. The book's suggestion: fetch status only when a user opens the group or refreshes the list.

Heartbeat

A heartbeat is a small signal sent at regular intervals to show that a client or server is still alive.

Example: a phone sends "still here" every 5 seconds, and the server marks it offline after 30 seconds of silence.

Check yourself: 1. Why not mark offline on the first dropped connection? 2. How many heartbeats per second for 2 million users at 10-second gaps? 3. Why does presence fanout fail for huge groups?