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

📚 Interview question

Tell me about a memory leak you found in production. What were the symptoms, how did you prove it was a leak and find the root that held the memory, how did you keep the service up meanwhile, and what stopped it happening again?

A STAR story for a production memory leak: recognising leak versus normal growth, capturing gcdumps or dumps, diffing heaps to the GC root, mitigation, the fix and prevention.

Senior RealWorldScenario Advanced dotnet-dump dotnet-gcdump garbage-collection memory-leak real-world star-story

🎯 Key points

  • Symptom: Gen 2 / LOH grows after every full GC and never returns; OOM or restarts
  • Read GC metrics in context: .NET 10 server GC with DATAS and container limits changes what normal looks like
  • Distinguished a managed leak from native growth or an unbounded cache
  • Captured two gcdumps some time apart and diffed them (Visual Studio, PerfView)
  • Followed the GC root path (gcroot) to the holder: static, event, cache, timer
  • Used allocation profiling (Visual Studio .NET Object Allocation, PerfView, dotnet-trace gc-verbose) to see who allocates
  • Mitigated with limits or graceful restarts; dumps handled as sensitive data
  • Fix plus soak test and Gen 2 growth alert; numbers before and after

⏱ 30-second answer

I tell it in five beats. Symptom: memory on [service] grew about [X MB/hour] and pods were OOMKilled every [N hours]. Prove it's a leak: dotnet-counters showed Gen 2 and heap size rising after every full GC, so it was live objects, not garbage. Find the holder: two dotnet-gcdump snapshots an hour apart; the diff showed [millions of X objects], and gcroot in dotnet-dump led to [a static event handler / an unbounded MemoryCache / a per-request HttpClient]. Mitigate: raised the memory limit and scheduled restarts while fixing. Prevent: a fix, a soak test in CI and an alert on Gen 2 growth. Result: [restarts from N a day to zero]. The trade-off: full dumps are the most complete evidence but pause the process and can hold personal data, so gcdumps come first.

🗣 Full answer (senior)

How I would answer this in an interview

"At [company] our [pricing service] ran on [AKS] with a [1 GiB] memory limit. After the [version] release, pods were being OOMKilled roughly every [six] hours, and each restart dropped in-flight requests. Restarts kept it alive, so nobody had chased it.

I started with dotnet-counters: GC heap size and Gen 2 size climbed steadily and didn't come back down after Gen 2 collections, so this was live managed memory, not just a lazy GC. I took two dotnet-gcdump snapshots, one at [30 minutes] and one at [three hours] after start, and compared them in Visual Studio. The biggest growth was [PriceChangedEventArgs] and closures, about [400,000] more. A full dump with dotnet-dump and gcroot on a few of them showed the path: a singleton PriceFeed had a public event, and a scoped QuoteCalculator subscribed to it in its constructor and never unsubscribed. Every request created a calculator, and the singleton's event held all of them for ever.

While fixing it I raised the limit to [1.5 GiB] so restarts dropped to once a day. The fix was to stop scoped objects subscribing to singleton events; we changed it to a Channel read by one hosted service. I added a soak test that runs [20,000] requests and asserts Gen 2 size stays under a threshold, and an alert on working set growth per hour. Restarts went from [four] a day to none in [three] months. The lesson I took away is that a leak in .NET is almost always a reference you forgot about, and the GC root path tells you exactly which one."


Leak or not?

Pattern What it means Next step
Heap rises then drops after Gen 2 GC Normal; GC is lazy with available memory Nothing; maybe tune GCHeapHardLimit / container limit
Gen 2 / LOH grows after every full GC Managed leak: live objects accumulate gcdump diff, gcroot
Working set grows, managed heap flat Native leak or unmanaged buffers (e.g. undisposed native handles, Marshal.AllocHGlobal) dotnet-dump !eeheap, native tools, check handle counts
Grows to a plateau and stays Cache warm-up Confirm cache has a size limit
LOH growth with fragmentation Large arrays or strings allocated repeatedly ArrayPool<T>, avoid big strings

Usual roots of a .NET leak

Root Example
Event subscription from short-lived to long-lived object Scoped service subscribes to singleton event
Static collection static Dictionary<string, X> used as a cache
Unbounded cache MemoryCache without SizeLimit, or keys with high cardinality
Timers System.Threading.Timer capturing this, never disposed
Captive dependency Singleton holding a scoped DbContext that keeps tracking entities
HttpClient per request Sockets and handlers piling up (also port exhaustion)
Undisposed IServiceScope Created manually and never disposed; scoped disposables pile up

Production example

Template: [pricing service], OOMKilled every [6] hours at a [1 GiB] limit; gcdump diff showed [+400,000] event-args objects per [3] hours; root was a singleton event holding scoped subscribers; after the fix Gen 2 stayed flat at [180 MB] and restarts went from [4/day] to 0.

🔍 What the interviewer is checking

Checks whether you understand how the GC decides what is alive and have a reliable method to go from symptom to the exact root, while keeping production up and evidence safe.

Green flags

  • Proves it's a leak with Gen 2 trends, not just "memory was high"
  • Uses snapshot diffs and a GC root path to name the holder
  • Mentions mitigation and secure handling of dumps
  • Adds a soak test or alert and gives numbers

Red flags

  • GC.Collect() or "more memory" as the fix
  • Can't explain why the object stayed alive
  • No measurable outcome
  • Vague "we" story with no personal action

📚 Learn in depth

1. What the interviewer is really assessing

A memory-leak story checks whether you understand how the .NET GC decides what is alive (reachability from roots) and whether you have a repeatable method rather than guessing. It also checks operational maturity: did you keep the service up, and did you protect the evidence (and the personal data in it).

2. How a leak happens in a garbage-collected runtime

The GC frees objects that are unreachable from roots: statics, thread stacks, GC handles and the finalisation queue. A "leak" is just objects that are still reachable but no longer useful.

[static PriceFeed singleton]
        |
        v  PriceChanged event (delegate invocation list)
   [QuoteCalculator #1] -> [captured state, buffers]
   [QuoteCalculator #2] -> ...
   [QuoteCalculator #400000] -> ...

Each object survives Gen 0 and Gen 1, gets promoted to Gen 2, and Gen 2 grows until the container limit is hit. With server GC in a container, .NET honours the cgroup limit (by default the GC heap hard limit is 75% of it), so you see OutOfMemoryException or the kernel OOM killer.

3. The evidence chain

  1. dotnet-counters (gc-heap-size, gen-2-size, loh-size, time-in-gc): proves the trend is in managed memory.
  2. dotnet-gcdump collect -p twice: a lightweight heap graph (types, counts, sizes) without personal data values; diff them to see what grew.
  3. dotnet-dump collect and dumpheap -stat, dumpheap -mt <MT>, gcroot <address>: shows the exact path from a root to the leaked object.
  4. In Kubernetes, dotnet-monitor as a sidecar can trigger a dump on a memory threshold so you don't race the OOM killer.

Full dumps contain everything in memory, including tokens and customer data. Treat them as sensitive: store them in a restricted location, delete them after the investigation, and under the Privacy Act 1988 treat personal information in them like production data.

4. Frameworks for telling it

Use STAR with the action split into the three steps above (prove, find, fix). If the interesting part was that restarts had hidden the leak for months, SOAR works well: the obstacle is "nobody had evidence because restarts wiped it".

5. How it is scored

Weak: "memory was high, we restarted and added more memory." Good: names counters and dumps. Strong: explains the root path and the mechanism. Excellent: adds a soak test or alert and quantifies the outcome, and mentions handling of dump data.

6. Adapting the story

The same story answers "hardest bug you've fixed", "a time you went deep on something", and "a time you improved reliability". For a non-technical interviewer, compress the evidence chain to one sentence: "I took snapshots of memory an hour apart, compared them, and traced the growth back to one line of code."

Try it yourself

  1. Write a small console app where a short-lived object subscribes to a static event in a loop; watch it with dotnet-counters monitor.
  2. Take two dotnet-gcdump snapshots and open the diff in Visual Studio or PerfView.
  3. Take a full dotnet-dump, run dumpheap -stat, pick an object and run gcroot to see the event handler path.
  4. Fix it with unsubscribe or a weak pattern and confirm Gen 2 stays flat.
  5. Write your STAR version and time it at 90–120 seconds.

💻 Code

The key fix in this example: a scoped object must not subscribe to a singleton event; a channel decouples them.

namespace Pricing.Services;

// Before (the leak): every scoped QuoteCalculator subscribed in its constructor and
// never unsubscribed, so the singleton's delegate list kept all of them alive.
// public QuoteCalculator(PriceFeed feed) => feed.PriceChanged += OnPriceChanged;

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

// After: one long-lived consumer reads price changes; request-scoped code reads the cache.
public sealed class PriceFeed
{
    private readonly Channel<PriceChanged> _channel =
        Channel.CreateBounded<PriceChanged>(new BoundedChannelOptions(10_000)
        {
            FullMode = BoundedChannelFullMode.DropOldest // prices are superseded anyway
        });

    public ValueTask PublishAsync(PriceChanged change, CancellationToken ct) =>
        _channel.Writer.WriteAsync(change, ct);

    public IAsyncEnumerable<PriceChanged> ReadAllAsync(CancellationToken ct) =>
        _channel.Reader.ReadAllAsync(ct);
}

public sealed class PriceCacheUpdater(PriceFeed feed, IMemoryCache cache) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var change in feed.ReadAllAsync(stoppingToken))
        {
            cache.Set($"price:{change.Sku}", change.Price,
                new MemoryCacheEntryOptions { Size = 1 }); // cache has SizeLimit set in Program.cs
        }
    }
}
# The evidence chain used in the story
dotnet-counters monitor -p <pid> --counters System.Runtime
dotnet-gcdump collect -p <pid> -o before.gcdump   # ~30 min after start
dotnet-gcdump collect -p <pid> -o after.gcdump    # ~3 h after start; diff in Visual Studio
dotnet-dump collect -p <pid>                       # then: dumpheap -stat, gcroot <addr>
STAR template
S: [Service] on [platform], [memory limit], restarting every [N h] after [release].
T: I [owned / volunteered for] finding the leak without more downtime.
A: Counters showed [Gen 2 growth]; gcdump diff showed [type +N]; gcroot led to [root];
   mitigated with [limit/restarts]; fixed by [change]; added [soak test + alert].
