Video in progress

How do you build the "online" / "last seen" status for users in a chat app?

The client sends a heartbeat on connect and every N seconds, and the server stores the user's status in Redis with a TTL. When the TTL expires, they're offline. You should push status changes not to all contacts but only to those who have the screen open right now.

📖 Answer

The simplest wrong approach is to set online = false in the DB when the WebSocket disconnects. The phone enters a tunnel, the connection "hangs", the disconnect event never arrives — and the user looks "online" for hours.

Heartbeat + TTL is more reliable:

// when a "ping" arrives from the client, every 30 seconds
public void heartbeat(long userId) {
    redis.opsForValue().set("presence:" + userId,
            String.valueOf(Instant.now().getEpochSecond()),
            Duration.ofSeconds(70));       // if two heartbeats are missed — offline
}

Key exists — online. Key missing — offline, and the "last seen" time is stored separately in a long-term place (the DB or a key without a TTL).

The hard part is distribution. A user has 500 contacts, and if you push every online/offline change to all of them, across millions of users that blows up the number of messages. In practice:

  • status is requested or subscribed to only when the chat list or the conversation is open;
  • rapid changes (online-offline within 5 seconds) are smoothed out;
  • in big groups you show a count like "45 people online" instead of individual status.

Privacy is part of the design too: the setting to hide "last seen" has to be checked on the server, not on the client.