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

📚 Interview question

Your SignalR app works on one server, but after scaling out to four instances some users stop receiving messages and others get stuck reconnecting. How do you scale SignalR across instances? Explain sticky sessions, the Redis backplane, Azure SignalR Service and connection limits, and how you would design for 100,000 concurrent connections.

Covers scaling ASP.NET Core SignalR horizontally: why connections and groups are per server, sticky sessions and when they are needed, the Redis backplane, Azure SignalR Service (default and serverless modes, units), connection and message limits, and capacity planning.

Senior Architecture Advanced aspnet-core azure-signalr-service load-balancing redis scalability signalr

🎯 Key points

  • Connections and groups live in memory on one server; without a backplane Clients.Group/User only reaches local connections
  • Sticky sessions are required when self-hosting unless every client uses WebSockets with SkipNegotiation; they also pin load unevenly and drop clients when their instance dies
  • Redis backplane (AddStackExchangeRedis) publishes every message to every server; run Redis with replication or a managed HA tier, and remember pub/sub does not buffer messages during a failover
  • Azure SignalR Service holds the client connections; the app keeps a few server connections, no sticky sessions needed at the app
  • Azure SignalR Standard: about 1,000 concurrent connections per unit plus message quotas and outbound data costs; plan units from peak connections and fan-out
  • Capacity drivers: concurrent connections, messages per second times fan-out, message size, reconnect storms on deploy
  • Graceful shutdown, jittered reconnects and staggered rollouts prevent all clients reconnecting at once
  • SignalR is not durable: missed messages need a store and catch-up on reconnect

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The root cause is that SignalR state is per process. The default HubLifetimeManager keeps connection ids and group memberships in memory, so with four instances each knows about a quarter of the users. Two things break. Messages sent to a group or user only reach the local connections, which is the 'some users don't get messages' symptom. And if a client falls back to SSE or long polling, its negotiate call and its later requests may land on different instances, which gives a 404 on the connection id and the 'stuck reconnecting' symptom. That second one is why self-hosted SignalR needs sticky sessions unless every client is WebSockets-only with negotiation skipped.

For example, at [company] we had [a dispatch dashboard] on [three App Service instances]. We first added the Redis backplane: one line, AddStackExchangeRedis, and every message is published to a Redis channel that all servers subscribe to. That fixed delivery, but every server now processes every message, so fan-out cost grows with instance count, and Redis became a single point of failure. When we grew to about [40,000] connections we moved to Azure SignalR Service. The app connects to the service with a few server connections, clients are redirected there by negotiate, and we no longer needed ARR affinity. [Deployment disconnects dropped to near zero and we cut instance count from X to Y.]

For 100,000 concurrent connections I would design around three numbers: peak concurrent connections, messages per second multiplied by average fan-out, and the reconnect rate during deployments. On Azure SignalR Standard that is roughly 100 units for connections, then I would check the message quota. The mistake I see is sizing by HTTP requests per second. With SignalR you size by connections and fan-out."


The options

Option How it works Sticky sessions? Limits and risks
Single server All state in memory No One instance's sockets and memory; no redundancy
Redis backplane Every server publishes to Redis pub/sub; all servers receive every message Yes, unless WebSockets-only with SkipNegotiation Every server processes every message; Redis throughput and availability; pub/sub is fire-and-forget
Azure SignalR Service (default mode) Clients connect to the service; your hubs still run in your app over server connections No (the service handles routing) Billed per unit; about 1,000 concurrent connections per Standard unit; message quotas
Azure SignalR Service (serverless) No hub server; Azure Functions or REST API push messages No No hub methods in your app; upstream webhooks for client messages
Orleans or custom fan-out Your own routing layer Depends Only when you have very specific needs

Capacity planning for 100,000 connections

Factor Question to answer Example
Concurrent connections Peak, not daily average 100k at the 8:30 am peak → ~100 Standard units, or Premium
Fan-out Messages per second times recipients 50 broadcasts/s to 2,000-user groups = 100k deliveries/s
Message size Billing counts messages in 2 KB chunks Trim payloads; send ids and let clients fetch details
Reconnect storm What happens when 100k clients reconnect in 10 s? Jittered withAutomaticReconnect delays, staggered rollouts
Region Users in Australia Azure SignalR in Australia East with the app in the same region

Production example

Moving a [dispatch] dashboard from a Redis backplane on [four] instances to Azure SignalR Service removed ARR affinity and let us scale the app on CPU instead of connections. Instance count dropped from [8 to 3], and the p95 delivery latency of broadcasts went from [about 900 ms to under 200 ms] because servers no longer processed every message.

🔍 What the interviewer is checking

Checks whether the candidate understands why SignalR state is per server, can explain sticky sessions and backplanes precisely, and can size a large deployment by connections and fan-out.

Green flags

  • Explains in-memory groups and connections per server as the root cause
  • Knows exactly when sticky sessions are needed and how to avoid them
  • Contrasts the Redis backplane (every server gets every message) with Azure SignalR Service (connections offloaded)
  • Sizes by peak connections, fan-out and message size, and plans for reconnect storms
  • Mentions that SignalR isn't durable delivery

Red flags

  • "Just add more instances" without a backplane
  • Thinks a load balancer alone solves it
  • No numbers or no idea how Azure SignalR is billed

📚 Learn in depth

1. Why it breaks when you add a second server

             Load balancer (round robin)
             /                \
   Server A                   Server B
   connections: u1, u2        connections: u3, u4
   group "vic": u1            group "vic": u3

Server A: Clients.Group("vic").Send(...)  ->  only u1 receives it. u3 never does.

The default DefaultHubLifetimeManager<THub> stores everything in local dictionaries. Nothing is shared.

2. Why sticky sessions are needed

Negotiate creates a connection id on one server. With WebSockets, the next request upgrades and stays on one TCP connection, so it's fine if negotiate and the upgrade reach the same server. With SSE, every client-to-server message is a separate POST, and with long polling every poll is a new request. Those must all reach the server that owns the connection id; otherwise you get 404 No Connection with that ID. Hence ARR affinity on App Service, sessionAffinity cookies on ingress, or WebSockets-only with skipNegotiation: true.

3. The Redis backplane internally

Server A --PUBLISH "hub:group:vic"--> Redis <--SUBSCRIBE-- Server B, Server C, Server D

RedisHubLifetimeManager turns every send into a Redis publish, and each server delivers to its local members. Consequences:

  • Every server receives every broadcast, so the cost per message grows with instance count.
  • Redis pub/sub is fire-and-forget: if Redis blips, messages are lost, and servers reconnect to Redis.
  • Use a dedicated Redis (not your cache), in the same region, and set a ChannelPrefix if several apps share one.

4. Azure SignalR Service internally

browser --negotiate--> your app --returns service URL + access token--> browser
browser ==WebSocket==> Azure SignalR Service <==server connections (5 per hub per server by default)== your app

Your hub code doesn't change: AddSignalR().AddAzureSignalR(). The service multiplexes thousands of client connections over a few server connections, routes group and user messages itself, and handles the client sockets. In serverless mode there is no hub server: you push through the REST API or Azure Functions bindings.

Units: in the Standard tier, one unit gives about 1,000 concurrent connections and a daily message quota, and you can scale up to 100 units per instance (Premium adds autoscale and higher limits). Check current limits in the Azure docs, because they change.

5. Reconnect storms

When an instance stops, every client connected to it reconnects at once. With 25,000 clients per instance, that is 25,000 negotiate requests, token validations and group re-joins in a few seconds. Mitigations: jittered retry delays in withAutomaticReconnect([0, 2000, 10000, 30000]) plus random offsets, rolling deployments with maxSurge, and with Azure SignalR Service, graceful shutdown (GracefulShutdown.Mode = MigrateClients) to move clients to other servers.

Try it yourself

  1. Run two instances of a SignalR app behind nginx with round robin and no affinity. Force long polling and watch the 404s, then turn on ip_hash and see them stop.
  2. Add the Redis backplane, broadcast to a group from instance 1, and confirm clients on instance 2 receive it. Watch MONITOR in redis-cli.
  3. Use crankier (the SignalR load tool in the aspnetcore repo) or k6's WebSocket support to open 20,000 connections and record memory per connection with dotnet-counters.
  4. Point the same app at a free Azure SignalR instance and compare server memory and CPU with the self-hosted run.
  5. Kill one instance under load and graph the reconnect rate, with and without jitter.

💻 Code

The same hub, three ways to host it. Hub code doesn't change; only registration does.

// Program.cs (.NET 10)
using Microsoft.AspNetCore.SignalR;

var builder = WebApplication.CreateBuilder(args);

var signalR = builder.Services.AddSignalR();

switch (builder.Configuration["SignalR:Mode"])
{
    case "Redis":
        // Every server publishes every message to Redis; all servers deliver to local members.
        // Still needs sticky sessions unless every client is WebSockets-only.
        signalR.AddStackExchangeRedis(builder.Configuration.GetConnectionString("SignalRRedis")!, o =>
            o.Configuration.ChannelPrefix = StackExchange.Redis.RedisChannel.Literal("dispatch"));
        break;

    case "Azure":
        // Clients connect to Azure SignalR Service; the app keeps a few server connections.
        // Connection string comes from Key Vault or managed identity config, never appsettings.json.
        signalR.AddAzureSignalR(o =>
        {
            o.ConnectionString = builder.Configuration["Azure:SignalR:ConnectionString"];
            o.GracefulShutdown.Mode = Microsoft.Azure.SignalR.GracefulShutdownMode.MigrateClients;
            o.GracefulShutdown.Timeout = TimeSpan.FromSeconds(20);
        });
        break;
}

