Video in progress

How do you design "user is online" (presence) in a system that runs in several regions?

Presence is a fast-changing, approximate state: each region tracks its own connections locally and sends condensed, delayed updates to the other regions. Don't aim for strong consistency; rely on TTL and heart-beat.

📖 Answer

The first decision is how accurate presence has to be. "Your friend went offline 3 seconds ago" or "online now": an error of a few seconds isn't noticeable to the user. With that you can give up synchronous cross-region writes.

Within a region: for each connection the gateway writes presence:{userId} to Redis with a TTL of 60 s, and the heart-beat refreshes it every 20 s. If a user has several devices, use a set or hash: {connId -> lastSeen}. The user is online if at least one entry is alive.

Why TTL? If a gateway dies unexpectedly, the "disconnect" event never arrives. Without a TTL, users stay online forever. That's the most common presence bug.

Across regions: each region replicates state changes (online-to-offline transitions, not every heart-beat) as events to the other regions, using Kafka MirrorMaker or similar. Each region keeps the "global view" locally and answers local queries from it. On a conflict, "latest timestamp wins", accounting for clock skew.

What you have to think about for load is fan-out. A user has 500 friends and each of them must be pushed their status change. On a mobile network, dropping and reconnecting can happen several times a second. So:

  • I delay the switch to offline by 10 to 30 s (debounce), so a short drop isn't noticed;
  • push only to contacts visible on screen, and the rest on request;
  • in large groups presence isn't pushed at all, only an "N people online" count.

Be careful about using presence for a business decision (for example "don't send SMS if online"). Approximate state means an approximate decision. For important delivery, rely on acks, not on presence.