Covers diagnosing Blazor Server under load: circuit memory and leaks, scoped DbContext, blocking calls, WebSockets and long polling, sticky sessions, circuit options and SignalR limits, Azure SignalR Service, .NET 10 circuit metrics, and moving pages to static SSR or WebAssembly.
A Blazor Server app holds a circuit per browser tab: component state, a DI scope and a SignalR connection. Under load, capacity is memory per circuit ร concurrent tabs plus thread-pool health. I check four things. Transport: are WebSockets enabled end to end, or has it fallen back to long polling? Affinity: after scale-out, do reconnects land on the server that owns the circuit (sticky sessions or Azure SignalR Service)? Memory: dotnet-counters, the .NET 10 circuit metrics and a dotnet-dump to find leaked components, circuit-long DbContexts and huge lists. Blocking: sync-over-async starving the thread pool.
Then I fix leaks first, use IDbContextFactory and Virtualize, and move read-only pages to static SSR. The trade-off: Server mode is productive, but every connected user costs server memory.
"First I separate the three symptoms, because they have different causes. 'Attempting to reconnect' means the browser lost its SignalR connection or stopped hearing heartbeats: an instance recycled, a proxy dropped the WebSocket, or the server was so starved of threads that pings were late. Slowness with a healthy connection means each click is expensive: high CPU, big render diffs, slow database calls, or simply round-trip latency to a distant region. Lost work means the circuit was gone by the time the user reconnected: the instance restarted, the reconnect landed on a different server, or the circuit was evicted from the retention buffer. So I look at transport, affinity, memory and the thread pool, in that order, with Application Insights open on the Monday window to correlate failed
_blazornegotiations, dependency timings, exceptions and instance restarts.Transport and affinity first, because they are quick to check. In the browser's Network tab I look for a WebSocket to
_blazor; if I see repeated long-polling requests, WebSockets are off on App Service or blocked by a proxy. If we scaled out, the reconnect must reach the server that holds the circuit, so I check ARR affinity, or better, Azure SignalR Service with sticky mode required. Then memory:dotnet-countersfor GC heap size, gen 2 collections, connection count and thread pool queue length, plus the circuit metrics .NET 10 adds. If memory per circuit is far above the few hundred kilobytes a lean component tree needs, I take adotnet-dumpand rundumpheap -stat. For example, at [company] we found [a scoped DbContext per circuit tracking thousands of entities] and [components kept alive by an event on a singleton], which pushed us to [~4 MB per circuit]; afterIDbContextFactory,Virtualizeand unsubscribing, it was [~300 KB] and the Monday peak fit in [half the instances].Finally the thread pool: one
.Resulton an HTTP call in a component blocks a thread per user, and under load the queue grows until SignalR heartbeats time out and everyone 'reconnects'. TuningCircuitOptionscomes last, after the leaks are fixed. The mistake I see is scaling up the plan to hide a leak; it buys a week. The senior fix is often architectural: read-only pages to static SSR, so only the screens that need interactivity hold a circuit."
| Symptom | Likely cause | Check |
|---|---|---|
| Reconnect UI for many users at once | Thread pool starvation, instance recycle, deployment | Thread pool queue length, App Service restarts |
| Reconnect fails after scale-out | No session affinity | ARR affinity setting, Azure SignalR Service mode |
Many _blazor?id= HTTP requests |
Long polling fallback | Network tab, App Service WebSockets setting, proxy |
| Memory climbs with flat user count | Leak (events, timers, interop refs) | Two dumps compared |
| Memory high but stable | Too much state per circuit | Memory รท circuits; large lists, scoped DbContext |
| Clicks slow, CPU high | Expensive renders, big diffs | Profiling with dotnet-trace, render counts |
| Clicks slow, CPU low | Slow dependencies or distant region | Application Insights dependency durations, user location |
| Users lose work after a short outage | Circuit evicted before reconnect | DisconnectedCircuitRetentionPeriod, persisted circuit state |
| Setting | Default | Meaning |
|---|---|---|
CircuitOptions.DisconnectedCircuitMaxRetained |
100 | Disconnected circuits kept in memory per server |
CircuitOptions.DisconnectedCircuitRetentionPeriod |
3 minutes | How long a disconnected circuit waits for its user |
CircuitOptions.JSInteropDefaultCallTimeout |
1 minute | Interop call timeout |
CircuitOptions.MaxBufferedUnacknowledgedRenderBatches |
10 | Render batches buffered for a slow client |
HubOptions.MaximumReceiveMessageSize |
32 KB | Largest client โ server message |
| App Service Web sockets | Off on some plans/templates | Must be on to avoid long polling |
An internal timesheet app hit [2,100] concurrent users every Monday at 9 am on two P1v3 instances. Memory per circuit was [~4 MB], instances ran out of memory and recycled, so everyone lost their circuit. After the fixes below, it ran at [~300 KB] per circuit on the same two instances with [p95 click latency under 120 ms] from Sydney and Melbourne.
Checks that the candidate understands Blazor Server's runtime model well enough to diagnose load problems systematically and fix the cause rather than scaling up.
Green flags
dotnet-counters, dotnet-dump and circuit metrics with specific signalsDbContext, leaked subscriptions and big lists as common culpritsRed flags
Browser tab
blazor.web.js --WebSocket /_blazor--> Load balancer --(affinity)--> Server instance
CircuitHost
|- Renderer + component tree
|- DI scope (scoped services)
|- JS interop object tables
'- SignalR HubConnection
The circuit lives in one process. Reconnects must reach the same process, or the circuit is lost. With Azure SignalR Service, browsers connect to the service and the service keeps a server connection to the instance that owns the circuit, so the app servers stop holding thousands of client sockets.
A small component tree costs in the low hundreds of kilobytes. What blows it up:
DbContext that lives for the circuit and tracks every entity loaded.<Virtualize>, held in fields and in the render tree.DotNetObjectReferences, which keep components alive after the user navigates away, or keep whole circuits alive after the tab closes.DisconnectedCircuitMaxRetained extra circuits per server.Capacity check: (memory per circuit ร peak tabs) + baseline must fit comfortably under the instance's memory, with headroom for GC.
SignalR sends keep-alive pings (every 15 seconds by default) and the client times out the connection if it hears nothing within the server timeout (30 seconds by default). If thread pool threads are blocked by sync-over-async (.Result, .Wait()), the queue grows, messages are delayed, and clients time out and show the reconnect UI, even though the server is "up". dotnet-counters monitor System.Runtime shows threadpool-queue-length growing and threadpool-thread-count creeping up slowly as the pool injects threads.
dotnet-counters monitor --counters System.Runtime,Microsoft.AspNetCore.Http.Connections for GC heap, gen 2 count, thread pool and current connections.CircuitHandler can log circuit open/close and count active circuits per instance.dotnet-dump collect, then dumpheap -stat and gcroot <address> on a component or DbContext to find what holds it._blazor WebSocket frames show render batch sizes and frequency.| Option | What it does | Notes |
|---|---|---|
| Session affinity (ARR affinity, ingress sticky cookie) | Keeps a browser on one instance | Uneven load; instance loss drops its circuits |
| Azure SignalR Service | Offloads client connections | Use ServerStickyMode.Required for Blazor; pick a region close to users, such as Australia East |
| Scale up | More memory per instance | Hides leaks |
| Static SSR / WebAssembly for some pages | Fewer circuits | Architectural change, best long-term |
When a circuit is gone, its in-memory state is gone. .NET 10 can persist circuit state and restore it when the user reconnects to a new circuit, which helps with short outages and evictions, but deployments and recycles still need durable drafts in the database or browser storage.
DbContext page that loads 5,000 rows and compare memory per circuit with an IDbContextFactory + Virtualize version..Result call in a click handler, load test, and watch threadpool-queue-length and the reconnect UI.CircuitHandler that counts circuits and expose it as a metric.Server-side settings, a circuit counter, and the fixes for the common leaks.
// Program.cs
using Microsoft.AspNetCore.Components.Server.Circuits;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents(o =>
{
// Tune only after fixing leaks: fewer retained circuits = less memory after mass disconnects
o.DisconnectedCircuitMaxRetained = 200;
o.DisconnectedCircuitRetentionPeriod = TimeSpan.FromMinutes(2);
})
.AddHubOptions(o => o.MaximumReceiveMessageSize = 64 * 1024); // only if large JS->.NET payloads are needed
// Offload client connections; Blazor requires sticky mode
builder.Services.AddSignalR().AddAzureSignalR(o =>
o.ServerStickyMode = Microsoft.Azure.SignalR.ServerStickyMode.Required);
// Short-lived DbContexts instead of one per circuit
builder.Services.AddDbContextFactory<TimesheetDb>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Timesheets")));
builder.Services.AddSingleton<CircuitCounter>();
builder.Services.AddScoped<CircuitHandler, CircuitCounterHandler>();
var app = builder.Build();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
app.Run();
// CircuitCounter.cs: active circuits per instance as a metric
using System.Diagnostics.Metrics;
using Microsoft.AspNetCore.Components.Server.Circuits;
namespace Timesheets.Diagnostics;
public sealed class CircuitCounter
{
private static readonly Meter Meter = new("Timesheets.Blazor");
private readonly UpDownCounter<int> active = Meter.CreateUpDownCounter<int>("blazor.circuits.active");
public void Opened() => active.Add(1);
public void Closed() => active.Add(-1);
}
public sealed class CircuitCounterHandler(CircuitCounter counter, ILogger<CircuitCounterHandler> log) : CircuitHandler
{
public override Task OnCircuitOpenedAsync(Circuit circuit, CancellationToken ct)
{
counter.Opened();
return Task.CompletedTask;
}
public override Task OnCircuitClosedAsync(Circuit circuit, CancellationToken ct)
{
counter.Closed();
return Task.CompletedTask;
}
public override Task OnConnectionDownAsync(Circuit circuit, CancellationToken ct)
{
log.LogInformation("Circuit {CircuitId} disconnected", circuit.Id);
return Task.CompletedTask;
}
}
@* Before: scoped DbContext, all rows in memory, blocking call. After: *@
@inject IDbContextFactory<TimesheetDb> DbFactory
<Virtualize ItemsProvider="LoadEntries" Context="e" ItemSize="40">
<TimesheetRow Entry="e" />
</Virtualize>
@code {
// Only the visible window is loaded and held; the context is disposed after each call
private async ValueTask<ItemsProviderResult<EntryDto>> LoadEntries(ItemsProviderRequest req)
{
await using var db = await DbFactory.CreateDbContextAsync(req.CancellationToken);
var query = db.Entries.AsNoTracking().OrderByDescending(x => x.Date);
var total = await query.CountAsync(req.CancellationToken);
var page = await query.Skip(req.StartIndex).Take(req.Count)
.Select(x => new EntryDto(x.Id, x.Date, x.Hours))
.ToListAsync(req.CancellationToken); // async all the way: no .Result
return new ItemsProviderResult<EntryDto>(page, total);
}
}
DbContext into interactive components. Why it is wrong: it lives for the circuit and its change tracker grows for hours. Instead: IDbContextFactory and a context per operation.Virtualize or server-side paging..Result, .Wait()) in handlers. Why it is wrong: they starve the thread pool, delaying heartbeats so every user sees reconnects. Instead: async all the way.DisconnectedCircuitRetentionPeriod to stop lost work. Why it is wrong: more disconnected circuits stay in memory, making the overload worse. Instead: save drafts durably and use .NET 10 circuit state persistence for short gaps.Blazor Server's cost model is memory and a connection per active tab, and that is a design constraint, not a tuning problem. I size it early: target memory per circuit (I aim for a few hundred kilobytes), expected peak tabs (users ร tabs per user), and latency from users to the region. For an Australian workforce, hosting in Australia East keeps click latency acceptable; hosting in a US region adds 150+ ms per click and makes the app feel broken. When the numbers do not fit, I change the architecture rather than the instance size.
For known peaks (Monday 9 am, end of month), I plan capacity rather than react: a memory-per-circuit budget enforced by a load test in the pipeline, scheduled scale-out before the peak (autoscale on memory reacts too late because new instances only receive new circuits), and Azure SignalR Service so instance count is not tied to connection count. For the case where limits are still exceeded, I design graceful degradation: drafts saved durably so a dropped circuit costs seconds not minutes, .NET 10 circuit state persistence backed by a distributed cache for short gaps, a custom reconnect UI that tells users their work is saved, and, if needed, a static SSR fallback for read-only views so the most common tasks never need a circuit.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Fix leaks + IDbContextFactory + Virtualize |
Always first | Engineering time | Never skip |
| Azure SignalR Service | Thousands of connections, multiple instances | Service units cost, another dependency | Small internal apps on one instance |
| Session affinity only | Few instances, self-hosted | Uneven load; instance loss drops circuits | Frequent autoscaling |
| Scheduled scale-out before known peaks | Predictable spikes | Paying for idle capacity briefly | Unpredictable traffic (use headroom instead) |
| Static SSR for read-only pages | Lists, reports, content | Less interactivity | Real-time editors |
| WebAssembly/Auto for heavy interactive parts | Public apps, many users | Download size, API needed | Code that must stay server-side |
I prove capacity with a WebSocket load test before go-live and watch circuits, memory per instance and thread pool queue length on an Application Insights / Azure Monitor dashboard afterwards, with alerts before memory reaches the recycle threshold.
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.
Inject IJSRuntime and load a collocated JS module with InvokeAsync<IJSObjectReference>("import", "./Components/Map.razor.js"), then call its exports with InvokeAsync<T> or InvokeVoidAsync. Do it in OnAfterRenderAsync(firstRender), because during prerendering there is no browser and before the first render there is no DOM element. JavaScript calls back into .NET with [JSInvokable] methods, either static (DotNet.invokeMethodAsync) or on an instance through a DotNetObjectReference.
Both references hold objects alive across the boundary, so dispose them in DisposeAsync and catch JSDisconnectedException when the circuit is already gone. In Server mode every call is a SignalR round trip and JS-to-.NET calls are untrusted input; in WebAssembly they are in-process and fast. The trade-off: interop unlocks browser APIs, but each call costs latency and adds lifetime management.
Sync-over-async is synchronously blocking on asynchronous work: .Result, .Wait(), GetAwaiter().GetResult() or Task.WaitAll. It holds a thread for the whole operation, causes ThreadPool starvation on servers and deadlocks under a SynchronizationContext. It sneaks in through constructors, DI factory lambdas, property getters, Dispose, lock blocks, synchronous interfaces (IComparer, old filters), static initialisers and "quick fixes" in legacy code. Remove it by making the call chain async, using async factory methods or lazy async initialisation, IAsyncDisposable, hosted-service warm-up, and async-capable interfaces. Where a sync boundary is unavoidable (for example a legacy interface), keep it at the edge and document it.
How to tell it (STAR)
**S:** At [company], our Blazor Server timesheet app for [~2,500] staff fell over every Monday morning: reconnect banners, slow clicks and lost entries. **T:** As [my role] I was asked to make Monday boring again without doubling the hosting bill. **A:** I ruled out transport and affinity in dev tools, then used `dotnet-counters` and two `dotnet-dump` captures to find about 4 MB per circuit from circuit-scoped `DbContext`s and components held by a singleton event, plus a `.Result` starving the thread pool. We moved to `IDbContextFactory`, added `Virtualize`, fixed the subscriptions and the blocking call, saved drafts to the database, and moved read-only pages to static SSR. I added a WebSocket load test with a memory budget to the pipeline. **R:** Memory per circuit fell to [~300 KB], Monday tickets went from [~60] to [2], and we went back to two instances, saving [~$X a month].
Last updated 23 Nov 2026.