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

📚 Interview question

It's 2 am and the alert says your order API pods are being OOMKilled and restarted every three hours, starting the day after Tuesday's release. Walk me through your playbook: what you do in the first five minutes, how you capture evidence before the next restart wipes it, how you tell a managed leak from native memory growth, and how you get from dump diffs to the leaking root and a fix.

A production playbook for a memory leak that ends in OOMKilled restarts: mitigation, evidence capture with dotnet-counters, dotnet-monitor and dotnet-gcdump, managed versus native growth, dump diffing with gcroot, the fix and prevention.

Mid-Level Debugging Intermediate dotnet-gcdump dotnet-monitor kubernetes memory-leak oomkilled production

🎯 Key points

  • Mitigate first: roll back Tuesday's release or add replicas and stagger restarts; don't debug a fire
  • Read container_memory_working_set_bytes against the limit and the restart reason (OOMKilled, exit 137)
  • dotnet-counters: gc-heap-size and gen-2 size rising means managed; working set rising with a flat GC heap means native
  • Capture before the restart: dotnet-monitor memory trigger or a CronJob running dotnet-gcdump at 50% and 80% of the limit
  • Diff two gcdumps (or dumpheap -stat on two full dumps) and find the type whose count only grows
  • gcroot on a sample instance to find the root: static collection, event handler, captured singleton, unbounded cache
  • Fix the root (bounded cache, unsubscribe, correct lifetime) and verify with a soak test showing a flat gen-2 after full GCs
  • Keep an incident log and post regular status updates; prevent recurrence with an 80% memory alert and a soak test stage

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The first five minutes are about the customers, not the leak. The pods restart every three hours and it started after Tuesday's release, so the cheapest mitigation is a rollback. Before I do that, I check whether I can grab evidence from a pod that's already at 70–80% of its limit, because once I roll back the leak may never show again and I'll be guessing. If capturing takes more than a few minutes, I roll back anyway and reproduce the leak in staging with the bad build. While that happens I start an incident log with timestamps and post a short status update in the incident channel, so support knows checkouts may fail at each restart.

Then I work out what kind of memory is growing. Kubernetes counts the container's working set, not the GC heap. With dotnet-counters monitor I watch gc-heap-size, the generation sizes and gc-committed. If the GC heap and gen 2 climb with the working set, it's a managed leak: something is keeping objects reachable. If the working set climbs but the GC heap is flat, it's native: unmanaged buffers, a native library, thread stacks, or memory-mapped files, and I need a full dump or native tools rather than a gcdump. For a managed leak I take two dotnet-gcdump snapshots an hour apart, open them in Visual Studio or PerfView, and diff them. The type whose count only goes up is my suspect. Then dotnet-dump analyze with dumpheap -stat, dumpheap -mt and gcroot on one instance shows me the chain that keeps it alive: usually a static dictionary used as a cache, an event handler on a singleton that nobody unsubscribes, or a scoped service captured by a singleton.

The mistake I see is raising the memory limit and calling it fixed. That just makes the restarts happen every six hours instead of three. A leak is fixed when a soak test shows gen 2 going flat after full collections."


The playbook, in order

Step What I do Tool or command
1. Symptom Confirm OOMKilled, not a crash kubectl describe pod → Last State: Terminated, Reason: OOMKilled, Exit Code: 137
2. First five minutes Roll back, or scale out and stagger restarts; open the incident log Deployment history, kubectl rollout undo, incident channel
3. Data to collect Counters, then gcdumps before the limit dotnet-counters, dotnet-gcdump collect, dotnet-monitor trigger
4. Rule out Not load: request rate flat while memory grows. Not cache warm-up: it never plateaus App Insights requests vs container memory chart
5. Root cause Diff dumps, gcroot on the growing type PerfView diff, dotnet-dump analyze
6. Fix Remove the root; bound the cache; fix the lifetime Code change + soak test
7. Prevention Alert at 80% of limit, soak test, memory budget Azure Monitor alert, load test stage

Managed or native?

Signal Managed leak Native growth
gc-heap-size Climbs with working set Flat
Gen 2 after a full GC Never comes back down Normal
Best evidence dotnet-gcdump (small, heap graph only) Full dump (dotnet-dump collect --type Full), maddress in SOS
Usual causes Static collections, event handlers, captured scopes, unbounded IMemoryCache Undisposed native handles, Marshal.AllocHGlobal, image libraries, thousands of threads (1 MB stack each)

What the leak usually turns out to be

Root in gcroot output Cause Fix
static Dictionary<,> Hand-rolled cache with no eviction IMemoryCache with SizeLimit, or HybridCache
Singleton's event delegate list Subscriber never unsubscribes Unsubscribe in Dispose, or use weak events
ServiceProviderEngineScope Scopes created and never disposed using var scope = ... / await using
System.Threading.TimerQueue Timer holds a closure over a big object Dispose the timer; don't capture this

Production example

A typical case: a release adds a static ConcurrentDictionary<string, PriceResult> keyed by customer and basket hash. Each pod gains roughly 1.5 GB in three hours against a 2 GiB limit and is OOMKilled about eight times a day across six pods. Rolling back stops it; the gcdump diff shows PriceResult count going from 40,000 to 2.1 million, and gcroot points at the static. Replacing it with a size-limited IMemoryCache (100 MB budget, 10-minute expiry) keeps the working set flat at about 600 MB through a 12-hour soak.

🔍 What the interviewer is checking

Checks that the candidate can run a memory incident end to end under pressure: mitigate first, preserve evidence, distinguish managed from native memory, and use dump diffs and gcroot to find a real root.

Green flags

  • Mitigates before investigating and links the timing to the release
  • Knows Kubernetes kills on working set and that exit code 137 means OOMKilled
  • Distinguishes GC heap growth from native growth with dotnet-counters
  • Uses gcdump diffs by count and gcroot to name the root
  • Verifies with a soak test, and mentions dump handling as sensitive data

Red flags

  • "Increase the memory limit" or "call GC.Collect" as the answer
  • No idea how to capture evidence before the restart
  • Treats every memory increase as a leak, ignoring caches that plateau

📚 Learn in depth

1. What Kubernetes actually kills you for

The kubelet compares the container's working set (container_memory_working_set_bytes, roughly RSS plus active page cache) against resources.limits.memory. When the cgroup exceeds the limit, the kernel OOM killer ends the process with SIGKILL, exit code 137. Nothing in .NET runs: no finally, no flush of logs, no graceful shutdown. That's why you capture evidence before the limit.

process memory (working set)
├── GC heap (gen0, gen1, gen2, LOH, POH)   ← dotnet-gcdump sees this
├── GC bookkeeping, JIT code, type metadata
├── thread stacks (1 MB reserved each, committed as used)
├── native allocations (libraries, Marshal, SafeHandle targets)
└── memory-mapped files, page cache attributed to the cgroup

2. How the .NET GC sees the container

.NET reads the cgroup limit and sets the GC's hard limit to 75% of the container limit by default (GCHeapHardLimitPercent). Since .NET 9, Server GC uses DATAS (dynamic adaptation) by default, so the heap grows and shrinks with load instead of reserving per-core heaps up front. A leak still wins in the end: once live objects exceed the hard limit you get an OutOfMemoryException from the GC, or the OOM killer if native memory pushes the total over first.

3. Why a leak in .NET is about reachability

The GC frees anything unreachable from a root: statics, thread stacks, GC handles (including pinned and strong handles), and the finaliser queue. A managed leak is always an object graph you didn't mean to keep reachable. gcroot walks backwards from an instance to the root, so its output is the answer to "who is keeping this alive?".

Root: static field Pricing.Cache._entries
  -> ConcurrentDictionary<string, PriceResult>
    -> Node[]
      -> PriceResult  (2.1 million of these)

4. gcdump versus full dump

dotnet-gcdump dotnet-dump --type Full
Content Heap object graph only (types, counts, references) Entire process memory
Size Tens of MB Roughly the working set (GBs)
Pause Triggers a gen 2 GC Suspends the process while writing
PII risk Low: no field values High: every string, token and connection string in memory
Answers Which types grow and who roots them Everything, including native memory and thread stacks

For the first pass I use gcdumps. I take a full dump only when the GC heap is flat (native growth) or I need field values, and then I treat it as sensitive data under the Privacy Act: stored encrypted, access-controlled and deleted after the investigation.

5. Capturing at the right moment

Three ways, from least to most automated:

  1. Manual: kubectl exec into the pod (or an ephemeral debug container sharing the process namespace) and run dotnet-gcdump collect -p 1.
  2. Scheduled: a small job that collects a gcdump every 30 minutes and uploads it to Blob Storage.
  3. Triggered: dotnet-monitor as a sidecar with a collection rule: when gc-heap-size exceeds a threshold, collect a gcdump and egress it to Blob Storage. dotnet-monitor 10.x is published for .NET 10; it exposes an HTTP API, so lock it down (authentication on, listening on localhost or a private port only).

6. Diffing

