Explains ASP.NET Core SignalR: hubs and the hub lifetime, transport negotiation and fallback, the JSON and MessagePack protocols, groups and users, strongly typed hubs with Hub<T>, IHubContext, and authentication and authorisation for connections.
SignalR is ASP.NET Core's real-time framework. A hub is a class whose public methods clients call, and the server calls methods on clients through Clients.All, Clients.Group(...) or Clients.User(...). Hubs are transient, created per invocation, so they hold no state. On connect the client calls negotiate and uses the best transport available: WebSockets, then Server-Sent Events, then long polling. Groups fan messages out to subsets of connections, but they live in memory, so a reconnecting client must re-join them (usually in OnConnectedAsync). Strongly typed hubs (Hub<IOrderClient>) replace method-name strings with an interface. Authentication uses the normal pipeline with [Authorize]. Browsers can't send an Authorization header on WebSockets or EventSource, so as a workaround the token travels as an access_token query parameter, read in JwtBearerEvents.OnMessageReceived.
The trade-off: reconnects and routing come free, but every client holds a stateful connection that you must plan to scale.
"SignalR is an RPC layer over persistent connections. I define a hub, a class deriving from
HuborHub<T>, and map it withapp.MapHub<NotificationsHub>("/hubs/notifications"). Clients call its public methods, and the server calls methods on clients throughClients. One important detail is that hubs are transient: a new instance is created for every invocation. So you never keep state in fields; you useContext.ConnectionId,Context.User, or an external store.When a client connects, it posts to
/negotiateand gets the transports the server supports. It tries WebSockets first, then Server-Sent Events, then long polling. The messages on top use the JSON hub protocol by default, or MessagePack if you want smaller binary payloads. For targeting I useClients.Caller,Clients.Group("region-vic"), orClients.User(userId).Usermaps to every connection of that authenticated user, using theNameIdentifierclaim by default. Groups are just in-memory lists of connection ids. They are not persisted, so after a reconnect the client has to join them again; I do that inOnConnectedAsyncfrom the user's claims. I always use strongly typed hubs:Hub<INotificationClient>turnsClients.User(id).JobAssigned(msg)into a compile-time-checked call instead ofSendAsync("JobAssigned", ...)with a magic string.For security, the hub goes through the normal authentication and authorisation middleware, so
[Authorize]on the hub or on individual methods works. The catch is that browsers can't set anAuthorizationheader on WebSockets orEventSource, so the JavaScript client sends the token asaccess_tokenin the query string. On the server you copy it into the context inJwtBearerEvents.OnMessageReceivedfor the hub path. The mistake I see is putting business logic straight into hubs. I keep hubs thin and push from application services throughIHubContext<THub, TClient>."
| Concept | What it is | Notes |
|---|---|---|
| Hub | Server class clients call into | Transient per invocation; Context, Clients, Groups available |
OnConnectedAsync / OnDisconnectedAsync |
Connection lifecycle hooks | Join groups here; disconnect gets the exception if it was not clean |
| Transports | WebSockets, SSE, long polling | Chosen by negotiate; can be restricted with HttpConnectionDispatcherOptions.Transports |
| Hub protocol | JSON (default) or MessagePack | MessagePack is smaller and faster, but harder to debug |
| Groups | Named sets of connections | Not persisted; lost on reconnect or server restart |
| Users | All connections for one user id | Default IUserIdProvider uses ClaimTypes.NameIdentifier |
IHubContext<THub, TClient> |
Send from outside a hub | Inject into services, background workers, endpoints |
| Call | Who receives it |
|---|---|
Clients.All |
Every connection |
Clients.Caller / Clients.Others |
The calling connection / everyone else |
Clients.Group("g") / Clients.OthersInGroup("g") |
Members of a group |
Clients.User(userId) |
All connections of that user (tabs, devices) |
Clients.Client(connectionId) |
One connection |
app.UseAuthentication() and app.UseAuthorization() before MapHub.[Authorize] on the hub, policies on sensitive methods.access_token from the query only for hub paths, and keep tokens short-lived (the token is checked when the connection starts, not on every message).CloseOnAuthenticationExpiration = true (.NET 8+) if a connection must end when its token expires.access_token from request logs.In a [field-service] app we pushed job assignments to about [4,000] technicians' browsers. Using Clients.User(technicianId) meant a technician with the app open on a laptop and a tablet got the update on both, and moving the hub to MessagePack cut payload size by about [40%] on mobile connections.
Checks practical SignalR knowledge: hub lifetime, transports, targeting, typed hubs and how authentication really works for browser connections.
Green flags
access_token query string and OnMessageReceivedIHubContext to push from outside the hubRed flags
Your hub methods (RPC) NotificationsHub.Acknowledge(id)
-------------------------------------------------------------------------
Hub protocol JSON / MessagePack framing (invocation, completion, ping)
-------------------------------------------------------------------------
Connection abstraction HttpConnectionDispatcher, connection id, keep-alive
-------------------------------------------------------------------------
Transport WebSockets | Server-Sent Events | Long Polling
-------------------------------------------------------------------------
Kestrel / HTTP /hubs/notifications, /hubs/notifications/negotiate
POST /hubs/notifications/negotiate?negotiateVersion=1.connectionToken and the transports it supports.wss://.../hubs/notifications?id=<token>.{"protocol":"json","version":1}).KeepAliveInterval (15 s by default), and the client treats the server as gone after ServerTimeout (30 s). Keep the client timeout at about twice the server keep-alive.With Azure SignalR Service, negotiate returns a redirect to the service URL and an access token, and the client connects there instead of to your app.
A hub is resolved from DI for each connect, disconnect and method invocation, then disposed. That is why:
async void or fire-and-forget work inside a hub method can run after the hub is disposed. Use IHubContext from a background service instead.Since .NET 7, hub methods can also take services as parameters, and clients can return results to the server (Clients.Client(id).InvokeAsync<T>()).
The default HubLifetimeManager keeps an in-memory map of group name to connection ids per server. That explains two behaviours:
Clients.Group("x") on server A never reaches members connected to server B. The Redis backplane or Azure SignalR Service replaces the lifetime manager to fix that.browser --negotiate (Authorization: Bearer ...)--> JwtBearer validates
browser --wss://...?access_token=eyJ...--------> OnMessageReceived copies token -> JwtBearer validates
-> Context.User populated for the whole connection
The user is fixed when the connection is established. Revoking a token does not drop open connections unless you enable CloseOnAuthenticationExpiration or close them yourself.
Hub<IChatClient>, connect two browser tabs, and send to Clients.Others.{"type":6} pings.HttpTransportType.LongPolling and watch the POST/GET traffic replace the WebSocket.[Authorize] and the OnMessageReceived handler, then connect with and without a token and compare the 401.OnConnectedAsync re-joins them.A strongly typed, authenticated hub, plus sending from outside the hub with IHubContext.
// Program.cs (.NET 10)
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
builder.Configuration.Bind("Jwt", options);
options.Events = new JwtBearerEvents
{
// Browsers can't set headers on WebSockets/SSE, so the client sends ?access_token=.
OnMessageReceived = ctx =>
{
var token = ctx.Request.Query["access_token"];
if (!string.IsNullOrEmpty(token) && ctx.HttpContext.Request.Path.StartsWithSegments("/hubs"))
ctx.Token = token;
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
builder.Services.AddSignalR(o => o.KeepAliveInterval = TimeSpan.FromSeconds(15));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapHub<NotificationsHub>("/hubs/notifications");
// Pushing from an ordinary endpoint (or a BackgroundService) through IHubContext.
app.MapPost("/jobs/{id:int}/assign/{technicianId}", async (
int id, string technicianId,
IHubContext<NotificationsHub, INotificationClient> hub, CancellationToken ct) =>
{
await hub.Clients.User(technicianId).JobAssigned(new JobAssigned(id, DateTimeOffset.UtcNow));
return TypedResults.Accepted($"/jobs/{id}");
}).RequireAuthorization();
app.Run();
public sealed record JobAssigned(int JobId, DateTimeOffset AssignedAt);
// The client contract: no more SendAsync("JobAssigned", ...) magic strings.
public interface INotificationClient
{
Task JobAssigned(JobAssigned message);
}
[Authorize]
public sealed class NotificationsHub(ILogger<NotificationsHub> logger) : Hub<INotificationClient>
{
public override async Task OnConnectedAsync()
{
// Groups are in memory and lost on reconnect, so re-join from claims every time.
var region = Context.User?.FindFirstValue("region");
if (region is not null)
await Groups.AddToGroupAsync(Context.ConnectionId, $"region-{region}");
await base.OnConnectedAsync();
}
[Authorize(Roles = "Dispatcher")]
public Task Acknowledge(int jobId)
{
logger.LogInformation("Job {JobId} acknowledged by {User}", jobId, Context.UserIdentifier);
return Task.CompletedTask;
}
}
// Browser client
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/notifications", { accessTokenFactory: () => getToken() })
.withAutomaticReconnect()
.build();
connection.on("JobAssigned", msg => showToast(msg));
await connection.start();
OnConnectedAsync from claims or stored subscriptions.SendAsync("methodName", ...) everywhere. Why it is wrong: A typo or a rename silently breaks clients. Instead: Use Hub<TClient> and IHubContext<THub, TClient>.Authorization header to arrive on WebSocket connections from the browser. Why it is wrong: The browser APIs can't set it, so every connection is anonymous and gets a 401. Instead: Use accessTokenFactory and read access_token in OnMessageReceived for hub paths only.MaximumParallelInvocationsPerClient = 1), and a disposed hub can't be used later. Instead: Queue the work and push the result through IHubContext.CloseOnAuthenticationExpiration, and check authorisation for sensitive actions.I treat a hub as an edge adapter, like a controller: it authenticates, maps the message and delegates. Business events are raised in the application layer and pushed through IHubContext<THub, TClient>, which also makes the push easy to test with a fake. That separation matters when you later move to Azure SignalR Service or replace SignalR for some clients.
| Decision | Option A | Option B | Guidance |
|---|---|---|---|
| Protocol | JSON | MessagePack | JSON for debuggability; MessagePack when payloads are large or clients are on mobile networks |
| Targeting | Groups | Clients.User |
User for per-person notifications across tabs; groups for topics, tenants, rooms |
| Hosting | Self-hosted plus Redis backplane | Azure SignalR Service | Azure SignalR when you want to offload connections and avoid sticky sessions to your app |
| Typing | SendAsync strings |
Hub<TClient> |
Always strongly typed unless you generate clients from another source |
What SignalR is not: a durable message queue. If a client is offline, the message is gone. For anything that must not be lost (a payment confirmation, an alert a nurse must see), store it and let the client fetch missed items on reconnect.
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
A SignalR server only knows its own connections and groups, held in memory. Scale out to several instances and Clients.Group("x") on server A never reaches users connected to server B. Self-hosted, you also need sticky sessions, because the negotiate request and the SSE or long-polling requests must reach the same server (WebSockets-only with SkipNegotiation avoids that). Affinity costs you even load distribution, and clients on a failed instance must reconnect. The Redis backplane fixes delivery by publishing every message to every server. It works well at moderate scale, but every server processes every message, and pub/sub doesn't buffer during a Redis failover, so run Redis highly available. Azure SignalR Service moves the client connections off your app: your servers keep a handful of connections to the service, which handles fan-out, at about 1,000 concurrent connections per Standard unit.
For 100,000 connections, I would use Azure SignalR Service, plan units from peak connections and fan-out, and design for reconnect storms.
Last updated 23 Nov 2026.