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

๐Ÿ“š Interview question

Your Blazor Server app works well in testing, but on Monday morning with about 2,000 users it slows down, memory climbs, users see 'Attempting to reconnect' and some lose their work. How do you diagnose it? Cover circuits and memory per user, WebSockets and sticky sessions, SignalR limits and Azure SignalR Service, and what you change in the app.

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.

Senior Debugging Advanced azure blazor debugging frontend performance signalr

๐ŸŽฏ Key points

  • Every tab holds a circuit: memory per circuit x concurrent tabs is the capacity limit
  • Separate symptoms: reconnects = broken or starved connection; slowness = CPU, render cost or round-trip latency; lost work = circuit gone before reconnect
  • Check transport: WebSockets disabled or blocked falls back to long polling; scale-out without sticky sessions breaks circuits
  • Measure with dotnet-counters (connections, GC heap, thread pool), the .NET 10 circuit metrics, and Application Insights live metrics, failed negotiations, dependency timings and exceptions correlated with the peak
  • dotnet-dump + dumpheap -stat / gcroot to find component and DbContext instances held by leaked event handlers
  • Common causes: circuit-long scoped DbContext, large lists in memory without Virtualize, undisposed timers/subscriptions, sync-over-async blocking the thread pool
  • Azure SignalR Service (sticky mode required) offloads connections; tune CircuitOptions only after fixing leaks
  • Move read-only pages to static SSR and heavy interactive parts to WebAssembly or Auto

โฑ 30-second answer

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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"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 _blazor negotiations, 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-counters for 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 a dotnet-dump and run dumpheap -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]; after IDbContextFactory, Virtualize and unsubscribing, it was [~300 KB] and the Monday peak fit in [half the instances].

Finally the thread pool: one .Result on 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'. Tuning CircuitOptions comes 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

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

Settings worth knowing

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

Production example

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.

๐Ÿ” What the interviewer is checking

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

  • Separates transport, affinity, memory and thread pool causes
  • Uses dotnet-counters, dotnet-dump and circuit metrics with specific signals
  • Names circuit-long DbContext, leaked subscriptions and big lists as common culprits
  • Knows Azure SignalR Service needs sticky mode for Blazor and considers static SSR or WebAssembly

Red flags

  • "Just scale up"
  • Does not know each tab holds a circuit on the server
  • Load tests with plain HTTP requests

๐Ÿ“š Learn in depth

1. Anatomy of a Blazor Server connection

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.

2. Memory per circuit

A small component tree costs in the low hundreds of kilobytes. What blows it up:

  • A scoped DbContext that lives for the circuit and tracks every entity loaded.
  • Lists of thousands of rows rendered without <Virtualize>, held in fields and in the render tree.
  • Event subscriptions on singletons, undisposed timers and DotNetObjectReferences, which keep components alive after the user navigates away, or keep whole circuits alive after the tab closes.
  • Disconnected circuits retained for the retention period: with 2,000 users on flaky Wi-Fi, up to 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.

3. Thread pool and heartbeats

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.

4. Observability

  • dotnet-counters monitor --counters System.Runtime,Microsoft.AspNetCore.Http.Connections for GC heap, gen 2 count, thread pool and current connections.
  • .NET 10 adds Blazor metrics and tracing, including circuit counts and durations, which you can export with OpenTelemetry to Application Insights or Azure Monitor.
  • A custom 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.
  • Browser dev tools: the _blazor WebSocket frames show render batch sizes and frequency.

5. Scaling options

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

6. Losing work

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.

Try it yourself

  1. Load test a sample Blazor Server app with a WebSocket-capable tool (for example k6 or Crank with a Blazor scenario) at 500 simulated users and record memory per circuit.
  2. Add a scoped DbContext page that loads 5,000 rows and compare memory per circuit with an IDbContextFactory + Virtualize version.
  3. Add a .Result call in a click handler, load test, and watch threadpool-queue-length and the reconnect UI.
  4. Disable WebSockets on a test App Service and watch the long-polling requests in the Network tab.
  5. Write a CircuitHandler that counts circuits and expose it as a metric.

๐Ÿ’ป Code

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

โš  Common mistakes

  • Mistake: Scaling up the App Service plan without finding the leak. Why it is wrong: memory still grows; you only delay the recycle. Instead: compare two dumps and fix what holds components alive.
  • Mistake: Scaling out without session affinity or Azure SignalR Service. Why it is wrong: reconnects land on another instance that does not have the circuit, so users lose state. Instead: turn on affinity or use Azure SignalR Service with sticky mode required.
  • Mistake: Leaving WebSockets disabled. Why it is wrong: the client falls back to long polling, multiplying requests and latency. Instead: enable WebSockets on App Service and any proxy or gateway.
  • Mistake: Injecting a scoped 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.
  • Mistake: Rendering thousands of rows into a component. Why it is wrong: the data, the render tree and the diff all scale with row count, per user. Instead: Virtualize or server-side paging.
  • Mistake: Blocking calls (.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.
  • Mistake: Raising 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.
  • Mistake: Load testing with plain HTTP requests. Why it is wrong: they never open circuits, so they measure nothing about Blazor Server capacity. Instead: use a WebSocket-capable load tool or real browsers.

๐Ÿ› Senior insight: trade-offs

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.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions sticky sessions or Azure SignalR Service Why: Checks deeper knowledge of scaling SignalR across instances and connection limits
    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.

  2. When: Candidate mentions undisposed DotNetObjectReference or JS listeners as a leak Why: Checks whether they know how to write interop that does not leak circuits
    How to answer

    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.

  3. When: Candidate says blocking calls starve the thread pool and delay heartbeats Why: Checks whether they can find and remove sync-over-async in real code
    How to answer

    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.

๐Ÿ›  Real-world problems: how you handle them

Monday 9 am reconnect storm in a Blazor Server timesheet app
Situation
An internal Blazor Server timesheet app for [~2,500 staff] on two Azure App Service P1v3 instances in Australia East. Every Monday between 8:45 and 9:30 am, users saw 'Attempting to reconnect', clicks took seconds, and some lost half-entered timesheets.
Signals
App Service memory at [95%] and instance recycles around 9:10 am; Application Insights showed a spike in failed `_blazor` negotiations; `threadpool-queue-length` in the hundreds; helpdesk received [~60] tickets each Monday.
Investigation
Browser dev tools showed WebSockets working, ruling out long polling. ARR affinity was on. `dotnet-counters` during the peak showed GC heap at [3.2 GB] with [~800] circuits per instance, about 4 MB each, and a growing thread pool queue. `dotnet-dump` with `dumpheap -stat` showed thousands of tracked `TimesheetEntry` entities from circuit-scoped `DbContext`s and `ReminderBanner` components rooted by a singleton `ReminderService` event. `dotnet-trace` found a `.Result` on an HTTP call to the payroll API in the submit handler.
Resolution
Immediate: scaled out to four instances for the next Monday. Real fix: `IDbContextFactory` with a context per operation, `Virtualize` on the entries grid, unsubscribing from `ReminderService` in `Dispose`, async payroll call, and moving the read-only history and reports pages to static SSR. Saved drafts to the database on each row change.
Prevention
A k6 WebSocket load test of 2,500 users in the release pipeline with a memory-per-circuit budget of [500 KB]; a custom circuit metric and alerts on memory and thread pool queue; an analyser rule against `.Result`/`.Wait()`; review checklist items for `IDbContextFactory` and event unsubscription.

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].

More in Blazor

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me