Presence & Online Status — Realtime

Presence shows who is online and when they were last seen. Online means having at least one connection. So count connections per person (a Map from user to a…

Mrs. Rini closes one of her two tabs, and Eko's screen right away says that she is offline. Yet she is still sitting in front of the board. The feature that gets it wrong here is called presence: the feature that shows who is connected right now (the green "online" dot) and when someone was last seen.

It looks easy, but presence is like the sign-in book at a security post: people who come in are written down, people who leave are crossed out. The trouble is that one person can come in through two doors at the same time, and some people leave without saying goodbye. The guard only learns that someone has gone when he calls them and gets no answer. In the app, the sign-in book is the server's record of connections. The two doors are two tabs, leaving without a goodbye is a device that dies suddenly, and calling someone is a ping from the server. At Mrs. Rini's Laundry, the staff screens show whether Mrs. Rini and Eko are online, and since when they have been offline.

Online means having a connection

The server counts connections per person on the namespace /staff, which is called staff in the code. socket.data.user has already been filled in by middleware from a token:

const connections = new Map() // user -> Set of socket.id

staff.on('connection', (socket) => {
  const user = socket.data.user // 'rini' or 'eko'
  if (!connections.has(user)) connections.set(user, new Set())
  connections.get(user).add(socket.id)
  if (connections.get(user).size === 1) staff.emit('presence:online', { user }) // first connection only

  socket.on('disconnect', () => {
    connections.get(user).delete(socket.id)
    if (connections.get(user).size > 0) return // another tab is still open
    connections.delete(user)
    staff.emit('presence:offline', { user, lastSeen: new Date().toISOString() })
  })
})

One person, many connections

What happens Mrs. Rini's connections News for the other staff
opens the board in tab 1 1 presence:online
opens the chat in tab 2 2 (none)
opens the board on her phone 3 (none)
closes tab 2 2 (none)
closes tab 1, locks the phone 0 presence:offline

If the server sent offline on every disconnect, closing just one tab would make Mrs. Rini look offline while she is still in front of the board.

Heartbeats: noticing who left without saying goodbye

When a tab is closed, the browser closes its connection, and the server gets disconnect right away with the reason transport close (tried). But a tablet that dies suddenly, goes into a lift or loses its Wi-Fi has no time to close its connection. The server only learns about it through a heartbeat: the Socket.IO server sends a ping every pingInterval (25,000 ms by default), then waits pingTimeout (20,000 ms by default) for the pong.

With those two numbers, guess: Eko's tablet has an empty battery and switches off suddenly. How long until the server knows that the tablet is no longer connected?

The server knows 20 to 45 seconds later, depending on when the tablet dies: 20 seconds if it dies right before a ping, 25 + 20 = 45 seconds if it dies right after a pong. Tried with socket.io 4.8.4 and the default settings: a client went silent 1 second after its last pong. The server disconnected it with the reason ping timeout 44 seconds later, exactly 45 seconds after that last pong. The client also disconnects by itself after 45 seconds without a ping from the server.

A signal that drops and returns: a grace period

Eko's tablet moves from Wi-Fi to mobile data. Its old connection is closed, the server gets disconnect, and the Socket.IO client reconnects about 1 second later. Without a pause, the other staff see Eko go offline, then come back online a second later. On a weak signal, his dot keeps blinking. The fix is a grace period: when the last connection drops, wait 10 seconds before announcing offline. In this code, pending keeps each user's timer for the offline news. The two functions below replace the two staff.emit calls in the connection counter code:

const pending = new Map() // user -> timer for the offline news

function firstConnection(user) {
  if (pending.has(user)) {
    clearTimeout(pending.get(user)) // back within the grace period: say nothing
    pending.delete(user)
  } else {
    staff.emit('presence:online', { user })
  }
}

function lastConnectionDropped(user) {
  const lastSeen = new Date().toISOString()
  pending.set(user, setTimeout(() => {
    pending.delete(user)
    staff.emit('presence:offline', { user, lastSeen })
  }, 10000))
}

Sometimes the server has not yet noticed that the old connection is gone (the ping timeout has not passed) when the new one arrives. His connection count then goes up to 2, then back down to 1, and the status never changes at all. The connection counter already handles that order.

Why 10 seconds? The Socket.IO client tries again after 1 second, then 2, then 4. Each wait is randomised by ±50%, and no wait is longer than 5 seconds. So the first three attempts are over within 1.5 + 3 + 5 = 9.5 seconds at the latest, and 10 seconds covers all three, even when the random waits are as long as possible. A longer grace period keeps someone who really left online for too long. Even with 10 seconds, a dead tablet may only look offline 45 + 10 = 55 seconds later.

"Last seen"

⚠️ Why is the green dot lying?

TL;DR: Presence shows who is online and when they were last seen. Online means having at least one connection. So count connections per person (a Map from user to a Set of socket.id, or the room user:rini), by listening for the disconnect event. Send presence:online on the first connection and presence:offline when the last one drops. A closed tab is noticed right away (transport close). A device that dies is only caught by Socket.IO's heartbeat: a ping every 25 seconds, 20 seconds to wait for the pong, so the server knows 20 to 45 seconds later. Use a 10-second grace period (wait before announcing offline) so the status does not blink. 10 seconds is enough for the first three reconnect attempts, 9.5 seconds at the latest. Save "last seen" when the last connection drops.

⚡ Offline when the last connection drops

Write:

socket.on('disconnect', () => {
  connections.get(user).delete(socket.id)
  if (connections.get(user).size > 0) return // another tab is still open
  connections.delete(user)
  staff.emit('presence:offline', { user, lastSeen: new Date().toISOString() })
})

Meaning: connections is a Map on the server: each user has a Set with the ids of all their connections (one tab, one connection). The server learns someone went offline from the disconnect event. One person can have many tabs, so presence:offline is sent to the staff (staff, the namespace /staff) only when the last connection drops.

⚡ A device dies: the heartbeat finds it

Guess first: the Socket.IO server sends a ping every 25 seconds, then waits 20 seconds for the pong. Eko's tablet has an empty battery and switches off suddenly. How long until the server knows that the tablet is no longer connected?

20 to 45 seconds, depending on when the tablet dies: 20 seconds if it dies right before a ping, 25 + 20 = 45 seconds if it dies right after a pong. Then the server disconnects it with the reason ping timeout.

Meaning: A device that dies suddenly is only caught by the heartbeat (a ping that must be answered with a pong). A closed tab is noticed right away (transport close), because the browser has time to close its connection.

⚡ A 10-second grace period

Meaning: When someone's last connection drops, the server waits 10 seconds before announcing offline. This pause is called a grace period. If the tablet switches networks and reconnects within those 10 seconds, its online dot does not blink. 10 seconds covers the first three reconnect attempts of the Socket.IO client (9.5 seconds at the latest).

What you will learn