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.
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.
"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 monitorI watchgc-heap-size, the generation sizes andgc-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 twodotnet-gcdumpsnapshots an hour apart, open them in Visual Studio or PerfView, and diff them. The type whose count only goes up is my suspect. Thendotnet-dump analyzewithdumpheap -stat,dumpheap -mtandgcrooton 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."
| 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 |
| 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) |
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 |
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.
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
Red flags
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
.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.
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)
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.
Three ways, from least to most automated:
kubectl exec into the pod (or an ephemeral debug container sharing the process namespace) and run dotnet-gcdump collect -p 1.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).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.
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.
List<byte[]> that grows on every request; run it in Docker with --memory=512m and watch it get killed with exit code 137.dotnet-counters monitor -p <pid> --counters System.Runtime while you hit it with bombardier or k6, and note which counters move.dotnet-gcdump collect snapshots five minutes apart and diff them in Visual Studio.dumpheap -stat, then gcroot <address> on one of the growing objects.IMemoryCache and a SizeLimit, rerun the load and confirm the gen 2 floor stays flat.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>
gc-heap-size side by side.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.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.