📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does SignalR work in ASP.NET Core? Explain hubs, transports and fallback, groups, strongly typed hubs and how you authenticate connections.

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.

Intermediate Theory Intermediate aspnet-core authentication real-time signalr websockets

🎯 Key points

  • A hub is transient: a new instance per invocation, so no state in fields; use Context.ConnectionId, Context.User or an external store
  • Negotiate offers transports and the client tries WebSockets, then SSE, then long polling; skipping negotiation is only possible when the client forces WebSockets
  • Clients.All, Caller, Others, Group, User; groups live in memory and are lost on reconnect, so re-join in OnConnectedAsync
  • Strongly typed hubs: Hub<IClient> removes magic method-name strings
  • IHubContext<THub, TClient> sends from outside a hub, for example from a BackgroundService or endpoint
  • Auth: [Authorize] on the hub or methods; because browsers can't set the Authorization header on WebSockets or EventSource, the token is sent as access_token in the query string and read in JwtBearerEvents.OnMessageReceived
  • Context.UserIdentifier comes from the NameIdentifier claim (IUserIdProvider) and drives Clients.User
  • Protocols: JSON by default, MessagePack for smaller binary payloads; per-server connection state means scale-out needs a backplane

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"SignalR is an RPC layer over persistent connections. I define a hub, a class deriving from Hub or Hub<T>, and map it with app.MapHub<NotificationsHub>("/hubs/notifications"). Clients call its public methods, and the server calls methods on clients through Clients. One important detail is that hubs are transient: a new instance is created for every invocation. So you never keep state in fields; you use Context.ConnectionId, Context.User, or an external store.

When a client connects, it posts to /negotiate and 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 use Clients.Caller, Clients.Group("region-vic"), or Clients.User(userId). User maps to every connection of that authenticated user, using the NameIdentifier claim 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 in OnConnectedAsync from the user's claims. I always use strongly typed hubs: Hub<INotificationClient> turns Clients.User(id).JobAssigned(msg) into a compile-time-checked call instead of SendAsync("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 an Authorization header on WebSockets or EventSource, so the JavaScript client sends the token as access_token in the query string. On the server you copy it into the context in JwtBearerEvents.OnMessageReceived for the hub path. The mistake I see is putting business logic straight into hubs. I keep hubs thin and push from application services through IHubContext<THub, TClient>."


The pieces

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

Targeting clients

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

Authentication checklist

  • app.UseAuthentication() and app.UseAuthorization() before MapHub.
  • [Authorize] on the hub, policies on sensitive methods.
  • Read 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).
  • Set CloseOnAuthenticationExpiration = true (.NET 8+) if a connection must end when its token expires.
  • Scrub access_token from request logs.

Production example

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.

🔍 What the interviewer is checking

Checks practical SignalR knowledge: hub lifetime, transports, targeting, typed hubs and how authentication really works for browser connections.

Green flags

  • Knows hubs are transient and keeps state elsewhere
  • Explains negotiate and the WebSockets → SSE → long polling fallback
  • Knows groups are lost on reconnect and re-joins them
  • Explains the access_token query string and OnMessageReceived
  • Uses IHubContext to push from outside the hub

Red flags

  • Keeps per-user state in hub fields
  • Thinks SignalR guarantees delivery to offline clients
  • Can't explain how a browser authenticates a WebSocket connection

📚 Learn in depth

1. The layers

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

2. Negotiation and connection start

  1. The client sends POST /hubs/notifications/negotiate?negotiateVersion=1.
  2. The server answers with a connectionToken and the transports it supports.
  3. The client opens the transport, for example wss://.../hubs/notifications?id=<token>.
  4. A handshake message chooses the protocol ({"protocol":"json","version":1}).
  5. Both sides exchange ping messages: the server sends one every 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.

3. Hub lifetime and DI

A hub is resolved from DI for each connect, disconnect and method invocation, then disposed. That is why:

  • Fields don't survive between calls.
  • You can inject scoped services (a scope is created per invocation).
  • 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>()).

4. Groups and users internally

The default HubLifetimeManager keeps an in-memory map of group name to connection ids per server. That explains two behaviours:

  • Restart the server and the groups are gone. Reconnecting clients get a new connection id and must re-join.
  • With two servers and no backplane, 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.

5. Authentication flow

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.

Try it yourself

  1. Build a hub with Hub<IChatClient>, connect two browser tabs, and send to Clients.Others.
  2. In DevTools (Network → WS), inspect the handshake and the JSON frames, including the {"type":6} pings.
  3. Restrict the client to HttpTransportType.LongPolling and watch the POST/GET traffic replace the WebSocket.
  4. Add [Authorize] and the OnMessageReceived handler, then connect with and without a token and compare the 401.
  5. Restart the server while clients are connected and confirm groups are lost until OnConnectedAsync re-joins them.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Storing state in hub fields. Why it is wrong: Hubs are transient, created for every invocation, so the field is empty next time. Instead: Keep state in a singleton service, cache or database keyed by connection or user id.
  • Mistake: Assuming group membership survives a reconnect. Why it is wrong: Groups are in-memory per connection id; a reconnect gives a new id. Instead: Re-join groups in OnConnectedAsync from claims or stored subscriptions.
  • Mistake: Using SendAsync("methodName", ...) everywhere. Why it is wrong: A typo or a rename silently breaks clients. Instead: Use Hub<TClient> and IHubContext<THub, TClient>.
  • Mistake: Expecting the 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.
  • Mistake: Doing slow work or fire-and-forget tasks inside hub methods. Why it is wrong: A slow hub method blocks further messages from that client (one invocation at a time by default, MaximumParallelInvocationsPerClient = 1), and a disposed hub can't be used later. Instead: Queue the work and push the result through IHubContext.
  • Mistake: Assuming an open connection is re-authorised on every message. Why it is wrong: The user is set when the connection starts; an expired or revoked token keeps working. Instead: Use short-lived tokens with CloseOnAuthenticationExpiration, and check authorisation for sensitive actions.
  • Mistake: Running several instances without a backplane. Why it is wrong: Messages only reach clients connected to the same instance. Instead: Use Azure SignalR Service or a Redis backplane, with sticky sessions where required.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions injecting IHubContext into a hosted service. Why: Checks understanding of the Generic Host and service lifetimes.
    How to answer

    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.

  2. When: Candidate mentions running SignalR behind a load balancer. Why: Checks understanding of sticky sessions, idle timeouts and connection draining.
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

  3. When: Candidate mentions running SignalR on more than one server. Why: Checks whether they understand that groups and connections are per server and how backplanes fix it.
    How to answer

    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.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me