Sub topic 11
Presence with heartbeats
Presence tells users whether a contact is online. This chapter assumes you know how WebSocket connections work and how a key-value store with expiring keys behaves. It covers how heartbeats produce presence, the failure modes, and how to limit the cost of presence updates.
Why not use the connection state?
A connection closing looks like a good signal for going offline. It is not reliable. A phone that loses signal, a laptop that sleeps, or a crashed server can leave the connection half-open. The server may not learn about it for minutes, until the TCP timeout fires.
Heartbeats avoid this. The client sends a small message at a fixed interval. The server treats a user as online only if a heartbeat arrived recently.
The heartbeat model
The server stores the time of the last heartbeat for each user. A user is online if that time is within a time-to-live (TTL) window.
import time
HEARTBEAT_TTL = 30
last_seen = {}
def heartbeat(user_id, now=None):
last_seen[user_id] = now if now is not None else time.time()
def is_online(user_id, now=None):
now = now if now is not None else time.time()
ts = last_seen.get(user_id)
return ts is not None and now - ts <= HEARTBEAT_TTL
heartbeat("alice", now=100)
assert is_online("alice", now=120)
assert not is_online("alice", now=140)Alice sent a heartbeat at time 100. At 120 she is 20 seconds old, inside the 30-second window. At 140 she is 40 seconds old, so she counts as offline. No one has to record a "went offline" event. Presence expires on its own.
Choosing the interval and TTL
The TTL must be longer than the heartbeat interval, with room for a missed beat. A common choice is a TTL of about three times the interval.
| Interval | TTL | Effect |
|---|---|---|
| 5 s | 15 s | Fast detection, more load |
| 10 s | 30 s | Balanced default |
| 60 s | 180 s | Low load, slow detection |
A short interval makes status accurate but multiplies traffic. With 10 million connected users and a 10-second interval, the presence store takes about 1 million writes per second.
Production storage
In production, keep last_seen in a store with built-in expiry, such as Redis. Write the key with a TTL on each heartbeat. When the key expires, the user is offline. This also removes the need for a cleanup job.
Fan-out of status changes
Reading presence on demand works for one chat window. A contact list with hundreds of friends needs a different approach.
- Publish only changes, not every heartbeat. Going from offline to online, or the reverse, is an event. A refreshed heartbeat is not.
- Subscribe each client only to the users it is currently showing.
- For large groups, fetch presence on demand and skip push updates. Pushing every change to thousands of members is expensive.
Common errors
- Flapping. A flaky network makes a user alternate between online and offline. Add a short grace period before announcing offline.
- TTL shorter than the interval. Users appear offline between healthy heartbeats.
- Treating presence as exact. It is approximate. Design the UI for "last seen about a minute ago".
- Clock mismatch. Use server time for
last_seen, not client timestamps.
Exercise
A chat service has 2 million connected users. Each client sends a heartbeat every 20 seconds. The TTL is 60 seconds. How many heartbeat writes per second does the presence store handle, and what happens to a user whose app is killed right after a heartbeat?
Show answer
2,000,000 / 20 = 100,000 writes per second. The killed user keeps appearing online until the TTL runs out, so for up to 60 seconds, and then shows as offline.
Exercise
Why should the server avoid broadcasting every heartbeat to a user's contacts?
Show answer
Heartbeats are frequent and mostly change nothing. Broadcasting each one multiplies traffic by the number of contacts. Only transitions between online and offline need to be published.