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

📚 Interview question

Your API's memory grows steadily for hours until the container is OOM-killed and restarted. How do you use dotnet-counters and dotnet-gcdump snapshots to find what is growing and what keeps it alive, and how do you fix and verify it?

Diagnosing managed memory growth in .NET 10: confirming it with GC counters, comparing dotnet-gcdump snapshots in Visual Studio or PerfView, reading retention paths to the GC root, common leak roots (static caches, events, DI scopes, timers), and verifying the fix.

Mid-Level Debugging Intermediate debugging dotnet-gcdump gc memory-leak performance profiling

🎯 Key points

  • Confirm managed vs native: compare gc-heap-size and working set in dotnet-counters
  • A leak = Gen 2 / heap size rising after full GCs under steady load, not just a high number
  • Take 2–3 gcdumps under the same load minutes apart; diff by type count and size
  • Follow the retention path (paths to root) of the growing type to the GC root
  • Usual roots: static collections/caches, event handlers, captured closures, timers, DI root scope, unbounded IMemoryCache
  • Growth without a leak: LOH fragmentation (loh-size, fragmentation in GC info) from long-lived large buffers; pool them
  • Native growth or finaliser backlog needs dotnet-dump (eeheap, maddress, finalizequeue), not gcdump
  • Fix the root (bound, unsubscribe, scope, dispose), then verify heap flattens under a soak test

⏱ 30-second answer

First I confirm it is managed memory: in dotnet-counters, if gc-heap-size grows with the working set and survives Gen 2 collections, it's a managed leak; if the working set grows but the heap doesn't, it's native, and I switch to dotnet-dump (eeheap, maddress) and native tools.

For managed growth I take two or three dotnet-gcdump snapshots under the same load, minutes apart, and compare them in Visual Studio or PerfView. The type whose count and size keep rising is the suspect, and its paths to root show what holds it: usually a static cache, an event subscription, a timer, or services resolved from the root DI scope. If the heap grows but object counts don't, I check LOH fragmentation from long-lived large buffers.

I fix the root, not the symptom, and verify with a soak test that the heap flattens. The trade-off: each gcdump forces a full blocking GC, so I take few snapshots and avoid peak traffic when I can.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by checking that it really is a leak and what kind. In dotnet-counters I watch gc-heap-size, gen-2-gc-count and the working set. A high number on its own isn't a leak; the GC is lazy with Server GC and plenty of memory. A leak is the heap after each Gen 2 collection climbing under steady load. If the working set grows but the GC heap stays flat, it's native memory, such as unmanaged buffers, and that's a dump-and-native-tools job instead.

For managed growth I take dotnet-gcdump snapshots, normally three, ten minutes apart, while traffic is steady. A gcdump is the heap graph: types, counts, sizes and references, without field values, so it's small and safe to move around. I open them in Visual Studio, choose 'compare with baseline', and sort by size difference. For example, at [company] [the diff showed 1.4 million new PriceQuote objects per hour], and the paths-to-root view showed them held by a static ConcurrentDictionary used as a cache with no eviction. The fix was to replace it with IMemoryCache with a SizeLimit and expirations, and memory flattened at [600 MB] instead of climbing to the [2 GB] container limit.

The mistake I see is people raising the container memory limit or adding a nightly restart. That buys time but the leak is still there, and it usually takes the service down at the worst moment. The other mistake is fixing the type that's big instead of the thing that holds it: the leak is the root, not the objects."


Step by step

Step Tool What you look for
1. Confirm dotnet-counters gc-heap-size and Gen 2 size rising after full GCs; working set vs heap
2. Snapshot dotnet-gcdump collect × 2–3 Same load, minutes apart
3. Diff Visual Studio / PerfView Types with growing count and inclusive size
4. Retention Paths to root / RefTree The static, handler, timer or scope holding them
5. Fix Code Bound, unsubscribe, dispose, scope correctly
6. Verify Soak test + counters Heap flat over hours

Common leak roots

Root Typical cause Fix
Static collection Dictionary used as a cache IMemoryCache with SizeLimit, or HybridCache
Event handler Long-lived publisher, short-lived subscriber Unsubscribe in Dispose, weak events
Timer / CancellationTokenSource registration Not disposed Dispose; use PeriodicTimer in a BackgroundService
DI root scope Transient IDisposable resolved from root provider Create a scope per unit of work
HttpClient per call / IMemoryCache without limits Unbounded growth IHttpClientFactory; size limits
Captured closures Lambda captures a large object in a long-lived delegate Capture only what is needed

