Introduction

SignalR in .NET is an ASP.NET Core library for real-time communication between server and clients. It negotiates a compatible transport and offers a high-level API for calls between browser and server, event delivery, groups and streaming. I would choose it when the interface needs to receive updates with low latency or send interactive commands without turning every change into a new periodic query. SignalR simplifies the channel; it does not provide durable storage, ready-made domain authorization or exactly-once delivery guarantees.

That difference changes the design: connections drop, events can be lost and an authenticated user may still not have access to the requested environment. In Dokpod, the browser receives a small invalidation, queries the state through the REST API and only joins the group after the Hub checks authorization. The BFF keeps tokens out of the browser; in the article on BFF and security in SPAs, I explain that pattern in more detail.

This is the third article in the APIs and Communication in .NET series. The part on gRPC in .NET 10 explains the bidirectional mTLS-protected channel between API and agents. The comparison Real time in Angular and .NET discusses WebSockets, SSE, SignalR and Long Polling in more detail. Here the focus is different: the Hub lifecycle, calls, authorization, groups, subscription recovery and operational decisions.

ℹ️ Info: The public Dokpod repository did not have a stable release or tag at the time of reference. The code links in this article point to main, which is mutable; the files may change after this review.

Prerequisites

The examples use ASP.NET Core/.NET 10 and Angular; basic knowledge of C#, HTTP and web authentication is enough. The Dokpod snippets are illustrative, not a standalone sample.

It helps to distinguish four terms. A Hub is the abstraction that exposes server methods and sends events to clients. A logical connection is the session SignalR manages, even when the underlying transport changes. A group is an ephemeral association of connections for targeted delivery. An invalidation is a signal telling the client to query a state source again, not a copy of the state itself.

What SignalR abstracts, and what is still protocol

SignalR organizes messages over a connection managed by the library. The client calls Hub methods with invoke (and can await a result) or send (without awaiting the application result). The Hub sends events to the caller, to groups or to all clients. Arguments are serialized by the Hub protocol: JSON is the default and MessagePack is a binary alternative.

This API is not WebSocket itself. SignalR negotiates a transport and uses the Hub protocol on top of it: WebSockets is preferred when available; Server-Sent Events (SSE) and Long Polling are alternatives. The fallback depends on support and configuration in the client, server and intermediaries. It does not make every transport available in every environment, nor does it turn a one-way transport into a duplex one.

Transport and format are separate layers: JSON or MessagePack can use any compatible SignalR transport. Raw WebSockets are an option when the application needs to control the protocol, but then it takes on the details of framing, reconnection and routing. The Hub is not a long-lived domain session either: instances serve invocations, and persistent state should live in services or storage. To send messages outside an invocation, use IHubContext<T>.

Automatic negotiation is a compatibility convenience, not a performance measurement; validate the actual transport per client and environment.

From registering the Hub to per-environment authorization

In ASP.NET Core, AddSignalR registers the infrastructure and MapHub exposes the endpoint. The Dokpod Hub at /hubs/control-plane has [Authorize], as does its route. That blocks anonymous connections, but authentication does not authorize access to every environment.

JoinEnvironmentAsync validates the identifier, takes the sub and the access token received from the BFF from the authenticated context, and asks Keycloak for a decision on urn:dokpod:environment:{id} with the environment:read scope. Only an allowed decision leads to Groups.AddToGroupAsync; a denial, unavailability or an indeterminate result does not grant access.

The group has a deterministic name, such as environment-{guid}, but that name is not a credential. Authorization happens in the API before the association; the identifier received does not let the client pick any group it wants. Asynchronous operations receive ConnectionAborted to cancel work when the connection goes away.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public async Task JoinEnvironmentAsync(string environmentId)
{
    if (string.IsNullOrWhiteSpace(environmentId) || environmentId.Length > 64 ||
        environmentId.Any(character => !char.IsLetterOrDigit(character) && character != '-'))
        throw new HubException("Identificador de ambiente inválido.");

    var httpContext = Context.GetHttpContext();
    var accessToken = ExtractAccessToken(httpContext);
    var subject = Context.User?.FindFirstValue("sub");
    if (string.IsNullOrWhiteSpace(accessToken) || string.IsNullOrWhiteSpace(subject) ||
        !Guid.TryParse(environmentId, out var environmentGuid))
        throw new HubException("Acesso negado.");

    var decision = await authorizationDecider.DecideAsync(
        $"urn:dokpod:environment:{environmentGuid:D}", EnvironmentResourceScopes.Read,
        AuthenticatedActor.FromSubject(subject), accessToken, GetCorrelationId(httpContext),
        Context.ConnectionAborted);
    if (!decision.Allowed) throw new HubException("Acesso negado.");

    await Groups.AddToGroupAsync(Context.ConnectionId, GroupFor(environmentId),
        Context.ConnectionAborted);
}

📂 Source Code: ControlPlaneHub.cs and ApiHost.cs. The Hub’s exception messages remain in Portuguese, as in the original project.

The Hub is appropriate for validations tied to the caller and for coordinating this short flow. Larger rules live in application services, so authorization, auditing, limits and domain effects do not depend on a specific connection. If several invocations run concurrently, the implementation should not assume that calls from the same connection will be serialized in every scenario; shared state needs synchronization and an explicit owner.

Angular client through the BFF, with no token in the browser

The browser uses a same-origin URL. HubConnectionBuilder registers handlers, enables reconnection and sends the session cookie; beforehand, the service obtains an antiforgery token from the BFF for X-Dokpod-Antiforgery. The cookie is HttpOnly: Angular neither reads nor forwards the API Bearer token.

The BFF authenticates the session and adds the token obtained from the server-side ticket only on the BFF → API hop. On the downstream WebSocket, the Bearer goes in Authorization, never back to the browser. The BFF protects the negotiation POST against CSRF and validates Origin; the API still authorizes each environment.

invoke waits for the invocation to complete and rejects the promise on failure. send does not confirm that the business rule completed. Register handlers before start so you do not lose events received right after connecting.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const { requestToken } = await firstValueFrom(
  this.http.get<AntiforgeryResponse>('bff/antiforgery'),
);
const connection = new HubConnectionBuilder()
  .withUrl(controlPlaneHubUrl(document.baseURI), {
    headers: { 'X-Dokpod-Antiforgery': requestToken },
    withCredentials: true,
  })
  .withAutomaticReconnect()
  .build();

connection.on('invalidated', (notification: { environmentId: string; kind: InvalidationKind }) =>
  this.publish(notification.environmentId, notification.kind));
connection.onreconnected(() => void this.rejoinEnvironment(connection, environmentId));
await connection.start();
await connection.invoke('JoinEnvironmentAsync', environmentId);

📂 Source Code: console-realtime.service.ts and BffHost.cs.

The snippet omits cleanup and state handling. In the real service, a start() failure is handled as an initial error; withAutomaticReconnect() covers an already established connection that dropped. The interface should distinguish those cases, without inferring connectivity from the mere existence of the service.

Groups and invalidations: fast notice, durable read

After authorization, the client joins the environment group. When a projection changes, SignalRControlPlaneNotifier uses IHubContext<ControlPlaneHub> to send invalidated; the publisher does not instantiate a Hub or depend on a call from the browser.

The payload contains only the environment identifier and the resource type, such as inventory, events or alerts. The notifier aggregates emissions per environment and type, initially to one per second. The screen then queries the REST endpoint, which authorizes again and returns the current representation. SignalR reduces latency without duplicating the source of truth.

1
2
3
4
5
await hubContext.Clients
    .Group(ControlPlaneHub.GroupFor(environmentId.ToString("D")))
    .SendAsync("invalidated",
        new InvalidationNotification(environmentId, kind),
        CancellationToken.None);

📂 Source Code: SignalRControlPlaneNotifier.cs and AgentControlService.cs.

A group is not a queue, a history or a durable subscription. Its membership can disappear on disconnection or restart. Do not send large snapshots or interpret the absence of a notice as proof that nothing changed; when coming back, fetch the current state through the API.

The return of SendAsync does not confirm that the browser received or processed the invalidation either. If several changes are aggregated, the REST read still needs to converge on the most recent representation.

Authentication, authorization and trust boundaries

[Authorize] protects the entry point, but not the authorization of each resource. The principal is attached to the connection, and changes to roles or claims are not automatically revalidated on every invocation. Dokpod queries Keycloak when joining the group and reevaluates permissions in some sensitive long-running flows.

The browser uses a same-origin cookie through the BFF, which adds the Bearer only server-side. On a direct connection authenticated with a bearer token, the browser’s WebSocket and SSE APIs do not let you freely set Authorization; the client may place access_token in the query string. HTTPS protects the traffic, but URLs can show up in logs. If that option is unavoidable, restrict it to the Hub route and strip the query from logs. Dokpod’s relay avoids exposing the token to the browser or in the downstream URL.

Cookies also create CSRF risk. The BFF validates Origin, restricts origins and requires antiforgery on the negotiation POST. CORS controls cross-origin calls from the browser, but it neither authenticates users nor authorizes environments; same-origin does not remove the need to validate Origin for a cookie-based connection either.

Groups are not security boundaries: the server derives the resource and scope from the principal and fails closed when Keycloak denies or cannot decide. Limit messages, duration and concurrency, use TLS and avoid logging tokens, logs or terminal content.

⚠️ Warning: the JavaScript client may send bearer tokens in the query string for WebSockets/SSE because of browser API limitations. Dokpod’s BFF relay authenticates the browser by cookie and adds the Bearer only on the server-side hop to the API.

Reconnection, streams and events that can be lost

The JavaScript client does not reconnect by default. withAutomaticReconnect() uses delays of 0, 2, 10 and 30 seconds; after four failures, it stops and calls onclose. The policy does not cover failures of the initial start(), which need their own strategy. onreconnecting, onreconnected and onclose represent distinct states.

After reconnecting, the server sees a new connection. ConsoleRealtimeService keeps track of the observed environments and calls JoinEnvironmentAsync again. Updating only the indicator to “connected” leaves the interface without invalidations if the client does not restore its group membership.

1
2
3
4
5
6
7
8
connection.onreconnecting(() => this.status.set('connecting'));
connection.onreconnected(() => {
  const environmentIds = [...this.joined];
  this.joined.clear();
  this.status.set('connected');
  void this.watch(environmentIds);
});
connection.onclose(() => this.status.set('disconnected'));

📂 Source Code: console-realtime.service.ts.

Reconnection does not recover messages emitted during the outage. For inventory, do a REST refresh after reconnecting and use SignalR for subsequent changes. History, replay or acknowledgement require a durable sequence and explicit resumption; they are not Hub guarantees.

This strategy works best when the query is idempotent and returns a consistent view of the resource, instead of depending on reapplying every lost notification.

The Hub also offers long-running streams. StreamContainerLogs authorizes container:logs, lasts at most 15 minutes, propagates cancellation and reevaluates access every 60 seconds. OpenTerminal receives and returns streams, requires WebSocket and applies its own limits. These features carry content on demand and should not inherit the guarantees of an invalidation.

Scale and operations without promising what does not exist yet

A SignalR connection consumes a socket, memory and keep-alive traffic. Dokpod sets KeepAliveInterval to 15 seconds and ClientTimeoutInterval to 30, the ratio recommended by the ASP.NET Core documentation. These are project values: adjust them after measuring the proxy, latency and per-connection cost.

The proxy needs to forward the WebSocket upgrade, avoid buffering that delays SSE and align timeouts with the pings. In Dokpod, the browser goes through nginx and the BFF; a direct test against Kestrel does not validate that edge.

With multiple processes, the requests of a connection usually require affinity. There are documented exceptions, such as a single instance, Azure SignalR Service and WebSockets-only with negotiation skipped. A Redis backplane forwards messages between servers, but generally does not remove affinity or define ownership of agent sessions or command routing.

Azure SignalR Service and Redis are options with different topologies, costs and dependencies; Dokpod uses neither. The plan starts with a single API instance. Horizontal scaling requires a decision on ownership, fencing and durable command routing, driven by metrics and an ADR.

Watch current and closed connections, timeouts, authorization failures and latency up to the refresh. ASP.NET Core provides connection logs and metrics. Increase verbosity only during diagnostics: logs, HAR files and traces can contain sensitive payloads.

Practical Example: browser, BFF, Keycloak and invalidation

The flow below uses the Dokpod console: SignalR does not replace REST, nor is it the agent channel.

Dokpod SignalR flow with a Keycloak decision before the group and a REST query after the invalidation

  1. Angular registers handlers, requests antiforgery from the BFF and connects through /hubs/control-plane with the session cookie.
  2. The BFF validates the session and origin and adds the Bearer server-side on the hop to the API.
  3. JoinEnvironmentAsync validates the GUID and queries Keycloak for environment:read on that resource.
  4. Only an allowed decision adds the connection to the environment’s deterministic group.
  5. The API emits invalidated; Angular queries REST to get the current state.
  6. After reconnecting, the client rejoins environments and refreshes the state via REST; notices from the gap may have been lost.
1
2
3
4
5
6
7
8
builder.Services.AddSignalR(options =>
{
    options.KeepAliveInterval = TimeSpan.FromSeconds(15);
    options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
});

app.MapHub<ControlPlaneHub>("/hubs/control-plane")
    .RequireAuthorization();

📂 Source Code: ApiHost.cs. The current API also configures JWT authentication and a policy that requires an authenticated user.

ConsoleRealtimeService is the Angular client and SignalRControlPlaneNotifier publishes outside the Hub. Services notify changes to inventory, events and hosts; the subsequent read still uses an authorized HTTP route. Agents stay on the gRPC/mTLS channel.

The readiness report from 09/25 records an authorized browser connection and a denial for the environment without access; tests also cover protected routes, a stable group and an invalid identifier. That validates one slice, not load or release: the overall verdict remains NO-GO, with operations and distribution gates pending. docs/bff.md preserves a historical status from 09/13, prior to horizontal authorization; I considered the code and the most recent assessment without changing that record.

SignalR, gRPC, SSE and WebSockets: choose by flow

Use SignalR when the ASP.NET Core application benefits from a Hub, groups and supported clients. For one-way events, SSE can be smaller; to control a duplex channel, raw WebSockets; for services with an explicit contract and streaming, gRPC.

In every case, evaluate authentication, observability, failure semantics and infrastructure together with the shape of the traffic.

TechnologyCommon consumerFlowWhat it offersMain trade-off
SignalRBrowser and ASP.NET clientsMessages and streams in both directionsHub, groups, transport negotiation and .NET integrationPersistent connections, authorization and scale-out strategy
SSEBrowserServer → clientSimple one-way HTTP streamClient sends commands through another channel; proxy must not buffer the stream
WebSocketsBrowser or serviceDuplexLow-level persistent channelThe application manages framing, events, reconnection and routing
gRPCServices and agentsUnary or streamingProtobuf contracts, generated clients and HTTP/2Browser integration and infrastructure have their own requirements

In Dokpod, REST/OpenAPI serves queries, SignalR delivers invalidations to the browser and gRPC/mTLS connects the API to the agents. The real-time comparison and the gRPC in .NET 10 guide detail those choices.

Tips and Good Practices

  • Do not keep domain state in the Hub instance. Treat the Hub as an invocation boundary and delegate rules to application services. For state that must survive disconnection, persist it or rebuild it through a durable API.

  • Authorize before adding the connection to a group. Derive the resource and scope on the server, from the authenticated principal, and do not trust a group name supplied by the client. Reevaluate permissions in long-running flows when the policy requires revocation during the session.

  • Handle start() separately from automatic reconnection. Configure failure handling for the first connection and present the connecting, connected, reconnecting and disconnected states. The default withAutomaticReconnect() policy has finite attempts; it does not mean reconnecting forever.

  • Restore subscriptions and state after reconnecting. Rejoin groups, because the new connection does not inherit the entire previous membership. Also make a REST query to get the current state, which may have changed while the client was offline.

  • Send small invalidations, not large snapshots. The browser can update the projection by querying the authorized resource. For history, replay or acknowledged consumption, use a durable mechanism with a cursor and explicit semantics.

  • Keep the origin and the edge restricted. Prefer same-origin through the BFF when there are server-side tokens, validate Origin on cookie-based connections and do not open CORS with credentials to any origin. Configure nginx/the load balancer for the transport that is actually enabled.

  • Measure connections before adding infrastructure. Watch active connections, duration, timeouts, reconnections, limits and traffic per client. Affinity, a backplane or a managed service solve different problems; choose after you know the topology and the load.

Conclusion

SignalR offers a productive API for real-time communication in ASP.NET Core, but its abstractions do not eliminate security and operations decisions. A Hub organizes calls; a group targets messages; a connection can drop; and a notification does not become persistent state. When the application needs to recover reliable information, the query must go back to a durable source.

The Dokpod flow demonstrates this separation: the browser connects through the BFF, the API authorizes each environment with Keycloak and sends an invalidation, and Angular queries REST. Reconnection restores subscriptions; gRPC/mTLS remains the agents’ channel.

I would adopt SignalR when low latency, bidirectional communication or Hub integration make up for the cost of persistent connections. For a one-way stream, I would compare SSE; for controlled services, gRPC. The series covers REST, GraphQL, gRPC and SignalR according to the need.

Before treating this channel as critical infrastructure, I would test the journey through the real edge: allowed and denied authorization, API restart, connection loss, rejoining and reconciliation through the REST query. The result needs to be measured under the expected load, not inferred from a local Hub test.

Objective Summary

  • ASP.NET Core SignalR — real-time library with Hubs and negotiation between compatible WebSockets, SSE and Long Polling.
  • SignalR Hub — exposes methods and events; its instance should not hold durable domain state.
  • SignalR groups — target messages, but are not storage, a durable queue or authorization.
  • JavaScript reconnection — withAutomaticReconnect() retries at 0, 2, 10 and 30 seconds; start() failures require separate handling.
  • Per-environment authorization — JoinEnvironmentAsync queries Keycloak for environment:read before associating the connection.
  • Dokpod notifications — invalidated leads the browser to the REST API, the source of durable state.
  • SignalR scale — multiple instances require affinity or a compatible scale-out; Redis and Azure SignalR have different requirements.
  • Dokpod readiness — the allowed/denied SignalR validation does not change the overall release verdict: NO-GO.

Read Also

References