A previous article built real-time updates on one server-sent events stream, around one rule: a frame is a signal, never the data. The design held. What wore thin was the plumbing around it: a hand-written text/event-stream writer, a hand-rolled registry of connections, and a stream that had to be reopened every time the client wanted one more topic.

In this article, we will move that stream to a single SignalR hub and keep everything else: the topics, the authorizers, the outbox and the fan-out over RabbitMQ. We will cover the hub, the delivery behind it, the gateway, tokens that expire under a live connection, the Angular client, and how to test all three transports.

What changes, and what does not

The rule stays, and so does most of the code. A domain still publishes through IServerEventPublisher with a kind:value topic, an IServerEventTopicAuthorizer still decides who may follow each kind, and the publish still goes through the transactional outbox. What SignalR replaces is the transport:

Server-sent events SignalR
Endpoint GET /api/v1/events/stream?topic=… the hub /hubs/events
Transport text/event-stream, written by hand WebSockets, then server-sent events, then long polling
Choosing topics in the query string: a new topic reopens the stream follow / unfollow on the open connection
Local connections a registry of bounded channels SignalR groups, one per topic
An expired access token the stream outlives it the hub closes the connection

Two costs come with it. The browser needs the @microsoft/signalr client, and a connection is no longer one request: the negotiation and the transport must reach the same server, which matters once the API runs on several replicas.

One hub, groups as topics

A SignalR group is exactly what the old registry was: the connections of this process that follow a name. So a topic becomes a group, and the hub only decides who joins which:

Copy
public override async Task OnConnectedAsync()
{
    if (Subject is { } subject)
    {
        // Through the authorizer like any other follow, so there is one path into a group.
        await FollowAsync(ServerEventTopic.ForUser(new UserId(subject)).ToString());
    }

    await base.OnConnectedAsync();
}

[HubMethodName("follow")]
public async Task<bool> FollowAsync(string topic)
{
    if (Subject is not { } subject
        || !ServerEventTopic.TryParse(topic, out var parsed)
        || parsed is null)
    {
        return false;
    }

    // No authorizer for a kind means nobody has decided who may read it: a refusal, not an omission to wave
    // through.
    var authorizer = topicAuthorizers.FirstOrDefault(x => string.Equals(x.Kind, parsed.Kind, StringComparison.Ordinal));

    if (authorizer is null || !await authorizer.IsAllowedAsync(new UserId(subject), parsed, Context.ConnectionAborted))
    {
        return false;
    }

    await Groups.AddToGroupAsync(Context.ConnectionId, parsed.ToString(), Context.ConnectionAborted);

    return true;
}
  • Every connection follows its own user:{sub} on connect, as the stream did when no topic was named, so the notification centre never has to know its own id. It goes through the same FollowAsync, so there is one way into a group.
  • A refusal is false, not an exception. A topic that is malformed, of a kind with no authorizer, or not the caller's is an expected answer. The client can then tell a refusal (false) from a connection that dropped while it asked (a rejected promise), and treat them differently.
  • The user comes from the connection's own principal, Context.User, never from an argument and never from a service that reads IHttpContextAccessor, which SignalR does not promise inside a hub method.
  • The authorizer is asked on every follow. Groups do not survive a reconnect, so a client follows again each time, and access revoked in between is refused.

The server calls one method on the browser, declared on a strongly typed client interface: Task ReceiveServerEvent(string name, string data). The interface must be public, because SignalR implements it at runtime. data is the JSON the producer already serialized, so the hub never learns a feature's payload.

Mapping the hub

All three transports stay on, in SignalR's order of preference: the fallbacks are the reason to choose SignalR over a raw socket.

Copy
public HubEndpointConventionBuilder MapServerEventsHub()
    => endpoints.MapHub<ServerEventsHub>(ServerEventsHub.Path, options =>
    {
        // All three, in SignalR's order of preference: the fallbacks are the reason to use SignalR at all.
        options.Transports = HttpTransportType.WebSockets
                             | HttpTransportType.ServerSentEvents
                             | HttpTransportType.LongPolling;
        options.LongPolling.PollTimeout = LongPollTimeout;

        // A WebSocket outlives the access token it was opened with otherwise. Closed when the token expires,
        // the client comes back through the gateway, which refreshes the token — or refuses a session that
        // has since been signed out.
        options.CloseOnAuthenticationExpiration = true;
    });

The other options are set explicitly rather than left to defaults that nobody remembers:

Setting Value Why
MaximumReceiveMessageSize 4 KB A client only ever sends a topic name; the 32 KB default is room for abuse
KeepAliveInterval 15 s Well under the 100 seconds a YARP hop allows an idle request
ClientTimeoutInterval 30 s Twice the keep-alive, as SignalR recommends
LongPolling.PollTimeout 90 s Under the same 100 seconds, so the API answers a poll before the proxy drops it
EnableDetailedErrors false Hub exceptions do not reach the client

The hub has its own authorization policy too. The application's default one asks for a write scope on any POST, and SignalR's negotiation and long polling's sends are POSTs that change nothing.

Several replicas: keep the bus, skip the backplane

Groups live in one process, like the registry did. SignalR's usual answer is a backplane, for instance Redis, which relays every group send to every server. The code base already had something that reaches every replica: the instance-scoped consumer, with one RabbitMQ queue per process. So only its last step changes. The consumer, in the real-time adapter, calls a small interface:

Copy
public interface IServerEventDelivery
{
    Task DeliverAsync(ServerEventTopic topic, ServerEvent @event, CancellationToken cancellationToken = default);
}

And the API, which hosts the hub, implements it with IHubContext:

Copy
internal sealed class SignalRServerEventDelivery(
    IHubContext<ServerEventsHub, IServerEventsClient> hubContext) : IServerEventDelivery
{
    public Task DeliverAsync(ServerEventTopic topic, ServerEvent @event, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(topic);
        ArgumentNullException.ThrowIfNull(@event);

        return hubContext.Clients
            .Group(topic.ToString())
            .ReceiveServerEvent(@event.Name, @event.Data);
    }
}

The adapter never references SignalR, and nothing references the hub but the API. Keeping the bus rather than adding a backplane has three reasons:

  • The outbox. The publish goes through the transactional outbox, so a signal never announces a row that is not committed yet. A backplane is called from inside the use case, outside any outbox.
  • No new hard dependency. Redis is a cache here: when it is down, reads go to the database. A backplane cannot degrade that way.
  • Nothing to gain. A backplane is for addressing one connection or one user wherever they are connected. This design only ever sends to a topic, and a topic is a group.

IServerEventDelivery sits in the adapter itself rather than in its .Abstractions project, which the domains reference: a domain publishes through the outbox and should not be able to deliver locally.

Through the gateway

The browser reaches the hub through the same YARP gateway as everything else (see the BFF article): it holds the session cookie and attaches the access token to the negotiation, to the WebSocket's upgrade request and to every long poll. No token reaches JavaScript, and none ends up in a query string, which is where the SignalR documentation puts it when the browser has to send it itself.

The gateway asks for an X-CSRF: 1 header on every call, and a browser WebSocket cannot send a custom header, just as EventSource could not. So the hub's route is exempted:

Copy
public static class ServerEventsHubRoute
{
    public const string Path = "/hubs/events";

    extension(IEndpointRouteBuilder endpoints)
    {
        public IEndpointConventionBuilder MapServerEventsHub(string backendUrl)
            => endpoints.MapRemoteApi(Path, backendUrl, requireAntiforgeryHeader: false);
    }
}

The exemption is covered three ways:

  • The session cookie is SameSite=Strict, so a page on another site cannot make the browser send it, including on a WebSocket handshake.
  • CORS does not apply to a WebSocket handshake, so the gateway refuses a request to /hubs/events whose Origin is not its own. That is the check a cross-site WebSocket hijacking would otherwise slip past:
Copy
app.UseSameOriginCheck(blouppyConfiguration.GatewayUrl, [McpRoute.Path, ServerEventsHubRoute.Path]);
  • The hub changes nothing: it lets a connection follow the topics its authorizers allow, and a frame carries no data.

The Content Security Policy keeps connect-src 'self'. CSP Level 3 makes 'self' match wss: on the same host. Adding a bare wss: would let an injected script open a socket to any host. A browser too old for the rule falls back to SignalR's server-sent events or long polling, plain https: to the same origin.

A token that expires under a live connection

A WebSocket is authenticated once, at the upgrade, and the old stream happily outlived the access token it was opened with. With CloseOnAuthenticationExpiration, SignalR closes the connection when that token expires. The client reconnects through the gateway, which refreshes the token, and follows its topics again: each follow is asked of its authorizer anew, so someone removed from an organization stops hearing it at the latest one token lifetime later.

If the session itself is gone, the gateway answers the negotiation with a 401, and the client must stop trying. That is the part of the client with a trap in it.

In Angular: the same service, a different engine

ServerEventsService kept its public API (listen(name, listener), follow(topic), onRecovered(listener), a status signal), so NotificationService and the services that keep lists did not change. Underneath, a few things are new.

The client library is loaded on the first listener. Imported eagerly, @microsoft/signalr took the application's initial bundle from 813 kB to 868 kB, past its 850 kB budget. A dynamic import('@microsoft/signalr') in the function that builds the connection puts it in its own chunk, and a signed-out page never loads it. The service imports only types from the library, and compares the connection's state to 'Connected' rather than to the enum's value, so nothing pulls it back in.

Following is a call, not a reconnect. follow is counted per caller and invokes follow on the hub when the first caller asks. After every reconnection, the service follows each topic again, then tells its listeners they may have missed something:

Copy
/** Up for the first time, or again: follows every topic, then says so. */
private async onConnected(): Promise<void> {
  const connection = this._connection;

  await Promise.all([...this._topics.keys()].map(topic => this.sendFollow(topic)));

  if (connection !== this._connection) {
    return;
  }

  this._hasConnected = true;
  this._status.set('open');

  if (this._isRecovering) {
    this._isRecovering = false;
    this._recoveryListeners.forEach(listener => listener());
  }
}

A topic the hub answers false for is forgotten, since asking again on every reconnect would only be refused again. A follow lost with a dropping connection is kept and sent again on the next one.

It reconnects forever, except on a 401. The automatic reconnection waits 0, 2, 5, 10, then 30 seconds between attempts and never gives up, because a connection that comes back late costs nothing but a re-read. A failed first start, and a connection the server closed (an expired token), are retried by the service on the same schedule, since SignalR's automatic reconnection only covers a transport that dropped. A 401 means the session is gone, and here is the trap: SignalR does not report a 401 the same way everywhere. During a reconnection, the retry reason is an HttpError carrying statusCode. At negotiation, the library catches that HttpError and rejects with a FailedToNegotiateWithServerError that keeps only the message. An instanceof HttpError check misses that path, and the client keeps knocking at a closed door every thirty seconds. So the service reads both forms:

Copy
/**
 * A 401 from the gateway: no session. SignalR reports it as an `HttpError`
 * carrying the status, except at negotiation, where it wraps it in an error
 * that keeps only the message.
 */
function isUnauthorized(error: unknown): boolean {
  if (!(error instanceof Error)) {
    return false;
  }

  return (error as Error & { statusCode?: number }).statusCode === 401 || error.message.includes("Status code '401'");
}

It closes at once on sign-out. The hub would close the connection when the token expires, but nothing should arrive for someone who has just left, so AuthService.signOut() calls disconnect() before redirecting to the gateway's logout. The tab-hidden rule of the old stream stays, and coming back online starts a fresh connection rather than waiting out the rest of a thirty-second back-off.

Scaling the API out

The fan-out already reaches every replica. What does not is the connection itself: SignalR's negotiation hands out a connection token, and the WebSocket upgrade, each server-sent events stream and each long poll must land on the replica that issued it. With one API instance there is nothing to pin. With several, the options are:

  1. Affinity at the gateway: move the hub's route to a YARP route and cluster that lists each API replica, with session affinity on the cluster. It is configuration in the gateway, nothing changes in the API, and the rest of /api stays round-robin.
  2. Sticky sessions at a load balancer in front of the API, on /hubs/events only.
  3. WebSockets only, negotiation skipped: one request, so nothing to pin, but no fallback for the networks that do not carry a WebSocket. That gives up the reason to use SignalR in the first place.

The first one is the one to take. Until then, the deployment guide says plainly that the REST API scales out and the hub does not yet.

Testing every transport

Each layer gets the test that can see it:

  • The hub, in unit tests, with a mocked HubCallerContext and IGroupManager: the own topic joined through its authorizer, a follow allowed, refused, of an unknown kind or malformed, and an unfollow of the own topic ignored.
  • The whole API, in integration tests, with the real .NET SignalR client talking to the in-memory test server over WebSockets and long polling. The test server gives both the HTTP handler and a WebSocket client:
Copy
return new HubConnectionBuilder()
    .WithUrl(new Uri(server.BaseAddress, "hubs/events"), options =>
    {
        options.Transports = transport;
        options.HttpMessageHandlerFactory = _ => server.CreateHandler();
        options.WebSocketFactory = (context, cancellationToken) =>
            new ValueTask<WebSocket>(server.CreateWebSocketClient().ConnectAsync(context.Uri, cancellationToken));
    })
    .Build();

A workspace renamed through the API arrives as data.changed on the organization's topic, through the outbox, the in-memory bus, the consumer and the group.

  • The whole graph, end to end, through the real gateway and RabbitMQ: a connection over each of the three transports follows its own topic and is refused another user's, a rename is signalled over WebSockets and long polling, and a connection without a session is refused with a 401. A follow answered over server-sent events or long polling also proves that direction gets through the proxy unbuffered.
  • The Angular service, with Vitest and a fake HubConnection injected through the token that builds the connection: re-follow before recovery, a refusal forgotten, a 401 at negotiation and at reconnection leaving the service idle, and a disconnect on sign-out.
  • The visual gallery, where Playwright's routeWebSocket answers the negotiation, the JSON handshake and every follow. The real client then runs behind every screenshot, and one scene pushes notifications.changed and checks that the bell's badge counts one more.

Conclusion

SignalR replaced the parts of the server-sent events stream that were plumbing: the wire format, the connection registry, the reconnection, and a stream that reopened for every new topic. The parts that were design stayed: a frame only says that something changed, a topic is opaque to the transport, one authorizer per kind fails closed, and the bus carries every signal to every replica after the commit. A few details decide whether it holds in production: a refusal that is an answer rather than an exception, a token that cannot outlive its session, a 401 recognized in both of its forms, and affinity on the hub's route before the API gets a second replica.

This is how real-time updates work in Blouppy Starter today. The real-time page of its documentation summarizes the design.

References