Production example

A notification service was OOM-killed every 9 hours at its 2 GB limit. Three gcdumps showed Subscription objects growing by 200,000 an hour, rooted through a singleton event PriceChanged that per-request handlers subscribed to and never left. Unsubscribing in Dispose flattened the heap at 450 MB over a 24-hour soak test, and restarts stopped.

🔍 What the interviewer is checking

Checks that the candidate can run a memory leak investigation methodically and fix the cause rather than the symptom.

Green flags

  • Distinguishes managed from native growth with counters
  • Compares multiple snapshots instead of reading one
  • Uses retention paths to find the GC root
  • Names concrete leak roots (events, statics, DI scopes) and verifies with a soak test

Red flags

  • Calls any high memory a leak
  • Proposes bigger limits or nightly restarts as the fix
  • Calls GC.Collect to 'solve' it

📚 Learn in depth

1. Managed vs native growth

 working set  ─┬─ managed GC heap  (gc-heap-size counter)
               │     ├─ Gen0 / Gen1 / Gen2
               │     ├─ LOH (>= 85,000 bytes)
               │     └─ POH (pinned)
               └─ native: runtime, JIT code, thread stacks, unmanaged buffers,
                          native libraries (SQL client, gRPC, image codecs)

If only the native part grows, gcdump won't help. Use dotnet-dump (and !maddress / eeheap) or native tools.

2. What a gcdump contains

dotnet-gcdump collect asks the runtime (through EventPipe) to run a full, blocking, compacting GC and emit GCBulkNode and GCBulkEdge events describing every live object, its type and size, and the references between objects. The tool turns that into a graph. There are no field values, so it's tens of MB rather than GB, and it carries little personal data, unlike a full dump. For very large heaps it may sample objects and scale counts.

3. Reading the diff

In Visual Studio (open .gcdump → 'Compare with baseline') or PerfView (Heap Snapshots → 'Diff'):

  • Count diff and size diff per type. Sort by inclusive size difference.
  • Ignore framework types like string and byte[] at first; look for your types whose count rises steadily, then see which framework types hang off them.
  • Paths to root (VS) / RefTree (PerfView): the chain from the object up to a GC root such as a static field, a GC handle, a thread stack or the finaliser queue.
 PriceQuote  ◀── Entry<string,PriceQuote>[] ◀── ConcurrentDictionary ◀── static PriceCache._items
                                                                    (GC root: static)

4. Why leaks happen in a GC language

The GC frees only unreachable objects. A leak in .NET is always something reachable that you no longer need: a collection that only grows, a long-lived object holding a reference to a short-lived one (events, callbacks, CancellationToken.Register), or a scope that is never disposed (IServiceProvider root scope tracks every transient IDisposable it creates).

5. The finaliser and LOH variants

  • Objects with finalisers survive one extra GC; a blocked finaliser thread makes them pile up (dotnet-dump: finalizequeue).
  • LOH fragmentation looks like growth without a leak; check loh-size and consider GCSettings.LargeObjectHeapCompactionMode or pooling large buffers.

6. Verifying the fix

Run a soak test (hours, steady load) and plot gc-heap-size and Gen 2 size. A healthy service shows a sawtooth that returns to the same baseline. Add an alert on post-GC heap size trend in Azure Monitor so the next leak is caught early.

Try it yourself

  1. Write an endpoint that adds a 1 KB object to a static List<object> per request; load it and watch dotnet-counters.
  2. Take two gcdumps 2 minutes apart and compare them in Visual Studio; find the static root.
  3. Repeat with an event subscription leak and see the delegate in the retention path.
  4. Fix both, run a 30-minute soak with k6, and confirm the heap flattens.

💻 Code

Capturing and comparing snapshots, then the leak found and its fix.

# Watch the shape first
dotnet-counters monitor -n Notify.Api --counters System.Runtime[gc-heap-size,gen-2-gc-count,working-set]

# Three snapshots under the same steady load
dotnet-gcdump collect -n Notify.Api -o 1.gcdump
sleep 600; dotnet-gcdump collect -n Notify.Api -o 2.gcdump
sleep 600; dotnet-gcdump collect -n Notify.Api -o 3.gcdump

