SignalR
SignalR lets a server push messages to connected clients as events happen, instead of clients repeatedly polling for changes.
Overview
A hub is a transient server endpoint whose methods receive client invocations and whose typed client contract pushes events to connected callers, users, groups, or all clients. SignalR negotiates WebSockets, Server-Sent Events, or long polling and handles framing and connection management, but an application still owns identity, authorization, group membership, reconnect reconciliation, message compatibility, ordering assumptions, and missed-event recovery. Connections are temporary and a reconnect usually receives a new connection identifier; groups are routing conveniences rather than durable membership or security stores. Multi-instance deployments need Azure SignalR Service or a supported backplane so a message reaches connections on every node, plus sticky-session and transport settings appropriate to the chosen scale path. Production design bounds receive size, invocation concurrency, send rate, connection count, group fan-out, and buffered state, keeps hubs thin, sends compact versioned contracts, and uses a durable source of truth that clients re-fetch after reconnect. WebSockets also require correct proxy upgrades, idle timeouts, origin policy, token handling, observability, and graceful draining.
What you will learn
- Model strongly typed hub and client contracts while keeping business logic outside hubs.
- Authenticate connections and authorize each invocation and target resource.
- Use caller, user, connection, and server-controlled groups correctly.
- Design reconnect and snapshot reconciliation without assuming delivery durability.
- Scale across instances with an appropriate managed service or backplane.
- Test negotiation, transport, denial, group routing, payload bounds, and deployed proxy behavior.
Prerequisites
- ASP.NET Core authentication and authorization, async C#, and JSON contracts.
- Basic WebSocket, proxy, horizontal scaling, and distributed state concepts.
- A .NET 10 SDK to run the operations-room sample.
When to use SignalR
Good fit
- Use SignalR for interactive notifications, dashboards, collaboration, or presence where server push materially improves experience.
- Use groups for server-authorized routing to a changing subset of connections.
- Use a durable API snapshot plus live events when clients must recover after disconnect.
Choose another approach when
- Do not use SignalR as the only durable event store or guaranteed message bus.
- Do not let callers join tenant, user, order, or privileged groups without server authorization.
- Do not broadcast large state to every connection when a targeted notification and API refresh will work.
- Do not assume reconnect preserves connection ID, group membership, ordering across streams, or missed messages.
Key concepts
A hub is a server-side class clients connect to and call methods on; the server can call back to connected clients through the same hub.
SignalR automatically selects WebSockets when available and falls back to other transports, so application code does not manage the transport directly.
Connections can be organized into groups or targeted by user identifier, letting the server send updates to exactly the right audience.
A backplane such as Redis fans messages out across multiple server instances so clients connected to different servers still receive the same broadcasts.
Negotiation, connect, transient disconnect, reconnect, timeout, and graceful drain are separate states clients and servers must observe.
Hub<TClient> turns server-to-client method names and payloads into a compile-time contract for .NET server code.
A client reloads an authoritative snapshot after reconnect, then applies compact live events without assuming none were missed.
SignalR provides live routing to current connections, not durable exactly-once delivery or offline retention.
Architecture
Clients connect to a hub over a negotiated transport; the server calls back to individual connections, groups, or all clients as events occur.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The dedicated operations-room sample authenticates each connection, exposes a strongly typed client contract, validates server-controlled room names, bounds messages and history, sends a snapshot on join, broadcasts only to the room group, and verifies negotiation and WebSocket behavior through the real .NET client.
- 01Define the live use case
Separate transient notifications from durable state, offline delivery, and commands that belong to APIs or messaging.
- 02Design contracts
Create small versionable hub inputs and a strongly typed client interface with explicit event names.
- 03Authenticate early
Configure cookie, bearer, or workload identity before MapHub and derive a stable user identifier.
- 04Authorize routing
Validate every invocation and allow group membership only after tenant and resource checks.
- 05Bound the connection
Set receive size, parallel invocations, timeouts, keepalive, fan-out, rate, and per-connection state limits.
- 06Reconcile reconnects
Have clients rejoin authorized groups and fetch a durable snapshot before resuming event application.
- 07Scale and verify
Choose managed scale or backplane and test real proxy upgrades, multi-node fan-out, drain, and observability.
Code example
A hub method adds a caller to a group; a separate service call notifies just that group when an order's status changes.
public sealed class OrderStatusHub : Hub
{
public Task SubscribeToOrder(string orderId) =>
Groups.AddToGroupAsync(Context.ConnectionId, $"order:{orderId}");
}
public sealed class OrderNotifier(IHubContext<OrderStatusHub> hub)
{
public Task NotifyStatusChangedAsync(Guid orderId, string status) =>
hub.Clients.Group($"order:{orderId}").SendAsync("statusChanged", status);
}Testing strategy
Real-time correctness requires a real client connection, not only direct hub method calls.
- Use the supported client against an in-process server to test negotiate and WebSocket or fallback transport.
- Prove anonymous and unauthorized connections or invocations are denied.
- Join an authorized group and assert only intended clients receive the typed message.
- Test invalid room, payload size, rate, and parallel-invocation limits.
- Simulate disconnect and reconnect, then prove group rejoin and snapshot reconciliation.
- Run a multi-instance or managed-service test before claiming horizontal fan-out works.
Security considerations
A persistent connection can invoke repeatedly and receive pushed data, so both directions require least privilege.
- Authenticate the connection and authorize every hub method, group, tenant, and target resource.
- Restrict origins deliberately and protect browser token transport, logs, and query-string handling.
- Never expose connection IDs as authorization credentials or trust caller-selected group names.
- Bound messages, invocation rate, parallel work, connection count, and fan-out to limit abuse.
- Send minimum data and avoid detailed production errors or sensitive payload logging.
Performance and scalability
Capacity is driven by concurrent connections, fan-out, message rate, payload size, and transport behavior.
- Send compact events and let clients fetch large authoritative state through cacheable APIs.
- Target users or groups rather than broadcasting globally.
- Measure active connections, reconnects, send queue, message bytes, hub latency, errors, and backplane lag.
- Use MessagePack only after client compatibility and measured bandwidth or CPU benefit.
- Load-test connection ramps, steady fan-out, failure recovery, and multi-node scale with production-shaped limits.
Deployment and operations
The entire route must support long-lived upgraded connections and safe multi-instance routing.
- Verify WebSocket upgrade headers, TLS, origins, proxy buffering, idle timeout, and maximum request size.
- Configure Azure SignalR Service or a supported backplane before scaling beyond one node.
- Plan sticky sessions only where the selected transport and scale architecture require them.
- Drain connections during deployment and make reconnect plus snapshot recovery routine.
- Smoke-test authenticated connect, group join, broadcast, disconnect, reconnect, and cross-instance fan-out.
Common problems and fixes
WebSockets fail and clients fall back.
Likely cause: A proxy, load balancer, origin, TLS, or upgrade setting blocks the transport.
Fix: Inspect browser and server transport logs and verify the exact deployed upgrade path.
Some clients miss broadcasts after scale-out.
Likely cause: Connections are split across nodes without a backplane or managed service.
Fix: Configure supported scale-out and test a sender and receiver on different instances.
A reconnected client stops receiving group messages.
Likely cause: The new connection did not rejoin authorized groups.
Fix: Re-establish membership and reload the durable snapshot after reconnect.
One tenant sees another tenant's update.
Likely cause: Caller-controlled group membership or missing tenant authorization mixed audiences.
Fix: Derive groups server-side after tenant and resource checks and add negative routing tests.
Memory grows with connection count.
Likely cause: Payloads, per-connection state, queues, or invocation concurrency are unbounded.
Fix: Bound each dimension, remove hub state, target fan-out, and load-test retention.
Clients reconnect continuously.
Likely cause: Idle timeouts, keepalive, token expiry, network instability, or server draining is misaligned.
Fix: Correlate client and server lifecycle telemetry and tune supported timeout and credential refresh behavior.
Best practices
- Scope broadcasts to server-authorized users or groups instead of all clients.
- Add a supported backplane or managed SignalR service before multi-instance scale.
- Design reconnect to re-authenticate, rejoin groups, and reload authoritative state.
- Keep hubs transient and thin and delegate business rules to application services.
- Use typed compact message contracts and evolve them compatibly.
- Bound payload, invocation, connection, queue, history, and fan-out work.
- Treat groups as routing, not durable membership or authorization storage.
- Test negotiation, real transports, denial, multi-node fan-out, and graceful drain.
Production checklist
- The live feature distinguishes transient events from durable source-of-truth state.
- Hub and client contracts are small, typed, versioned, and compatibility-tested.
- Connections, methods, groups, tenants, and resources are authenticated and authorized.
- Message size, rate, parallel invocation, connection count, history, and fan-out are bounded.
- Reconnect re-authenticates, rejoins groups, and reconciles an authoritative snapshot.
- Managed scale or backplane behavior is tested across instances.
- WebSocket, fallback, proxy, TLS, origin, timeout, and drain settings are verified.
- Connection, reconnect, error, message, fan-out, and backplane telemetry has alerts.
Common interview questions
How does SignalR decide which transport to use?
It negotiates with the client and prefers WebSockets when both the browser and any intermediate proxies support it, falling back to Server-Sent Events or long polling otherwise, without the application needing to choose a transport explicitly.
Why is a backplane needed when scaling SignalR horizontally?
Each server instance only knows about the connections it holds directly; a backplane like Redis relays messages between instances so a broadcast reaches clients connected anywhere, not just on the server that triggered it.
What is a SignalR group used for?
It lets the server send a message to a named subset of connections—for example everyone viewing one order—without tracking connection IDs manually in application code.
Does SignalR guarantee durable delivery?
No. It routes live messages to current connections; durable retention, replay, acknowledgement, and offline delivery need another store or broker.
What should a client do after reconnect?
Re-authenticate as needed, rejoin authorized groups, reload an authoritative snapshot, and then resume applying live events.
Why should group names not be trusted from clients?
A caller could select another tenant or resource. The server must authorize the target and derive membership rules before adding the connection.
What drives SignalR capacity?
Concurrent connections, connection churn, message rate and size, fan-out width, serialization, transport, and backplane or managed-service behavior.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
SignalR Operations Room
A .NET 10 real-time service demonstrating authenticated connections, strongly typed hub clients, server-controlled groups, bounded messages and snapshots, reconnection design, and real WebSocket client tests.
- Run
dotnet run --project src/SignalROperationsRoom- Test
dotnet test SignalROperationsRoom.slnx