Open both gcdumps in Visual Studio ("Compare with baseline") or PerfView. Sort by count difference first, not size: a leak of small objects shows in counts long before it dominates bytes. Ignore types that are just big (byte arrays from a buffer pool); look for your domain types and for collections whose element counts grow.

7. Verifying the fix

Run a soak test (k6 or Azure Load Testing) at production-like rate for several hours and plot gen 2 size after each full GC. A fixed leak looks like a sawtooth with a flat floor. A leak looks like a rising floor.

Try it yourself

  1. Write a minimal API with a static List<byte[]> that grows on every request; run it in Docker with --memory=512m and watch it get killed with exit code 137.
  2. Run dotnet-counters monitor -p <pid> --counters System.Runtime while you hit it with bombardier or k6, and note which counters move.
  3. Take two dotnet-gcdump collect snapshots five minutes apart and diff them in Visual Studio.
  4. Take a full dump and run dumpheap -stat, then gcroot <address> on one of the growing objects.
  5. Fix it with IMemoryCache and a SizeLimit, rerun the load and confirm the gen 2 floor stays flat.
  6. Add a dotnet-monitor sidecar with a collection rule that captures a gcdump when the heap passes 300 MB.

💻 Code

A leak that looks harmless in review, and the bounded fix.

// Before: a static cache with no eviction. Every distinct basket hash stays forever.
namespace Orders.Pricing;

public sealed class PriceCalculator(IPricingClient client)
{
    private static readonly ConcurrentDictionary<string, PriceResult> Cache = new(); // leaks

    public async Task<PriceResult> GetAsync(string customerId, string basketHash, CancellationToken ct)
    {
        var key = $"{customerId}:{basketHash}";
        if (Cache.TryGetValue(key, out var cached)) return cached;
        var result = await client.PriceAsync(customerId, basketHash, ct);
        Cache[key] = result; // grows with every unique basket
        return result;
    }
}
// After: a bounded, expiring cache. Size and expiry are explicit, so memory has a ceiling.
namespace Orders.Pricing;

using Microsoft.Extensions.Caching.Memory;

public sealed record PriceResult(decimal Total, string Currency);

public sealed class PriceCalculator(IPricingClient client, IMemoryCache cache)
{
    public async Task<PriceResult> GetAsync(string customerId, string basketHash, CancellationToken ct)
    {
        var key = $"price:{customerId}:{basketHash}";
        return (await cache.GetOrCreateAsync(key, async entry =>
        {
            entry.Size = 1;                                      // counts against SizeLimit
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
            return await client.PriceAsync(customerId, basketHash, ct);
        }))!;
    }
}

// Program.cs
// builder.Services.AddMemoryCache(o => o.SizeLimit = 50_000); // entries, not bytes: pick a unit and stick to it
# Evidence capture, in the order you'd run it
kubectl describe pod orders-api-7d9f -n prod | grep -A3 'Last State'
kubectl debug -it orders-api-7d9f -n prod --image=mcr.microsoft.com/dotnet/sdk:10.0 --target=orders-api -- bash
dotnet tool install -g dotnet-counters dotnet-gcdump dotnet-dump
dotnet-counters monitor -p 1 --counters System.Runtime
dotnet-gcdump collect -p 1 -o /tmp/heap-1.gcdump   # again 30-60 minutes later
dotnet-dump analyze core.dmp                        # then: dumpheap -stat, dumpheap -mt <MT>, gcroot <addr>

⚠ Common mistakes

  • Mistake: Raising the memory limit and closing the incident. Why it is wrong: A leak grows without bound; a bigger limit only stretches the restart interval and costs more. Instead: Use the extra headroom to buy time while you find the root.
  • Mistake: Rolling back before capturing anything. Why it is wrong: If the leak doesn't reproduce in staging you have nothing to analyse. Instead: Grab one gcdump from a pod already at 70–80% if it takes minutes, then roll back.
  • Mistake: Taking a full dump when a gcdump would do. Why it is wrong: Full dumps are gigabytes, pause the process and contain tokens and personal data. Instead: Start with gcdumps; take a full dump only for native growth or when you need field values, and handle it as sensitive data.
  • Mistake: Looking at GC heap size alone. Why it is wrong: The OOM killer uses the container working set; native growth never shows in the GC heap. Instead: Compare working set and gc-heap-size side by side.
  • Mistake: Sorting the dump diff by size. Why it is wrong: Big buffers dominate bytes and hide a growing count of small domain objects. Instead: Sort by count difference first.
  • Mistake: Calling GC.Collect() in code to "fix" it. Why it is wrong: Reachable objects can't be collected; you just add pauses. Instead: Remove the reference that keeps them alive.
  • Mistake: Declaring victory after an hour. Why it is wrong: Leaks often grow with unique keys or time; an hour can look flat. Instead: Soak for several hours at production-like rate and check the gen 2 floor.

