⚙️ Asp.Net Core: Fix SignalR Reconnects Losing Group Membership
SignalR’s automatic reconnect transparently re-establishes the transport connection, but a reconnect creates a logically new connection with a new ConnectionId on the server. Group membership is keyed per-ConnectionId by default, so any earlier Groups.AddToGroupAsync calls don’t carry over — unless the application explicitly re-adds the new connection to its groups, a client that silently reconnects after a brief network blip quietly stops receiving group broadcasts.
🔎 The Problem
public class NotificationsHub : Hub
{
public async Task JoinTeam(string teamId)
{
// only called once, on the very first connect from the client
await Groups.AddToGroupAsync(Context.ConnectionId, $"team-{teamId}");
}
// after a transparent reconnect, ConnectionId changes but
// JoinTeam is never called again - the new connection is
// in no groups at all
}
✅ Fix: Re-Join Groups on Every Connect, Not Just the First
- Re-run group-join logic inside the hub’s
OnConnectedAsyncfor every new connection unconditionally, rather than only on the client’s very first connect, so a reconnect’s new ConnectionId gets re-added to whatever groups the user’s session should belong to. - Track which groups a user should be in by user identity (not ConnectionId) in your own application state, so
OnConnectedAsynccan look that up and restore membership regardless of whether this is a first connection or a reconnect. - On the client, listen for the
onreconnectedevent and treat it as a signal to re-confirm server-side state, rather than assuming a successful reconnect means everything picked back up exactly where it left off.
🚨 Why This Is Dangerous
- A user who appears connected but has silently fallen out of their groups will stop receiving real-time updates with no visible error, making the bug look like an intermittent, unreproducible gap in functionality rather than the deterministic reconnect behavior it actually is.
SignalR’s automatic reconnect restores the connection, not the connection’s group memberships — those have to be rebuilt explicitly, every time, because to the server a reconnect and a first connect look exactly the same.
