LESSON 4 OF 14

Connection Lifecycle and Tracking Connected Users

Learn to manage connection IDs, online users, last-seen information, and client connection status with OnConnectedAsync and OnDisconnectedAsync.

45 dk 53

Introduction

In the previous lesson, we created shared message models and established type-safe communication. This lesson focuses on the lifecycle of a SignalR connection. You will learn what happens when a client connects to a hub, how to react when a connection ends, how to maintain online-user information, and why reconnecting clients receive a new connection ID.

SignalR tracks connections rather than users. The same person can connect from a desktop browser, a mobile device, or several browser tabs. Therefore, online presence must distinguish a stable user identifier from an individual connection identifier. If these concepts are mixed together, closing one tab may incorrectly mark the user offline or remove the record for another active connection.

1. Understanding the connection lifecycle

When a client establishes a hub connection, SignalR invokes the hub's OnConnectedAsync method. This is a suitable place to create a connection record, add the connection to a group, or notify other clients that a user is online. When the connection ends, SignalR invokes OnDisconnectedAsync. Its exception parameter helps distinguish a controlled disconnect from an unexpected network or transport failure.

Context.ConnectionId identifies one SignalR connection. Context.UserIdentifier identifies the associated user according to the authentication configuration. Because one user can have multiple connections, online presence should not be modeled with a single connection ID.

Recommended state model

FieldDescription
UserIdThe user's stable identifier
ConnectionIdThe identifier of one SignalR connection
ConnectedAtWhen the connection was established
LastSeenAtThe user's last known activity or disconnect time

The basic online-presence rule is simple: a user is online while at least one of the user's connections is active. When all connections have ended, the user becomes offline and the last-seen timestamp can be updated.

2. Creating a connection registry

Hub instances should not be treated as the permanent storage location for connection state. A separate service makes the responsibility explicit and allows all hub instances in the process to share the same registry. An in-memory ConcurrentDictionary is practical for a single-server exercise. A production deployment with multiple servers requires shared storage such as Redis or another distributed data store.

using System.Collections.Concurrent;

public sealed record ConnectionRecord(
    string UserId,
    string ConnectionId,
    DateTimeOffset ConnectedAt);

public sealed class ConnectionRegistry
{
    private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, ConnectionRecord>> _connections = new();
    private readonly ConcurrentDictionary<string, DateTimeOffset> _lastSeen = new();

    public bool Add(string userId, string connectionId)
    {
        var userConnections = _connections.GetOrAdd(
            userId,
            _ => new ConcurrentDictionary<string, ConnectionRecord>());

        return userConnections.TryAdd(
            connectionId,
            new ConnectionRecord(userId, connectionId, DateTimeOffset.UtcNow));
    }

    public bool Remove(string userId, string connectionId)
    {
        if (!_connections.TryGetValue(userId, out var userConnections))
            return false;

        var removed = userConnections.TryRemove(connectionId, out _);

        if (removed)
        {
            _lastSeen[userId] = DateTimeOffset.UtcNow;

            if (userConnections.IsEmpty)
                _connections.TryRemove(userId, out _);
        }

        return removed;
    }

    public bool IsOnline(string userId) =>
        _connections.TryGetValue(userId, out var items) && !items.IsEmpty;

    public IReadOnlyCollection<string> GetConnectionIds(string userId) =>
        _connections.TryGetValue(userId, out var items)
            ? items.Keys.ToArray()
            : Array.Empty<string>();

    public DateTimeOffset? GetLastSeen(string userId) =>
        _lastSeen.TryGetValue(userId, out var value) ? value : null;
}

Register the service as a singleton so all hub instances use the same in-process registry.

builder.Services.AddSingleton<ConnectionRegistry>();

Using DateTimeOffset.UtcNow is important. Relying on local server time can produce inconsistent last-seen values when servers or clients use different time zones.

3. Implementing hub lifecycle methods

The following hub records connections for authenticated users and broadcasts presence changes. If authentication is not configured yet, you can temporarily use a test identifier, but a real application should obtain the user identity from authentication rather than trusting a value supplied by the browser.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

[Authorize]
public sealed class PresenceHub : Hub
{
    private readonly ConnectionRegistry _registry;

    public PresenceHub(ConnectionRegistry registry)
    {
        _registry = registry;
    }

    public override async Task OnConnectedAsync()
    {
        var userId = Context.UserIdentifier;

        if (string.IsNullOrWhiteSpace(userId))
        {
            Context.Abort();
            return;
        }

        var wasOnline = _registry.IsOnline(userId);
        _registry.Add(userId, Context.ConnectionId);

        if (!wasOnline)
        {
            await Clients.All.SendAsync("UserPresenceChanged", new
            {
                UserId = userId,
                IsOnline = true,
                LastSeenAt = (DateTimeOffset?)null
            });
        }

        await Clients.Caller.SendAsync("ConnectionRegistered", new
        {
            ConnectionId = Context.ConnectionId,
            UserId = userId
        });

        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        var userId = Context.UserIdentifier;

        if (!string.IsNullOrWhiteSpace(userId))
        {
            _registry.Remove(userId, Context.ConnectionId);

            if (!_registry.IsOnline(userId))
            {
                await Clients.All.SendAsync("UserPresenceChanged", new
                {
                    UserId = userId,
                    IsOnline = false,
                    LastSeenAt = _registry.GetLastSeen(userId)
                });
            }
        }

        await base.OnDisconnectedAsync(exception);
    }
}