var app = builder.Build();
app.MapHub<DispatchHub>("/hubs/dispatch");
app.Run();

public interface IDispatchClient
{
    Task JobUpdated(JobUpdate update);
}

public sealed record JobUpdate(int JobId, string Status); // ids and status only: keep messages small

public sealed class DispatchHub : Hub<IDispatchClient>
{
    public override async Task OnConnectedAsync()
    {
        // Re-join groups on every (re)connect: membership is not persisted.
        if (Context.User?.FindFirst("depot")?.Value is { } depot)
            await Groups.AddToGroupAsync(Context.ConnectionId, $"depot-{depot}");
        await base.OnConnectedAsync();
    }
}
// Client: jittered reconnect so 25,000 clients don't all retry at the same millisecond.
const connection = new signalR.HubConnectionBuilder()
  .withUrl("/hubs/dispatch", { accessTokenFactory: getToken })
  .withAutomaticReconnect({
    nextRetryDelayInMilliseconds: ctx =>
      ctx.elapsedMilliseconds > 120000 ? null : Math.min(30000, 1000 * 2 ** ctx.previousRetryCount) + Math.random() * 3000
  })
  .build();
# Kubernetes ingress-nginx: cookie affinity for a self-hosted Redis-backplane setup
metadata:
  annotations:
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "signalr-affinity"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"

⚠ Common mistakes

  • Mistake: Scaling out without a backplane or Azure SignalR Service. Why it is wrong: Group and user messages only reach clients on the same instance. Instead: Add the Redis backplane or move to Azure SignalR Service before the second instance.
  • Mistake: Turning off ARR affinity or session affinity for a self-hosted SignalR app. Why it is wrong: SSE and long-polling requests land on servers that don't know the connection id and fail with 404. Instead: Keep affinity, or force WebSockets with SkipNegotiation, or use Azure SignalR Service.
  • Mistake: Relying on sticky sessions as if they were free. Why it is wrong: Affinity pins long-lived clients to old instances, so new instances get little load after a scale-out, and every client on a failed instance reconnects at once. Instead: Prefer WebSockets-only or Azure SignalR Service, and plan reconnects as a normal event.
  • Mistake: Sharing the application's cache Redis as the backplane, on a single node. Why it is wrong: Broadcast traffic competes with cache traffic, and a single node or an unplanned failover takes out both; pub/sub messages published during the failover are lost. Instead: Use a dedicated, replicated Redis (for example a zone-redundant Azure Managed Redis tier) in the same region, with a channel prefix, and let clients catch up from a store after reconnect.
  • Mistake: Not monitoring the backplane. Why it is wrong: High message rates show up as rising Redis CPU, network bandwidth and pub/sub latency long before messages are dropped. Instead: Alert on Redis server load, connected clients and end-to-end delivery latency.
  • Mistake: Sizing by requests per second. Why it is wrong: SignalR cost is driven by concurrent connections and fan-out, not request rate. Instead: Model peak connections, messages per second times recipients, and message size.
  • Mistake: Sending large payloads to large groups. Why it is wrong: A 50 KB message to 5,000 users is 250 MB of egress and, on Azure SignalR, many billed message units. Instead: Send small notifications with ids and let clients fetch details.
  • Mistake: Treating SignalR as guaranteed delivery. Why it is wrong: Backplane pub/sub and client connections drop messages during failures. Instead: Persist important events and let clients catch up on reconnect.
  • Mistake: Ignoring reconnect storms on deployment. Why it is wrong: Every client on a stopping instance reconnects at once, spiking CPU and token validation. Instead: Jittered retries, rolling deployments and graceful client migration.

🏛 Senior insight: trade-offs

Self-hosting with a Redis backplane is fine up to a few thousand connections per instance and modest fan-out, provided Redis is replicated and monitored. Beyond that, Azure SignalR Service usually wins on total cost of ownership: you stop scaling your app for sockets and scale it for CPU, and sticky sessions disappear. The service has its own limits (units, message quotas, a cap per instance) and its bill includes units, messages beyond the quota and outbound data transfer, so put the numbers in a spreadsheet, not just the architecture diagram.

