Track online status cheaply
Broadcasting every status change to every contact is N² traffic.
Say it like this
Presence is a last-seen timestamp with a TTL, refreshed by a batched heartbeat, and I publish changes only to the people who currently have that contact open, so it never becomes an all-to-all broadcast.
Basic solution
Clients heartbeat every ~30 s; store last_seen with a TTL; publish changes only to users who are currently subscribed (chat open).
Heartbeats in, scoped publishes out
Connection servers batch heartbeats into TTL keys. A status change is published only to the watcher set for that user, which holds the people with that chat open.
How it works
- While the app is in the foreground, the client sends a tiny heartbeat frame over its socket every 30 seconds, and once immediately on every connect. The frame carries nothing but the fact that the user is still there.
- The connection server does not write each heartbeat as it arrives. It collects the heartbeats it received in the last second and writes them in one batch: for each user, SET presence:user last_seen EX 60, which stores the timestamp and sets a 60-second expiry.
- A user is online if their presence key exists. Because the key expires on its own 60 seconds after the last heartbeat, going offline needs no cleanup job: silence is what marks a user offline.
- When Alice opens a chat with Bob, her client subscribes to Bob's status. The server adds alice to the set watchers:bob, with a TTL of a few minutes that is refreshed while the chat stays open on her screen. Closing the chat lets the entry expire, which is the unsubscribe.
- When Bob's status flips (his first heartbeat after an absence, or his key expiring, noticed through a Redis keyspace event or a periodic scan of watched users), the presence service reads watchers:bob and publishes one event to those users only. Nobody else is told.
- Typing indicators are sent as plain frames to the current watchers and are never written to any store; they are meaningful for a few seconds and then worthless.
Why subscriptions
- Most users have hundreds of contacts but look at one or two conversations at a time. Publishing a status change only to the people who currently have that user on screen, instead of to every contact, cuts the fan-out by two orders of magnitude.
Worked example
Presence for the chat app
- 10M online users, 300 contacts each on average.
- Naive broadcast: every status change goes to 300 contacts. Users flip online or offline about 20 times a day, so 10M x 20 x 300 = 60B presence frames per day, about 700K per second, and most land on users who are not looking.
- Heartbeats: 10M / 30 s = 333K per second. Batched per connection server (250K users per server, flushed once a second) that is 40 pipelined batches per second into Redis, trivial.
- Storage: one key per online user, about 50 bytes, so 500 MB for 10M users. Watcher sets: assume 2M chats open at any moment with 1.2 watchers each, about 150 MB.
- With subscriptions: a status change goes only to current watchers, about 1.2 on average, so 10M x 20 x 1.2 = 240M frames per day, under 3K per second. That is a 250 times reduction, and the ones delivered are the ones someone sees.
Variants and when each wins
Heartbeat with TTL (pull on open)
- Clients heartbeat, the presence key expires on silence, and when a chat opens the client reads the current status once and subscribes for changes. This is the default; it wins because it is cheap, self-cleaning and only pushes to people who are looking.
Connection-driven presence
- Online means the socket is open and offline means it closed, with no heartbeat keys at all. It wins on cost, but mobile sockets drop constantly, so status flickers unless you add a grace period before publishing offline.
Last-active instead of online
- Store only a timestamp and show "active 5 min ago" rather than a live dot. It wins when the product does not need a true online indicator, because there is no TTL to tune and no flicker to hide.
Full fan-out to contacts
- Publish every status change to every contact. It wins only for small contact lists or a small user base; at scale it is hundreds of billions of frames a day that nobody is looking at.
Recommendation: heartbeat with TTL, subscriptions scoped to open chats, and a grace period of a minute before showing offline.
Failure modes
Flapping status
- A contact flips between online and offline every few seconds. It happens because a phone's radio sleeps between heartbeats and the socket drops, so the key expires and is recreated over and over. Set the TTL to two or three heartbeat intervals, add a grace period before publishing offline, and never tie the displayed status directly to whether the socket is open.
Heartbeats dominate Redis
- Redis runs at 300K operations per second and nearly all of them are presence writes. It happens because each heartbeat from each user becomes its own write. Batch the writes per connection server, lengthen the interval when the app is in the background, and skip the write when the previous one was less than half an interval ago.
Watchers that never expire
- The watcher sets grow to hundreds of millions of entries. It happens because clients close a chat without sending an unsubscribe, so entries added on open are never removed. Put a TTL on every watcher entry and refresh it only while the chat is visible; expiry then does the unsubscribe for you.
Stored typing indicators
- "Bob is typing" stays on screen for minutes after Bob has left. It happens because the typing event was written to a store and nothing ever cleared it. Treat typing as a transient frame with a client-side timeout of a few seconds, and never write it to storage.
Privacy leak through presence
- Users work out when a contact is awake or at work from the online dot. It happens because presence is visible to everyone in the contact list by default. Check each user's visibility settings at the moment a watcher subscribes, not at publish time, so a hidden user is never added to anyone's watcher set.
Interviewer follow-ups
Answer out loud before you open each one.
How do you detect that a user went offline without polling every key?
Let the TTL expire and do not publish anything; the next time a watcher opens the chat they read the current state. For watchers already subscribed, either Redis keyspace notifications on expiry or a short periodic scan of the watched users, which is a small set. Offline is allowed to be a minute late.
Why not publish presence changes to all contacts?
Because the fan-out is contacts times status changes, hundreds of billions of frames a day at scale, and almost all of them land on screens that are not showing that contact. Scoping to people who currently have the conversation open shrinks the fan-out to the handful who can see it.
What happens to presence when a connection server crashes?
Its users stop heartbeating and their keys expire within a minute, so they show as offline until they reconnect elsewhere and heartbeat again. Nothing needs cleaning up, which is the point of using a TTL instead of explicit offline writes.
How is typing different from presence?
Typing is transient and only meaningful for a few seconds, so it is a frame sent to the current watchers with a client-side timeout and no storage. Presence is state that must survive the client, so it is stored with a TTL. Mixing them is the common mistake.
Connections
- In study paths
- Real-time delivery
- Built on
- Skip list · Ring buffer
- Pairs with
- Find which server holds a user · Push to the browser in real time · Expire data automatically · Batch small operations · Fan one event out to many consumers
- Pulls against
- Precompute on write, read cheaply
- Used in
- Chat App (WhatsApp / Messenger)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 | Connection server | Compute Engine | Azure Virtual Machines | DigitalOcean Droplets, any VM or bare metal |
| Amazon ElastiCache | Presence keys, Watchers set | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon EC2 Auto Scaling | Presence service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |