Sub topic 11
Presence with heartbeats
Presence shows whether a user is online. This chapter covers how a chat system works out presence from periodic signals called heartbeats. It assumes you know how WebSocket connections work, have used a key-value store such as Redis, and can read short Python and JavaScript. It builds on the earlier chapters on connection protocols and the high-level architecture.
What presence is and why it is hard
Presence is the green dot next to a contact's name. It looks like a simple boolean, but it has to be computed from unreliable evidence:
- A phone can lose signal without closing its TCP connection cleanly. The server sees nothing.
- A user can close the app, switch networks, or put the phone in a tunnel for ten seconds and come back.
- Millions of users can change state at the same moment, for example after a data center blip.
Presence is also allowed to be approximate. A dot that is wrong for a few seconds harms nobody. A lost message does. So presence should never share a failure path with message delivery. It should be cheap, lossy, and self-correcting.
The heartbeat and TTL model
A heartbeat is a small message the client sends at a fixed interval while the app is active. The server records when it last heard from each user. A time-to-live (TTL) is how long that record stays trustworthy. A user is online if the last heartbeat is newer than the TTL.
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)The state is derived from the timestamp, not stored as a flag. Nobody has to "set offline". If heartbeats stop, the user ages out on their own. That is why this design survives crashes, dead connections, and killed apps.
Why not just use connection open and close events?
The chat server knows when a WebSocket opens and closes, so it is tempting to mark the user online on open and offline on close. This fails in three ways:
- A half-open connection (the client vanished without a TCP FIN or RST) can look alive for minutes until TCP keepalive notices.
- If the chat server itself crashes, no close events are ever emitted, and its users stay "online" forever.
- Flaky mobile networks reconnect constantly, so the status flips between online and offline.
Heartbeats fix the first two because absence of a signal is the signal. The third is handled by the TTL, which tolerates a gap.
Choosing the interval and TTL
The TTL must be longer than the heartbeat interval, or a single late packet marks the user offline. A common rule is a TTL of at least two to three intervals.
| Interval | TTL | Detection delay after a silent drop | Heartbeat load at 10M connections |
|---|---|---|---|
| 5 s | 15 s | up to 15 s | 2M requests/s |
| 10 s | 30 s | up to 30 s | 1M requests/s |
| 30 s | 90 s | up to 90 s | about 333K requests/s |
The load column explains why you cannot pick a very short interval. At 10 million concurrent connections, a 10-second interval means about one million writes per second to the presence store. Heartbeats are small, but they are the largest request stream in the whole system. Choose the longest TTL your product can tolerate.
Two optimizations reduce the load:
- Piggyback. Any message the client already sends (a chat message, an ack) counts as a heartbeat. Only send an explicit one after a quiet interval.
- Heartbeat to the connection server, not the store. The chat server holds the connection anyway. It can batch updates and write to the presence store once per interval per user, or only when state changes.
Client and server flow
The client sends a heartbeat on the existing WebSocket. The chat server refreshes the user's presence record. If the user was previously offline, the server also announces the change to interested users.
Storing presence in a shared store
With many chat servers, presence must live outside any one server's memory. A key-value store with built-in expiry fits well. The sketch below uses a Redis sorted set per user, with one entry per device, scored by last heartbeat time. It takes the time from the Redis server, so clock differences between chat servers do not matter.
import redis
HEARTBEAT_TTL = 30
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def redis_now():
seconds, micros = r.time()
return seconds + micros / 1_000_000
def heartbeat(user_id, device_id):
key = f"presence:{user_id}"
now = redis_now()
pipe = r.pipeline()
pipe.zadd(key, {device_id: now})
pipe.zremrangebyscore(key, "-inf", now - HEARTBEAT_TTL)
pipe.expire(key, HEARTBEAT_TTL)
pipe.execute()
def is_online(user_id):
key = f"presence:{user_id}"
return r.zcount(key, redis_now() - HEARTBEAT_TTL, "+inf") > 0Three details matter here:
- A user is online if any device has a fresh score. Closing the laptop does not mark the user offline while the phone is still sending heartbeats.
zremrangebyscoreprunes stale devices, andexpireremoves the whole key when all devices go quiet. The store cleans itself.- Reads compare scores against the current time, so a missed expiry never produces a wrong answer. The expiry only reclaims memory.
Telling other users about changes
Reading presence on demand is easy. Pushing changes to friends is the expensive part.
Publish on change, not on every heartbeat
Only a transition (offline to online, or online to offline) is worth announcing. A heartbeat that refreshes an already-online user produces no event. The server detects a transition by checking whether the user was online before the write.
Fan out only to people who are looking
A user with 500 contacts does not need 500 notifications each time they flicker. Common approaches:
- Subscribe to presence only for contacts visible on screen, such as the open chat or the first page of the contact list. Unsubscribe when they scroll away.
- Use a publish/subscribe channel per user. Interested chat servers subscribe to
presence:aliceon behalf of their connected clients. - Skip presence updates for large groups. Showing "1,203 online" in a 50,000-member group is usually computed lazily or approximated, not pushed per member.
Damp the flapping
A phone that bounces between wifi and cellular can go offline and online several times a minute. Add a short grace period, for example delaying the offline announcement by a few seconds and canceling it if a heartbeat arrives. This costs a few seconds of accuracy and saves a lot of notifications.
Edge cases and failure modes
- Last seen. When a user goes offline, keep the last heartbeat time in durable storage so clients can show "last seen 3:42 PM". This is a separate, low-write record and can be updated only on the offline transition.
- Mobile background. Operating systems suspend background apps, so heartbeats stop even though the user may be reachable. Treat this as offline for presence and deliver messages through push notifications, covered in the next chapter.
- Presence store outage. Fail open. If presence cannot be read, show no dot rather than blocking message sending. Messaging must never depend on presence.
- Reconnect storms. After a chat server restarts, all of its clients reconnect at once and send heartbeats together. Add random jitter to client reconnect and heartbeat timing so the load is spread out.
- Clock skew. Compare timestamps from a single clock, such as the store's, not from clients. A client with a wrong clock would otherwise appear permanently online or offline.
- Privacy. Presence leaks behavior. Let users hide their status and enforce it on the server by checking the viewer's permission before returning or publishing presence.
Client side heartbeat
A minimal browser client that sends a heartbeat only while the page is visible:
const ws = new WebSocket("wss://chat.example.com/ws");
const HEARTBEAT_INTERVAL_MS = 10000;
setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) return;
if (document.visibilityState !== "visible") return;
ws.send(JSON.stringify({ type: "heartbeat" }));
}, HEARTBEAT_INTERVAL_MS);Skipping heartbeats on a hidden tab is a product choice. It makes users appear offline when they have switched tabs, but it saves load and matches what many users expect.
Exercise
A chat service has 20 million concurrent connections. It uses a 15-second heartbeat interval and a 45-second TTL. (a) How many heartbeats per second reach the system? (b) A user's phone loses signal without closing the connection. What is the longest time other users could still see that user as online? (c) Name one change that would reduce the heartbeat load without lengthening the TTL.
Show answer
(a) 20,000,000 / 15 is about 1.33 million heartbeats per second. (b) Up to 45 seconds after the last heartbeat that was received, because the record only becomes stale when the TTL runs out. (c) Treat normal client traffic such as chat messages and acks as heartbeats, so explicit heartbeats are only sent after a quiet interval. Batching writes per chat server also reduces the load on the presence store.