Option When it fits Cost When not to
Single instance Internal tools, under ~5k connections, downtime acceptable Cheapest Anything needing redundancy
Redis backplane A few instances, modest fan-out, data must stay in your network HA Redis plus sticky sessions and uneven load High fan-out across many instances
Azure SignalR Service Tens of thousands of connections, Azure-hosted, want no affinity Units per day, extra messages, egress Strict on-premises requirements, or no Azure
Serverless SignalR Push-only notifications from Functions Pay per unit, no hub server You need hub methods with app logic
Sticky sessions Benefit Cost
On (self-hosted) Works with every transport Uneven load after scale-out, mass reconnect when an instance fails, harder blue-green deployments
Off (WebSockets-only or Azure SignalR) Even load, stateless app tier Clients behind proxies that block WebSockets can't connect when self-hosted

Also ask whether you need SignalR at all for the hot path. Broadcasting a price feed to 100,000 read-only viewers may be cheaper as SSE through a CDN or Azure Web PubSub. Keep SignalR where you need two-way interaction.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions groups or Clients.User without explaining how they work. Why: Checks the fundamentals behind the scaling problem: hubs, groups and users.
    How to 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.

  2. When: Candidate mentions sticky sessions or ARR affinity. Why: Checks load balancer knowledge: layer 7 affinity, 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 reconnect storms during deployment. Why: Checks graceful shutdown and readiness probes during rollouts.
    How to answer

    A burst of 502s on every rollout is almost always a shutdown or start-up race, not a code bug. On termination, Kubernetes sends SIGTERM to the container and removes the pod from the Service endpoints at the same time, so the ingress keeps sending requests for a few seconds to a process that is closing. I fix it in layers, with numbers that must add up: a preStop sleep (about 10 s) so routing updates first; HostOptions.ShutdownTimeout sized from the measured p99.9 request duration (say 15 s) so in-flight requests drain; and terminationGracePeriodSeconds larger than both together (35 s). Then readiness probes that only pass when the app is warm and fail once ApplicationStopping fires, separate from liveness, plus maxUnavailable: 0. I also check keep-alive timeouts: if Kestrel closes idle connections before the proxy does, the proxy reuses a dead connection and returns 502. The trade-off is slightly slower deployments for zero dropped requests.

🛠 Real-world problems: how you handle them

Missed broadcasts and reconnect loops after scaling SignalR to four instances
Situation
A [dispatch] web app on [Azure App Service] pushed job updates to [about 12,000] browsers through SignalR. To handle a seasonal peak, the team scaled from one to four instances and turned off ARR affinity to "spread load evenly".
Signals
Support tickets said some dispatchers never saw new jobs until they refreshed. Browser consoles showed `404 No Connection with that ID` and repeated reconnects for users behind a corporate proxy that blocked WebSockets. Application Insights showed a spike in `/negotiate` calls and failed `/hubs/dispatch` POSTs.
Investigation
Grouped failed requests by instance in Application Insights and saw the negotiate and the follow-up POSTs landing on different instances. Confirmed the affected users were on the SSE or long-polling transport by enabling client logging (`configureLogging(signalR.LogLevel.Information)`). For the missed messages, logged the instance name in the send path and confirmed that broadcasts only reached clients on the sending instance: there was no backplane.
Resolution
Immediate: turned ARR affinity back on and scaled back to one instance during the business day. Real fix: moved the hub to Azure SignalR Service in Australia East (`AddAzureSignalR`), which removed the need for affinity and handled fan-out across instances, sized at [15] units for peak plus headroom. Added `GracefulShutdown.Mode = MigrateClients` and jittered client reconnects.
Prevention
An ADR documenting the SignalR hosting decision and the unit sizing. A pre-production load test with crankier at 1.5x peak connections across multiple instances. Alerts on Azure SignalR connection count against unit capacity, and on the client reconnect rate. A deployment checklist item: "scale-out changes require a SignalR review".

How to tell it (STAR)

**S:** Our [dispatch] app pushed job updates to about [12,000] browsers. When we scaled from one to four instances for [the seasonal peak], dispatchers started missing jobs and some got stuck reconnecting. **T:** I had to find out why within [a day], because missed jobs meant [late deliveries]. **A:** I grouped the failures by instance in Application Insights and saw negotiate and the follow-up requests on different servers for users who had fallen back from WebSockets. Broadcasts also only reached the sending instance, because we had no backplane. I restored affinity as a stopgap, then moved us to Azure SignalR Service, sized at [15] units from our peak connection count, and added jittered reconnects and graceful client migration. **R:** Missed-update tickets went from [about 30 a day to zero], and we could scale the app on CPU from then on: [instance count and cost numbers].

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me