# Quick text view of the largest types (then diff in Visual Studio or PerfView)
dotnet-gcdump report 3.gcdump | head -20
namespace Notify.Api;

public sealed record PriceChange(string Sku, decimal Price);

public sealed class PriceFeed               // registered as a singleton
{
    public event EventHandler<PriceChange>? PriceChanged;
    public void Publish(PriceChange change) => PriceChanged?.Invoke(this, change);
}

// BEFORE: a scoped service subscribes to a singleton's event and never leaves.
// The singleton's delegate list now roots every request's handler forever.
//
// public sealed class PriceWatcher(PriceFeed feed)
// {
//     public void Start() => feed.PriceChanged += OnChanged;
//     private void OnChanged(object? s, PriceChange c) { /* ... */ }
// }

// AFTER: unsubscribe when the scope is disposed.
public sealed class PriceWatcher : IDisposable
{
    private readonly PriceFeed _feed;

    public PriceWatcher(PriceFeed feed)
    {
        _feed = feed;
        _feed.PriceChanged += OnChanged;
    }

    private void OnChanged(object? sender, PriceChange change)
    {
        // handle the change for this request
    }

    public void Dispose() => _feed.PriceChanged -= OnChanged;  // breaks the root
}

// Program.cs
// builder.Services.AddSingleton<PriceFeed>();
// builder.Services.AddScoped<PriceWatcher>();   // DI disposes it at the end of the request

⚠ Common mistakes

  • Mistake: Optimising without measuring: guessing the leak from code review. Why it is wrong: Leaks hide in framework interactions (events, DI scopes) you won't spot by reading. Instead: Let the snapshot diff and retention path tell you.
  • Mistake: Micro-optimising allocations on cold paths while hunting a leak. Why it is wrong: Allocation rate and retention are different problems; short-lived garbage doesn't leak. Instead: Focus on what survives Gen 2.
  • Mistake: Calling high memory a leak. Why it is wrong: Server GC uses memory freely when it's available. Instead: Look for post-GC heap growth under steady load.
  • Mistake: Taking one snapshot. Why it is wrong: It shows what's big, not what's growing. Instead: Two or three snapshots under the same load, then diff.
  • Mistake: Fixing the big type instead of its root. Why it is wrong: Making PriceQuote smaller just delays the OOM. Instead: Break the reference that keeps it alive.
  • Mistake: Using gcdump for native growth. Why it is wrong: It only sees the managed heap. Instead: Compare working set with gc-heap-size first; use dotnet-dump or native tools for native memory.
  • Mistake: Raising the memory limit or adding scheduled restarts as the fix. Why it is wrong: It hides the bug and moves the outage. Instead: Use it only as a mitigation while you fix the root.
  • Mistake: Snapshotting at peak traffic on a huge heap. Why it is wrong: The forced full GC pauses the process. Instead: Take snapshots off-peak or on one instance pulled from the load balancer.

🏛 Senior insight: trade-offs

A leak investigation is a routine, not heroics: confirm with counters, diff snapshots, follow the root, fix, soak. The senior part is making it cheap next time: memory alerts on post-GC heap trend rather than raw working set, dotnet-monitor collection rules that take a gcdump automatically when the heap crosses a threshold, and a soak test in the pipeline for long-running services. I also treat container memory limits as part of the design: DOTNET_GCHeapHardLimit or the container-aware defaults mean the GC knows its budget, so an OOM-kill really means a leak or a sizing error, not a lazy GC.

Tool When it fits Cost When not to
dotnet-gcdump diff Managed growth Blocking full GC per snapshot Native memory
dotnet-dump + SOS (gcroot, dumpheap) Need field values, finaliser queue, native Large sensitive file, process pause First look at a simple leak
Visual Studio / dotMemory locally Reproducible leak Needs a repro Production-only behaviour
dotnet-monitor trigger Leak appears after hours Sidecar to run and secure Short-lived processes

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions objects rooted by a DI scope or ServiceProviderEngineScope Why: Checks they understand disposable transients captured by the root scope
    How to answer

    The container is keeping objects alive because it promised to dispose them. Every scope, including the root, tracks the transient IDisposables it creates until the scope ends; for the root that means process shutdown. Typical causes are resolving from app.Services or from an IServiceProvider injected into a singleton (which is the root), or a scope created once and never disposed. ValidateScopes doesn't catch it.

    Find the type and call site from the gcdump's retention path (ServiceProviderEngineScope → disposables), then either create a scope per operation with IServiceScopeFactory.CreateAsyncScope() when several scoped services are needed, or use a factory whose result you dispose with using when it's one object. The cost of leaving it: a growing Gen2 heap, longer full GCs and eventual OOM kills. Verify with dotnet-counters over several hours.

  2. When: Candidate says gcdump can't see native memory or field values Why: Checks they can analyse a full memory dump with SOS
    How to answer

    When I can't attach a debugger, I take a dump: a snapshot of the process's memory, threads and stacks that I analyse offline. For a hang or a leak, dotnet-dump collect -p <pid> does it in seconds. For crashes, I enable automatic crash dumps with the DOTNET_DbgEnableMiniDump environment variables. On App Service I use Diagnose and solve problems, and in Kubernetes dotnet-monitor. Then I analyse with dotnet-dump analyze: clrstack -all and syncblk for hangs, dumpheap -stat and gcroot for leaks, pe for exceptions. Or I open the dump in Visual Studio and use the Threads and Parallel Stacks windows. Dumps contain customer data, so they're handled as sensitive.

  3. When: Candidate mentions dotnet-counters or dotnet-monitor Why: Checks they know the whole diagnostics toolbox and when to use each tool
    How to answer

    The .NET diagnostics tools all talk to the runtime over its diagnostics IPC channel, so they work on Windows, Linux and in containers without a debugger.

    • dotnet-counters shows live metrics (CPU, GC heap size, allocation rate, ThreadPool queue length, exceptions) with almost no overhead. It tells you what kind of problem you have.
    • dotnet-trace records an EventPipe trace with CPU samples and runtime events; it tells you where time goes.
    • dotnet-gcdump captures the managed heap graph (types, sizes and references). Comparing snapshots shows what is growing; the reference paths show what keeps it alive. dotnet-dump captures the whole process for SOS analysis of hangs and native memory.
    • dotnet-monitor wraps all of this as an HTTP API or sidecar with triggers, which is how you use them in Kubernetes or Container Apps.

    I start with counters because they are cheap, then pick the heavier tool the symptom points to. The trade-off is overhead and data sensitivity: a full dump contains every secret in memory.

🛠 Real-world problems: how you handle them

Notification service OOM-killed every 9 hours by an event subscription leak
Situation
A notification service in [AKS, Australia East] pushed price alerts to [~40,000] users. Each pod had a [2 GB] memory limit and ran [6] replicas.
Signals
Kubernetes events showed OOMKilled restarts every [8–10 hours] per pod; Azure Monitor showed memory climbing linearly; brief bursts of 503s during restarts; no error logs before the kill.
Investigation
dotnet-counters on one pod showed gc-heap-size tracking the working set and the post-Gen 2 baseline rising about [150 MB/hour], so it was managed. I took three dotnet-gcdump snapshots 15 minutes apart via dotnet-monitor's /gcdump endpoint, compared them in Visual Studio, and saw PriceWatcher and EventHandler<PriceChange> counts growing by [~50,000] per snapshot. Paths to root went through the singleton PriceFeed's PriceChanged delegate.
Resolution
Immediate: raised the restart cadence with a lower memory alert so pods recycled gracefully off-peak. Fix: PriceWatcher implemented IDisposable and unsubscribed; DI disposed it per scope. A 24-hour soak showed the heap flat at [~450 MB].
Prevention
Alert on post-GC heap trend, not just working set; a dotnet-monitor collection rule that takes a gcdump when the heap passes [1.2 GB]; a review checklist item for subscriptions to singleton events; a nightly soak test in the staging environment.

How to tell it (STAR)

**S:** At [company] our notification pods were being OOM-killed roughly every [9 hours], causing short bursts of failed pushes. **T:** I was asked to find the cause rather than keep raising the memory limit. **A:** I confirmed with dotnet-counters that the managed heap was growing after each full GC, took three gcdumps through dotnet-monitor, and compared them in Visual Studio. The growing type was our per-request PriceWatcher, rooted by a singleton's event. I made it unsubscribe on Dispose and ran a 24-hour soak test. **R:** Memory flattened at [450 MB], OOM restarts went from [16 a day] to zero, and we added an alert and an automatic gcdump rule so the next leak is caught in minutes.

↩ Usually asked after

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me