Inside OnDisconnectedAsync, remove only the current Context.ConnectionId. Removing all records for the user would incorrectly terminate the presence state of other tabs or devices.

4. Displaying connection status in the client

A clear client status improves the user experience. Users should be able to distinguish between a healthy connection, a temporary reconnecting state, and a connection that has permanently closed. Automatic reconnect is opt-in in the SignalR JavaScript client, so enable it explicitly.

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/presence")
    .withAutomaticReconnect([0, 2000, 10000, 30000])
    .build();

const statusElement = document.querySelector("[data-connection-status]");

function setStatus(text, cssClass) {
    statusElement.textContent = text;
    statusElement.className = cssClass;
}

connection.onreconnecting(error => {
    setStatus("Reconnecting", "status-warning");
    console.warn("The SignalR connection was temporarily lost", error);
});

connection.onreconnected(newConnectionId => {
    setStatus("Connected", "status-success");
    console.info("New connection ID:", newConnectionId);
});

connection.onclose(error => {
    setStatus("Disconnected", "status-danger");
    console.error("The SignalR connection closed", error);
});

connection.on("UserPresenceChanged", change => {
    const item = document.querySelector(`[data-user-id="${change.userId}"]`);

    if (item) {
        item.textContent = change.isOnline
            ? "Online"
            : `Last seen: ${new Date(change.lastSeenAt).toLocaleString()}`;
    }
});

async function startConnection() {
    try {
        await connection.start();
        setStatus("Connected", "status-success");
    } catch (error) {
        setStatus("Could not start", "status-danger");
        setTimeout(startConnection, 5000);
    }
}

startConnection();

After a successful automatic reconnect, the server treats the connection as new. The client therefore receives a new connection ID and the server runs OnConnectedAsync again. Never treat a connection ID as a permanent user identifier.

5. Multiple tabs and duplicate connections

When the same user opens two browser tabs, SignalR creates two separate connections. The first tab changes the user from offline to online. The second tab should usually not create another user-level online notification because the user is already online. If the first tab closes, the user remains online through the second tab. The user becomes offline only after the final active connection closes.

This is why the registry stores a collection of connections per user. A simple Dictionary<string, string> is incorrect because the second tab overwrites the first connection. Likewise, removing by user ID alone can delete active connections that belong to other tabs or devices.

Duplicate connections can also result from client code that starts the same connection more than once. In a single-page application, keep the connection manager at application scope and stop the connection deliberately when a feature is removed. Avoid creating a new hub connection every time a view is rendered.

6. Common mistakes and prevention strategies

  • Treating the connection ID as the user ID: A reconnect can produce a different connection ID, so use a stable authenticated user identifier for user-level state.
  • Keeping only in-memory state: Records disappear when the process restarts, and separate servers maintain separate views of connected users. Use distributed storage when the deployment requires it.
  • Assuming OnDisconnectedAsync always runs: A server crash or process termination may prevent a clean disconnect event. Use expiration policies or periodic reconciliation for robust presence.
  • Ignoring asynchronous operations: Missing await can cause races, incomplete writes, and notifications that arrive before state has been updated.
  • Listening only to onclose: During automatic reconnect, the client first enters the reconnecting state and then fires the reconnected callback if recovery succeeds.
  • Storing local timestamps: Store UTC values and convert them for display at the client or presentation boundary.
  • Trusting browser-supplied user IDs: Presence must be associated with the authenticated principal, not with an arbitrary value sent by the client.

7. Practice exercise

Add an online-user panel to the existing SignalR application.

  1. Register ConnectionRegistry as a singleton service.
  2. Create a PresenceHub and implement OnConnectedAsync and OnDisconnectedAsync.
  3. Map the hub endpoint to /hubs/presence.
  4. Add withAutomaticReconnect on the client and display separate messages for connected, reconnecting, and disconnected states.
  5. Open two tabs for the same authenticated user. Close one tab and verify that the user remains online.
  6. Temporarily disconnect the network and reconnect it. Confirm that ConnectionRegistered is received again and that the connection ID changes.
  7. Restart the application and explain why an in-memory registry cannot provide durable presence information.

Conclusion

This lesson introduced the connection lifecycle methods, the distinction between user identifiers and connection identifiers, and the design required for multiple tabs and devices. A reliable presence system stores a collection of connections per user, removes only the connection that actually ended, and broadcasts an offline event only when the user's final connection is gone.

These concepts prepare the application for user- and group-based messaging. They also expose the limits of an in-memory registry and provide the foundation for moving to Redis backplane and distributed connection management in later lessons.

Sources