🏛 Senior insight: trade-offs

The senior move is to separate the incident from the investigation. The incident ends when customers stop seeing errors, usually via rollback. The investigation ends when you can name the root and show a flat soak test. Keeping those apart stops people debugging under pressure and stops the team closing the ticket when the restarts merely become less frequent.

The other senior habit is making the next one cheap: a dotnet-monitor trigger or scheduled gcdump that is already deployed means evidence exists before anyone is paged.

Option When it fits Cost When not to
Roll back Clear correlation with a release Minutes; delays the feature When the release carries a data migration you can't undo
Scale out and stagger restarts Unclear cause, need time More pods, more spend When the leak is fast enough that every pod dies within minutes
Raise the limit temporarily Buying hours to capture evidence Higher node cost As the fix
dotnet-monitor sidecar with triggers Repeat offenders, Kubernetes A second container, an endpoint to secure Tiny services where a scheduled gcdump is enough

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions diffing gcdump snapshots Why: Checks hands-on use of dotnet-counters and gcdump diffing in more detail
    How to 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.

  2. When: Candidate says 'then I find the leak' Why: Checks the step-by-step leak investigation internals
    How to answer

    First confirm a leak: memory keeps rising across GCs under steady load, rather than a cache warming up. Then decide managed or native: if the GC heap size (dotnet-counters) grows with the working set, it is managed; if the working set grows while the GC heap is flat, look at native memory. For managed leaks, take two dotnet-gcdump snapshots some time apart and compare which types grow, then use dotnet-dump with dumpheap -stat and gcroot to find what keeps them alive. Typical roots: static collections and caches, event subscriptions, timers, captured closures, DI root-scoped transients, and unbounded queues. Fix, then verify with the same metrics under load.

  3. When: Candidate says the GC heap looks small but the pod still dies Why: Checks understanding of working set, private bytes and native memory in containers
    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.

🛠 Real-world problems: how you handle them

OOMKilled every three hours after a pricing release
Situation
An order API on AKS in Australia East, [six] pods with a [2 GiB] limit serving [about 400 requests/s] at peak. A release on [Tuesday] added basket price caching. From the next morning pods were OOMKilled roughly every three hours, and in-flight checkouts failed each time.
Signals
Azure Monitor container insights showed working set climbing in a straight line to the limit, then dropping to zero. `kubectl get pods` showed restart counts rising; `kubectl describe` reported OOMKilled with exit code 137. Application Insights showed bursts of 502s from the ingress at each restart and a [1.5%] checkout failure rate.
Investigation
Correlated the start with the release in the deployment history. Ran `dotnet-counters monitor` in an ephemeral debug container: `gc-heap-size` and gen 2 climbed with the working set, so it was managed. Took two `dotnet-gcdump` snapshots 45 minutes apart and diffed them in Visual Studio: `PriceResult` and `ConcurrentDictionary` nodes grew by millions. `gcroot` on one instance from a full dump pointed to a static field in `PriceCalculator`.
Resolution
Immediate: rolled back the release, which stopped the restarts within the hour. Real fix: replaced the static dictionary with a size-limited `IMemoryCache` with a 10-minute expiry, then redeployed behind a canary.
Prevention
Added a container memory alert at 80% of the limit, a four-hour soak test stage in the release pipeline that fails if the gen 2 floor rises, a dotnet-monitor collection rule that captures a gcdump at a heap threshold, and a code review checklist item: no static mutable collections without a bound.

How to tell it (STAR)

**S:** At [company], our order API on AKS started getting OOMKilled every three hours the day after a release, and every restart failed in-flight checkouts. **T:** I was on call, so I owned mitigation and finding the cause. **A:** I grabbed a gcdump from a pod at about 75% of its limit, then rolled back, which stopped the restarts. dotnet-counters showed the GC heap growing, so it was managed. I diffed two gcdumps and found millions of `PriceResult` objects, and `gcroot` pointed at a static dictionary the release added as a cache. We replaced it with a size-limited `IMemoryCache` and added a soak test stage. **R:** Restarts went from [eight a day] to zero, the working set stayed flat at [about 600 MB] over a 12-hour soak, and the soak test has since caught [one more] leak before production.

↩ Usually asked after

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me