wasAsked.

How would you implement real-time notifications using SignalR while handling reconnects and authorization?

Swiggy · Full Stack Developer · 3-4-years · technical

Published

Year not specified · .NET, ASP.NET Core, React

Community answers

Posted by wasAsked editorial collection

SignalR is useful for server-pushed updates such as order status, notifications, and dashboards. Treat a connection as transient: reconnects occur, messages can be missed, and a client may have several connections. Example: public Task JoinOutlet(Guid outletId) { AuthorizeOutlet(outletId); return Groups.AddToGroupAsync(Context.ConnectionId, $"outlet:{outletId}"); } await hub.Clients.Group($"outlet:{outletId}").SendAsync("OrderChanged", dto, ct); Authorize group membership from server-side claims, never from an untrusted ID alone. Send small events and let clients reload authoritative state after reconnect. For multiple instances use a supported backplane/service, and apply rate limits, versioned payloads, correlation, and disconnect cleanup.

Backbencher Developer · · 0 likes

SignalR keeps a persistent connection (WebSockets, falling back to Server-Sent Events or long polling) so the server can push notifications to the browser. Server - Create a hub and require authentication: [Authorize] public sealed class NotificationsHub : Hub { } app.MapHub<NotificationsHub>("/hubs/notifications"); - Send from anywhere through IHubContext<NotificationsHub>: await hub.Clients.User(userId).SendAsync("notification", dto, ct); Clients.User uses the user ID claim (IUserIdProvider), so every tab and device of that user receives it. - Use groups for tenants, rooms or orders: Groups.AddToGroupAsync(Context.ConnectionId, $"order:{id}"), and verify the user may join that group before adding them. Authorization details - WebSockets cannot send custom headers from the browser, so for JWT authentication the client sends the token as access_token in the query string; read it in JwtBearerEvents.OnMessageReceived for hub paths only. With cookie authentication this is not needed. - Hub methods called by clients need their own [Authorize] policies and resource checks. Reconnects (React client with @microsoft/signalr) const connection = new HubConnectionBuilder() .withUrl('/hubs/notifications', { accessTokenFactory: () => getToken() }) .withAutomaticReconnect([0, 2000, 10000, 30000]) .build(); connection.onreconnected(() => refetchUnread()); - After a reconnect the connection ID changes and messages sent while disconnected are lost, because SignalR does not store messages. Persist notifications in a database and fetch missed ones (since the last received ID) on reconnect or page load. - Handle onclose when automatic reconnect gives up: show an "offline" indicator and retry with backoff. - Refresh tokens: accessTokenFactory is called on each (re)connection, so return a fresh token. Scale-out - With several servers, use the Redis backplane or Azure SignalR Service so messages reach users connected to other instances. - Configure sticky sessions when not using WebSockets exclusively. Keep payloads small (an ID and summary), and let the client fetch details through the normal API with its usual authorization.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics