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

📚 Interview question

Your ASP.NET Core service's memory grows steadily for days until the pod is OOM-killed, and a dotnet-gcdump shows thousands of instances retained through the DI container. Walk through how you diagnose DI-related memory growth (root-tracked transient disposables, long-lived scopes, captured singletons) and how you fix it.

Covers diagnosing memory growth caused by dependency injection: confirming managed growth with dotnet-counters, reading gcdump retention paths through ServiceProviderEngineScope, the three common DI causes, and fixes plus prevention.

Senior Debugging Advanced dependency-injection dotnet-gcdump idisposable memory-leaks production-debugging service-lifetimes

🎯 Key points

  • First prove it is managed-heap growth: dotnet-counters gc-heap-size and gen-2 size rising after full GCs (versus native growth: working set up, GC heap flat)
  • Take two dotnet-gcdumps an hour apart and diff the type counts; follow the retention path (Visual Studio, PerfView, or dotMemory snapshots locally)
  • Root-tracked transients: ServiceProvider → root ServiceProviderEngineScope → disposables list
  • Long-lived scopes: a worker that creates one scope before its loop and resolves transient disposables per iteration, Blazor circuits, scopes never disposed
  • Captured singletons: a singleton holding a growing collection, a captive DbContext change tracker, event handlers never unsubscribed
  • ValidateScopes catches captive scoped services but not root-resolved transient disposables
  • Fix: resolve inside short scopes, own disposables via factories and using, bound caches (IMemoryCache SizeLimit)
  • Prevent: soak test with heap assertions, working-set slope alerts, analyser ban on root provider access

⏱ 30-second answer

First I confirm it is the managed heap: dotnet-counters shows gc-heap-size and Gen2 climbing even after full collections. Then I take two dotnet-gcdumps an hour apart, diff the type counts, and follow the retention path of the growing type.

If the path runs through ServiceProviderEngineScope → disposables, the container is holding them. Three usual causes:

  • Transient IDisposables resolved from the root (static helpers, singletons using an injected IServiceProvider): tracked until shutdown.
  • Scopes that live too long: one scope for a worker's whole loop, never-disposed scopes, long Blazor circuits.
  • Singletons that accumulate: a captive DbContext change tracker, unbounded dictionaries, unremoved event handlers.

Fix by resolving inside short scopes, owning per-call disposables through factories and using, and bounding caches. ValidateScopes doesn't catch root-tracked transients, so add a soak test and a working-set alert.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by separating managed from native growth, because the tools are different. dotnet-counters monitor on the pod: if GC heap size and Gen2 keep rising after Gen2 collections, it's managed and something is rooting objects. Then I take a gcdump, wait an hour, take another, and compare. The type whose count grows is the lead; the retention path tells me who's holding it. With DI leaks the path usually reads ServiceProvider → ServiceProviderEngineScope → its disposables list, which tells me the container is keeping objects alive because it promised to dispose them later.

For example, at [company] we [had a document service OOM-killed every couple of days]. The diff showed [tens of thousands] of a transient renderer, rooted by the root scope. A static helper was calling app.Services.GetRequiredService<PdfRenderer>() per request; because the renderer was IDisposable, the root tracked every one until shutdown. We replaced it with a factory and using, and [memory went flat at about 350 MB]. Scope validation didn't catch it because resolving a transient from the root is legal.

The other two patterns I check: scopes that live too long, like a worker that creates one scope before its loop, so every transient resolved inside it piles up; and singletons that grow, like a captive DbContext whose change tracker never empties, or a Dictionary cache with no eviction. The mistake I see is raising the memory limit or adding a nightly restart and calling it fixed. The leak is still there; you've just scheduled the outage."


Triage

Observation Likely area
GC heap and Gen2 grow, never drop Managed leak (DI, caches, events)
Working set grows, GC heap flat Native memory, unmanaged handles, pinned buffers
Growth proportional to requests Per-request leak (root-tracked transients)
Growth proportional to time or messages in a worker Long-lived scope or captive context

DI causes and their retention paths

Cause Retention path in the gcdump Fix
Transient disposable from root ServiceProvider → root ServiceProviderEngineScope → disposables Resolve in a scope or use a factory with using
Long-lived scope BackgroundService field / closure → ServiceProviderEngineScope → disposables Scope per unit of work
Captive DbContext Singleton → DbContext → StateManager → entries Correct lifetime or IDbContextFactory<T>
Unbounded singleton cache Singleton → Dictionary/ConcurrentDictionary IMemoryCache with SizeLimit and expiry
Event subscriptions Singleton event → delegate → scoped subscriber Unsubscribe in Dispose, or avoid events across lifetimes

Production example

After the fix, gen-2 size stayed between [180 and 220 MB] over a [7-day] soak instead of climbing [~40 MB an hour], the OOM restarts (previously [3–4 a week]) stopped, and the nightly restart cron job was deleted.

🔍 What the interviewer is checking

Checks a methodical memory investigation and specific knowledge of how the DI container retains objects.

Green flags

  • Separates managed from native growth with dotnet-counters first
  • Diffs two gcdumps and reads retention paths
  • Recognises ServiceProviderEngineScope disposables as the DI signature
  • Knows ValidateScopes doesn't catch root-resolved transients
  • Adds prevention: soak test, alerts, analyser rules

Red flags

  • "Increase memory and restart nightly"
  • Calls GC.Collect()
  • No tool beyond Task Manager or the portal's memory graph

📚 Learn in depth

1. The tools, in order

dotnet-counters monitor -p <pid> --counters System.Runtime
   → gc-heap-size, gen-2-size, loh-size trend
         │ managed growth?
         ▼
dotnet-gcdump collect -p <pid>   (T0)  … wait …  (T1)
   → open both in Visual Studio / PerfView, diff by type count and size
         │ growing type found
         ▼
retention path ("Paths to root")
   → who holds it: container scope? singleton? static? event?
         │ need field values?
         ▼
dotnet-dump collect + analyze: dumpheap -stat, gcroot <addr>

dotnet-gcdump triggers a Gen2 GC and captures only the object graph (small, safe in production); dotnet-dump captures the full process (large, includes data, so treat it as sensitive under the Privacy Act if it may contain personal information).

2. Why the container holds objects

Each ServiceProviderEngineScope keeps the disposables it created so it can dispose them at scope end. If the scope is the root, "scope end" is process exit:

GC root (static ServiceProvider in Host)
  └─ ServiceProviderEngineScope (root)
       └─ List<object> disposables
            ├─ PdfRenderer #1
            ├─ PdfRenderer #2
            └─ … #90,000

The same thing happens with any long-lived scope, for example one created at the top of a BackgroundService and never disposed.

3. Captive contexts grow differently

A singleton holding a DbContext retains every tracked entity in the StateManager. Growth correlates with distinct rows read, not requests. ChangeTracker.Entries().Count() in a debug endpoint or a dump confirms it.

4. What validation catches

Problem ValidateScopes ValidateOnBuild
Singleton → scoped Yes Yes (at start-up)
Scoped resolved from root Yes n/a
Transient disposable from root No No
Long-lived scope No No

So the root-transient leak needs a runtime check: a soak test or production telemetry.

5. Fix patterns

  • Per-operation disposable from a singleton: Func<T> or a typed factory registered so the container does not track the result, then using.
  • Several scoped services: IServiceScopeFactory.CreateAsyncScope() per operation.
  • Caches: IMemoryCache with SizeLimit and per-entry Size, or HybridCache with limits.

Try it yourself

  1. Build a minimal API with an endpoint that resolves a transient IDisposable from app.Services; hit it 100,000 times with bombardier and watch gc-heap-size.
  2. Take two gcdumps and find the retention path through ServiceProviderEngineScope.
  3. Fix it with a factory and confirm the heap flattens.
  4. Write a soak test that runs 10,000 iterations and asserts GC.GetTotalMemory(true) growth below a threshold.

💻 Code

The leak and the fix.

namespace Reports;

public sealed class PdfRenderer : IDisposable
{
    private readonly byte[] _buffer = new byte[64 * 1024]; // stands in for native resources
    public byte[] Render(string html) =&gt; _buffer[..16];
    public void Dispose() { /* release handle */ }
}

// BEFORE: resolves a transient IDisposable from the ROOT provider per call.
public static class ReportHelper
{
    public static IServiceProvider Services { get; set; } = default!; // set to app.Services at start-up

    public static byte[] Render(string html)
    {
        var renderer = Services.GetRequiredService

⚠ Common mistakes

  • Mistake: Raising the memory limit or scheduling restarts. Why it is wrong: It hides the leak and turns it into a scheduled outage that returns as traffic grows. Instead: Find the retention path and fix the owner.
  • Mistake: Taking a single dump and guessing from the biggest type. Why it is wrong: Large but stable types (caches, pools) look suspicious and aren't leaks. Instead: Diff two gcdumps taken apart and chase the type whose count grows.
  • Mistake: Assuming ValidateScopes would have caught any DI leak. Why it is wrong: Resolving transient disposables from the root is legal and invisible to validation. Instead: Ban root-provider access outside composition code and run a soak test.
  • Mistake: Calling GC.Collect() in production to "free memory". Why it is wrong: Rooted objects are not collectable; you only add pauses. Instead: Remove the root.
  • Mistake: Taking a full dotnet-dump from a production pod without considering data. Why it is wrong: It contains request data and possibly personal information, which is a privacy and storage risk. Instead: Prefer dotnet-gcdump (graph only); handle full dumps under your data-handling policy.
  • Mistake: Fixing by making the transient a singleton. Why it is wrong: Shared mutable or non-thread-safe resources now break under concurrency. Instead: Keep it per-operation and own its disposal.

🏛 Senior insight: trade-offs

DI memory leaks are ownership bugs: the container is doing exactly what it promised (keep it until I can dispose it) for an owner that never dies. The senior instinct is to ask "what is the lifetime of the thing holding this?" rather than "what lifetime did we register?". I also push the team to treat memory as a tested property: a short soak test in CI and a working-set slope alert catch this class of bug long before an OOM.

Fix When it fits Cost When not to
Resolve inside a short scope Several scoped services per operation Scope allocation Hot loops where a factory is simpler
Factory + using One disposable per call from a singleton Caller must dispose Shared expensive resource (pool it instead)
Pool (ObjectPool<T>) Expensive, reusable, resettable objects Reset logic, pool sizing Objects with per-use state you can't reset
Bounded cache Singleton caches Eviction tuning Data that must never be evicted (use a store)
Restart schedule Never as a fix; only as short-term mitigation Hidden leak Always

Measure before and after with the same load profile: gen-2 size, working set and allocation rate over hours, not minutes.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the container tracking disposables Why: Checks the full disposal rules per lifetime and async disposal
    How to answer

    The container owns and disposes what it creates. Each scope keeps a list of the IDisposable/IAsyncDisposable objects it built (scoped and transient) and disposes them, in reverse creation order, when the scope ends; singletons are disposed when the root provider is disposed at host shutdown. Instances you pass in with AddSingleton(instance) are not disposed by the container.

    The trap: a transient disposable resolved from the root is tracked by the root, so it lives until shutdown, which is a memory leak if it happens per request. For async: disposing a scope with DisposeAsync calls DisposeAsync on services; calling synchronous Dispose on a scope that holds a service implementing only IAsyncDisposable throws. So use CreateAsyncScope() with await using, and never dispose injected services yourself.

  2. When: Candidate mentions OOMKilled pods or working set versus GC heap Why: Checks container memory accounting beyond the managed heap
    How to answer

    RAM is physical memory. Each process gets a virtual address space that the OS maps onto RAM page by page. The working set is what's resident in RAM right now; private (committed) memory is what the process owns. The GC heap is only one part: native allocations (native libraries, NativeMemory, unmanaged buffers), thread stacks, JIT code, and runtime structures add to it. In Kubernetes, the cgroup limit counts all of it, and going over gets the container OOMKilled (exit code 137), not an OutOfMemoryException. So if the GC heap is small but the pod dies, I compare GC heap size with working set in dotnet-counters. A big gap points to native memory or too many threads; a growing GC heap points to a managed leak I'd chase with dotnet-gcdump. Then I fix the cause and set limits and GC settings deliberately.

  3. When: Candidate mentions taking a dump in production Why: Checks dump capture and analysis skills
    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.

🛠 Real-world problems: how you handle them

Root-tracked transient renderers OOM-killed a document API every two days
Situation
[Document generation API on AKS in Australia Southeast, 6 pods, 1 GiB memory limit, ~30,000 reports a day for [a government client]].
Signals
Kubernetes OOMKilled events every [~2 days] per pod; Azure Monitor working-set graph a steady upward slope; dotnet-counters showed gen-2 size climbing and never dropping after Gen2 GCs; growth tracked report volume, not time.
Investigation
Confirmed managed growth with dotnet-counters. Took two dotnet-gcdumps one hour apart on the same pod and diffed in Visual Studio: PdfRenderer count grew by [~4,000] with a retention path ServiceProvider → ServiceProviderEngineScope (root) → disposables. Searched for GetRequiredService<PdfRenderer> and found a static ReportHelper using app.Services. ValidateScopes was on and had not flagged it, as expected.
Resolution
Mitigation: increased the memory limit to 1.5 GiB for a week. Fix: replaced the static helper with an injected IPdfRendererFactory whose renderers are created by our code and disposed with using; removed the static IServiceProvider entirely.
Prevention
BannedApiAnalyzers rule forbidding static IServiceProvider holders and app.Services outside Program.cs; a CI soak test rendering 10,000 reports with a heap-growth assertion; an Azure Monitor alert on working-set slope above [20 MB an hour] sustained for 6 hours.

How to tell it (STAR)

**S:** At [company], our document API's pods were OOM-killed every [couple of days], which had become [a recurring on-call page and a nightly restart job]. **T:** I took on finding the actual leak. **A:** dotnet-counters showed managed heap growth that tracked report volume. I took two gcdumps an hour apart; the diff showed thousands more renderer objects, all held by the root service provider's disposables list. A static helper resolved this transient disposable from the root on every report, so the container kept each one until shutdown. I replaced it with a factory and using, banned root-provider access with an analyser rule, and added a soak test to CI. **R:** Memory flattened at [about 350 MB per pod], OOM kills went from [3–4 a week] to zero, and we deleted the nightly restart.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me