R: [Restarts N/day -> 0]; Gen 2 flat at [X MB] for [period].

Illustrative only: pricing service, 1 GiB limit, OOMKilled every 6 h; singleton event held
scoped calculators; Channel-based fix; restarts 4/day -> 0 over 3 months.

⚠ Common mistakes

  • Mistake: Calling any high memory a leak. Why it is wrong: The GC is lazy; memory that drops after a Gen 2 GC is normal. Instead: Show Gen 2 growing after full collections.
  • Mistake: Calling GC.Collect() as the fix. Why it is wrong: It can't free reachable objects and adds pauses. Instead: Find and remove the reference.
  • Mistake: Taking a full dump first in production without thinking. Why it is wrong: It pauses the process and contains personal data. Instead: Start with counters and gcdumps; handle full dumps as sensitive.
  • Mistake: "We just restarted it nightly." Why it is wrong: That is mitigation, not resolution. Instead: Say restarts bought time while you found the root.
  • Mistake: Rambling through every SOS command. Why it is wrong: The interviewer wants method and outcome. Instead: Name three steps and the one finding that mattered.
  • Mistake: Saying "we" for the whole investigation. Why it is wrong: Your contribution is invisible. Instead: "I took the snapshots, I found the root path."
  • Mistake: No numbers. Why it is wrong: The impact and the fix can't be judged. Instead: Growth rate, restart frequency, memory after the fix.
  • Mistake: Blaming the author of the event subscription. Why it is wrong: Signals blame culture. Instead: Describe the missing guardrail (review rule, soak test).

🏛 Senior insight: trade-offs

The senior version shows you understand reachability (a leak is a forgotten reference with a root path), respect production (mitigate, use the lightest evidence first, treat dumps as sensitive data) and close the class of bug (lifetime rules, soak tests, alerts). Quantify both the cost before (restarts, dropped requests) and the result after.

Read the metrics for the runtime you're on. On .NET 10 the diagnostics tools are still the same family (dotnet-counters, dotnet-gcdump, dotnet-dump, dotnet-trace, plus dotnet-monitor for containers), and the runtime now publishes GC metrics through System.Diagnostics.Metrics (meter System.Runtime), so the same numbers appear in OpenTelemetry and Application Insights dashboards. What changed is what normal looks like: since .NET 9, server GC has DATAS (Dynamic Adaptation To Application Sizes) on by default, so the heap grows and shrinks with load rather than staying large, and the GC respects the container memory limit (heap hard limit defaults to 75% of it). A heap that grows under load and shrinks afterwards is DATAS doing its job; a Gen 2 size that rises after every full GC, even at low load, is a leak. For the who allocates question, use an allocation profiler: Visual Studio's .NET Object Allocation tool locally, or PerfView / dotnet-trace with the gc-verbose profile in a test environment.

Evidence When it fits Cost When not to
dotnet-counters / OTel runtime metrics First look, trend Negligible Need object-level detail
dotnet-gcdump Which types grow Brief pause, small file, no values Native leak; need field values
Full dump (dotnet-dump) Root paths, field values Pause, large file, holds personal data Without a plan to secure and delete it
Allocation profiling (VS, PerfView, dotnet-trace) Which code allocates the leaked objects Overhead; best in test Live production at peak
dotnet-monitor trigger Leak outruns humans; K8s Sidecar setup Single quick repro available
Mitigation Trade-off
Raise memory limit Cost; delays OOM but hides the trend
Scheduled restarts Dropped requests unless graceful; masks the bug
Roll back Best if the leak arrived with a release

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions OOMKilled pods or restarts in Kubernetes. Why: Checks the full technical playbook: first five minutes, capturing evidence before restart, managed vs native.
    How to answer

    First I mitigate: the restarts started after Tuesday's release, so I roll back or at least add replicas so the OOMKills don't line up. Then I preserve evidence, because every restart deletes the heap: a dotnet-monitor memory trigger or a scheduled dotnet-gcdump at about 50% and 80% of the container limit. dotnet-counters tells me which kind of growth it is: a rising GC heap and gen 2 means a managed leak; a rising working set with a flat GC heap means native memory (unmanaged buffers, a native library, too many threads). For a managed leak I diff two dumps, find the type whose count only grows, and run gcroot to see who holds it. The fix is the root, not a bigger limit. The trade-off: rolling back buys time but can hide the evidence, so capture first if it's safe.

  2. When: Candidate says working set grew but doesn't mention the managed heap. Why: Checks they can separate GC heap growth from unmanaged allocations.
    How to answer

    Compare the managed heap with the process memory. dotnet-counters gives gc-heap-size and working-set; if both rise together, it's a managed leak: diff two dotnet-gcdump snapshots and follow gcroot in dotnet-dump. If the working set (or private/committed memory) climbs while the GC heap stays flat, the growth is native: undisposed native handles, unmanaged buffers (NativeMemory, Marshal.AllocHGlobal), a native library, or many thread stacks. In a dump, !eeheap -gc only covers the managed heap; for native use !maddress -summary (address-space breakdown), watch handle and thread counts (/proc/<pid>/fd, Task Manager, !threads), and use native profilers (WinDbg/!heap on Windows, heaptrack or valgrind on Linux). Also watch the effect: rising memory usually shows up as more GC time and higher p99 before the OOM.

🛠 Real-world problems: how you handle them

Singleton event keeps every scoped calculator alive
Situation
[Pricing service] on [AKS], [3] pods with a [1 GiB] memory limit, serving [quote requests for the web shop]. Since release [version] pods were OOMKilled every [~6] hours; each restart dropped in-flight requests and caused [5xx spikes] for checkout.
Signals
Kubernetes events `OOMKilled`; restart count climbing; Azure Monitor container insights showing a saw-tooth working set that rose roughly [150 MB/hour]; a small burst of 502s at each restart; no CPU or latency change until near the limit.
Investigation
dotnet-counters: `gen-2-size` and `gc-heap-size` rose after every Gen 2 GC, so live managed objects (ruled out native growth and lazy GC). Ruled out the new Redis client because the growth also happened with Redis disabled in a staging soak. Two `dotnet-gcdump` snapshots [2.5] hours apart: `QuoteCalculator`, closures and `PriceChangedEventArgs` up by ~[400,000]. A full dump (stored in a restricted storage account, deleted after) with `gcroot` showed the path: static `PriceFeed` singleton -> `PriceChanged` delegate list -> `QuoteCalculator` instances. The release had added a subscription in the scoped calculator's constructor with no unsubscribe.
Resolution
Mitigation: raised the memory limit to [1.5 GiB] so restarts dropped to about once a day, and confirmed the rolling restarts were graceful. Real fix: removed the subscription; price changes now flow through a bounded `Channel` read by a single `BackgroundService` that updates a size-limited `IMemoryCache`, and scoped code reads the cache.
Prevention
A soak test in CI ([20,000] requests) asserting Gen 2 size stays under [250 MB]; an alert on working set growth per hour; a code-review rule (and a custom analyser [if built]) against scoped services subscribing to singleton events; dotnet-monitor sidecar configured to capture a gcdump at [80%] of the limit.

How to tell it (STAR)

**S:** At [company], our [pricing service] on [AKS] was being OOMKilled every [six] hours after a release, and each restart caused a burst of checkout errors. **T:** I [took ownership of] finding the cause without adding more downtime. **A:** dotnet-counters showed Gen 2 growing after every full collection, so it was a real managed leak. I took two gcdumps a couple of hours apart, saw [400,000] extra calculator objects, and used gcroot on a full dump to find the path: a singleton's event was holding every scoped calculator. I raised the memory limit to buy time, replaced the event with a bounded channel and one background consumer, and added a soak test and a growth alert. **R:** Gen 2 stayed flat at about [180 MB], restarts went from [four] a day to zero over [three] months, and the checkout error bursts stopped.

More in Production Incidents

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me