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.
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.
"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 andgcrooton a few of them showed the path: a singletonPriceFeedhad a public event, and a scopedQuoteCalculatorsubscribed 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
Channelread 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."
| 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 |
| 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 |
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.
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
Red flags
GC.Collect() or "more memory" as the fixA 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).
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.
gc-heap-size, gen-2-size, loh-size, time-in-gc): proves the trend is in managed memory.dumpheap -stat, dumpheap -mt <MT>, gcroot <address>: shows the exact path from a root to the leaked object.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.
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".
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.
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."
dotnet-counters monitor.dotnet-gcdump snapshots and open the diff in Visual Studio or PerfView.dotnet-dump, run dumpheap -stat, pick an object and run gcroot to see the event handler path.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.
GC.Collect() as the fix. Why it is wrong: It can't free reachable objects and adds pauses. Instead: Find and remove the reference.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 |
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.
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.
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.
Last updated 23 Nov 2026.