skip to content

How would you track which members are online in an ASP.NET Core SignalR app when users hold several connections and some drop without closing?

level: seniorimportance: should knowfreq 42%

answer

  1. count connections per user, not users
  2. increment in OnConnectedAsync, decrement in OnDisconnectedAsync
  3. announce only on 0 to 1 and 1 to 0
  4. silent drops: client timeout, 30 s
  5. crash: no OnDisconnectedAsync

basics

~20 s

Keep a thread-safe map from user id to connection ids, updated in OnConnectedAsync and OnDisconnectedAsync, announcing online on the first connection and offline after the last. Silent drops lag by the client timeout, and crashes leave stale entries.

solid answer

~40 s

SignalR has no presence API and cannot list a group's members, so presence is my own state. A user may hold several connections, so I track connection ids per `Context.UserIdentifier` in a thread-safe singleton (or a shared store when there is more than one server): add in `OnConnectedAsync`, remove in `OnDisconnectedAsync`, and broadcast `MemberOnline` only on the first connection and `MemberOffline` only when the last one is gone. Two realities shape the design. A client that vanishes without closing is noticed only after the server's client timeout, 30 seconds by default, so presence lags; and if the server process dies, `OnDisconnectedAsync` never runs, so entries in an external store need an expiry or a per-server sweep. I also debounce the offline announcement briefly, because a reconnect produces a disconnect followed by a new connect.

code

csharp · 18 lines
csharp
public class SpaceHub(PresenceTracker presence) : Hub
{
    public override async Task OnConnectedAsync()
    {
        var userId = Context.UserIdentifier;
        if (userId is not null && presence.Connected(userId, Context.ConnectionId))
            await Clients.Others.SendAsync("MemberOnline", userId);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        var userId = Context.UserIdentifier;
        if (userId is not null && presence.Disconnected(userId, Context.ConnectionId))
            await Clients.Others.SendAsync("MemberOffline", userId);
        await base.OnDisconnectedAsync(exception);
    }
}

go deeper

for a junior

Know that SignalR has no built-in online list, so you record connects and disconnects yourself in OnConnectedAsync and OnDisconnectedAsync.

for a middle

Explain per-user connection sets, announcing only on first and last connection, and why the tracker must be a thread-safe singleton.

for a senior

Design for the client-timeout lag, reconnect flapping and crashes that skip OnDisconnectedAsync, with expiry and sweeps in a shared store.

for a principal

Decide how accurate presence must be for the product and pay only for that accuracy, from a per-process map to a shared store with heartbeats.

## Why you build it yourself ASP.NET Core SignalR gives you connection events and routing, but no presence feature: there is no API that returns who is connected, and none that lists or counts a group's members. In the co-working space app, the "who's in today" panel therefore needs its own state, fed by the hub's connection events. ## Count connections, not users A member with a laptop, a phone and two tabs has **four connections** and one `Context.UserIdentifier`. Presence must be per user, derived from per-connection events: ```csharp public sealed class PresenceTracker { private readonly Dictionary<string, HashSet<string>> _byUser = new(); private readonly Lock _gate = new(); public bool Connected(string userId, string connectionId) { lock (_gate) { if (!_byUser.TryGetValue(userId, out var set)) _byUser[userId] = set = new HashSet<string>(); set.Add(connectionId); return set.Count == 1; // first connection: came online } } public bool Disconnected(string userId, string connectionId) { lock (_gate) { if (!_byUser.TryGetValue(userId, out var set)) return false; set.Remove(connectionId); if (set.Count > 0) return false; _byUser.Remove(userId); return true; // last connection: went offline } } } ``` Registered as a **singleton** and injected into the hub, it is called from `OnConnectedAsync` and `OnDisconnectedAsync`, and the hub broadcasts only on the transitions. ## The timing problems 1. **Silent drops.** When a laptop lid closes or a phone loses signal, no close message reaches the server. It notices only when it stops hearing from the client, by default after the 30-second client timeout, and then runs `OnDisconnectedAsync` with a non-null exception. Presence lags by up to that long. 2. **Reconnect flapping.** An automatic reconnect is a disconnect followed by a new connection. Without care, colleagues see "offline" then "online" a second later. Delay the offline broadcast by a few seconds and cancel it if the user reconnects. 3. **Crashes.** If the server process dies, `OnDisconnectedAsync` never runs for its connections. In-memory state dies with the process, which is consistent; state in an external store is now wrong. ## Where to keep it | Deployment | Store | Caveat | |---|---|---| | one server | in-memory singleton | lost on restart, which is fine since all connections are lost too | | several servers | a shared store (a database or Redis) | entries need an expiry or a per-server heartbeat and sweep, because a crashed server cleans nothing up | With a shared store, key entries by server instance as well as connection id, so a restarting server can clear its own stale rows. ## Telling others - Broadcast transitions to the people who care, for example `Clients.Group("company-17")`, rather than `Clients.All`. - Send the full list on demand through a hub method such as `GetOnlineMembers()`, so a client that just connected, or reconnected, can rebuild its panel instead of trusting a stream of deltas it may have partly missed. - Anonymous connections have a `null` user identifier; leave them out of presence or track them by connection id under a separate key. ## Checklist - Thread-safe singleton or shared store, never hub fields. - Per-user connection sets, announcing on 0 to 1 and 1 to 0 only. - Debounced offline, tolerant of the client-timeout lag. - Crash cleanup for any store outside the process.

  • Why not use a SignalR group per company and count its members for the online panel?
    Because SignalR exposes no way to list or count a group's members; the docs explain that the information is not available once the app runs on several servers. Groups route messages; presence needs its own state updated in the connection events.
  • On three servers with presence in Redis, one server crashes. What goes wrong, and how do you guard against it?
    Its connections never get `OnDisconnectedAsync`, so their entries stay and those members look online forever. Store entries with the server instance and an expiry, refresh them with a periodic heartbeat from each live server, and let a sweep, or the restarting server, delete entries whose server stopped refreshing.

  • OnDisconnectedAsync runs immediately when a phone loses signal.
  • One disconnect means the member went offline.
  • Context.Items is a good place to keep the online-members list.
  • Counting a SignalR group's members gives the online list.
  • OnDisconnectedAsync still runs for every connection when the server crashes.