skip to content

Why does a SignalR client stop receiving its room's group messages after an automatic reconnect, and how should the app restore membership?

level: seniorimportance: must knowfreq 52%

answer

  1. groups hold connection ids
  2. reconnect means a new connection id
  3. old id removed from groups on disconnect
  4. rejoin from OnConnectedAsync using durable state
  5. or the client calls JoinRoom in onreconnected

basics

~20 s

Groups store connection ids, and a reconnect is a new connection whose new id joined nothing; the old id left its groups on disconnect. Re-add it, ideally in OnConnectedAsync from the user's stored rooms, or by the client calling JoinRoom in onreconnected.

solid answer

~50 s

SignalR group membership is keyed by connection id and held in memory. When the transport drops, the server ends that connection and removes it from all its groups; automatic reconnect then opens a brand-new connection with a new `ConnectionId`, which belongs to no group, and the docs state that membership is not preserved across reconnects. Two fixes, often combined. Server-driven: keep the member's rooms in a durable store keyed by user id, and in `OnConnectedAsync` add `Context.ConnectionId` to each of them; this also covers new tabs and server restarts. Client-driven: in the client's `onreconnected` handler call `JoinRoom` for each room it shows; simple, but it trusts client state and needs the same authorization checks. Stateful reconnect keeps the same connection, and its groups, across short WebSocket blips only. Either way the client should also refetch missed messages.

code

csharp · 20 lines
csharp
public class SpaceHub(RoomMemberships memberships) : Hub
{
    // Runs for every new connection: first connect, reconnect, new tab, after a restart.
    public override async Task OnConnectedAsync()
    {
        var userId = Context.UserIdentifier;
        if (userId is not null)
        {
            foreach (var roomId in await memberships.GetRoomsAsync(userId))
                await Groups.AddToGroupAsync(Context.ConnectionId, $"room-{roomId}");
        }
        await base.OnConnectedAsync();
    }

    public async Task JoinRoom(int roomId)
    {
        await memberships.AddAsync(Context.UserIdentifier!, roomId);   // durable
        await Groups.AddToGroupAsync(Context.ConnectionId, $"room-{roomId}");
    }
}

go deeper

for a junior

Remember that a reconnect gives the client a new connection id, so it has to join its rooms again.

for a middle

Explain why groups hold connection ids, that disconnect removes the old id, and the two ways to rejoin.

for a senior

Prefer server-driven rejoin from durable membership in OnConnectedAsync, keep authorization server-side, and refetch missed messages after rejoining.

for a principal

Model room membership as application data with SignalR groups as a cache of it, so reconnects, devices and restarts all converge on one source of truth.

## The symptom In the co-working space app, a member is chatting in `room-3`. Their train enters a tunnel, the client's automatic reconnect brings the connection back, the UI looks healthy, and yet no room messages arrive. Sending still works; receiving does not. ## Why it happens Three facts combine: 1. **Groups contain connection ids**, not users. `AddToGroupAsync(Context.ConnectionId, "room-3")` added *that* connection. 2. **The old connection is gone.** When the transport dropped and the server ended the connection, the hub lifetime manager removed it from every group it was in. 3. **A reconnect is a new connection.** Automatic reconnect runs the whole connect sequence again; the server assigns a new `ConnectionId`, which belongs to no group. The docs say it plainly: group membership is not preserved when a connection reconnects, and the connection needs to rejoin. `Clients.User(...)` messages still arrive, because the user identifier is recomputed from the same claims on the new connection; only group-based routing breaks. ## Fix 1: server-driven rejoin (preferred) Treat "which rooms is this member in" as **application state** stored outside SignalR, keyed by user id, and re-apply it whenever a connection starts: ```csharp public override async Task OnConnectedAsync() { var rooms = await memberships.GetRoomsAsync(Context.UserIdentifier!); foreach (var roomId in rooms) await Groups.AddToGroupAsync(Context.ConnectionId, $"room-{roomId}"); await base.OnConnectedAsync(); } ``` Advantages: - the same code path handles a reconnect, a second tab, a new device and a server restart; - authorization is applied by the server from its own data, not from what the client claims; - `JoinRoom` and `LeaveRoom` hub methods update the store as well as the group, so the two stay in step. ## Fix 2: client-driven rejoin The client remembers what it joined and calls back after reconnecting: ```javascript connection.onreconnected(async () => { for (const roomId of joinedRooms) { await connection.invoke("JoinRoom", roomId); } }); ``` It is quick to add, but `JoinRoom` must re-check authorization each time, and if the server restarted while the client was connected elsewhere, only the client's memory says what it should be in. ## Comparing the options | Approach | Covers | Watch out for | |---|---|---| | rejoin in `OnConnectedAsync` from a store | reconnects, new tabs, restarts | one store read per connect | | `JoinRoom` from `onreconnected` | reconnects of that client | trusts client state; misses restarts handled by a fresh page | | stateful reconnect (.NET 8+) | short WebSocket blips only, same connection id | opt-in on both ends; longer outages still need a rejoin | ## The other half: missed messages Rejoining restores future delivery only. Messages sent to `room-3` while the member was disconnected were never delivered to the new connection, so the client should fetch recent history (for example, everything after the last message id it saw) right after rejoining. ## Related traps - Using the user id as the group member, which `AddToGroupAsync` does not support; it takes a connection id. - Rejoining only in `onreconnected` and forgetting that a page reload produces a fresh connection without that callback. - On several servers, rejoin logic is unchanged, but group sends must reach other servers through the scale-out layer.

  • Why do Clients.User messages keep arriving after the reconnect when group messages stop?
    User routing is recomputed per connection: the new connection runs `IUserIdProvider.GetUserId` at its handshake and gets the same identifier from the same claims. Group routing depends on membership of the specific connection id, and the new id was never added to any group.
  • Does stateful reconnect remove the need for rejoin logic?
    No. Stateful reconnect keeps the same connection, and therefore its groups, across short drops on WebSockets when both ends opt in. A longer outage, another transport, a new tab or a server restart still produces a new connection id, so the rejoin path is still needed.

Group membership is like a visitor badge printed for one visit: when the member walks out and back in, the old badge is void and the front desk prints a new one, so whatever list the old badge was on has to be re-applied to the new badge.

  • SignalR remembers a user's groups and re-adds them after a reconnect.
  • A reconnected client keeps its old connection id, so groups still match.
  • Adding the user id to the group once makes membership survive reconnects.
  • Rejoining the group also delivers the messages sent while disconnected.
  • Group membership after reconnect only breaks when there are several servers.