Diagnosing managed memory growth in .NET 10: confirming it with GC counters, comparing dotnet-gcdump snapshots in Visual Studio or PerfView, reading retention paths to the GC root, common leak roots (static caches, events, DI scopes, timers), and verifying the fix.
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.
"I start by checking that it really is a leak and what kind. In dotnet-counters I watch
gc-heap-size,gen-2-gc-countand the working set. A high number on its own isn't a leak; the GC is lazy with Server GC and plenty of memory. A leak is the heap after each Gen 2 collection climbing under steady load. If the working set grows but the GC heap stays flat, it's native memory, such as unmanaged buffers, and that's a dump-and-native-tools job instead.For managed growth I take dotnet-gcdump snapshots, normally three, ten minutes apart, while traffic is steady. A gcdump is the heap graph: types, counts, sizes and references, without field values, so it's small and safe to move around. I open them in Visual Studio, choose 'compare with baseline', and sort by size difference. For example, at [company] [the diff showed 1.4 million new
PriceQuoteobjects per hour], and the paths-to-root view showed them held by a staticConcurrentDictionaryused as a cache with no eviction. The fix was to replace it withIMemoryCachewith aSizeLimitand expirations, and memory flattened at [600 MB] instead of climbing to the [2 GB] container limit.The mistake I see is people raising the container memory limit or adding a nightly restart. That buys time but the leak is still there, and it usually takes the service down at the worst moment. The other mistake is fixing the type that's big instead of the thing that holds it: the leak is the root, not the objects."
| Step | Tool | What you look for |
|---|---|---|
| 1. Confirm | dotnet-counters |
gc-heap-size and Gen 2 size rising after full GCs; working set vs heap |
| 2. Snapshot | dotnet-gcdump collect × 2–3 |
Same load, minutes apart |
| 3. Diff | Visual Studio / PerfView | Types with growing count and inclusive size |
| 4. Retention | Paths to root / RefTree | The static, handler, timer or scope holding them |
| 5. Fix | Code | Bound, unsubscribe, dispose, scope correctly |
| 6. Verify | Soak test + counters | Heap flat over hours |
| Root | Typical cause | Fix |
|---|---|---|
| Static collection | Dictionary used as a cache | IMemoryCache with SizeLimit, or HybridCache |
| Event handler | Long-lived publisher, short-lived subscriber | Unsubscribe in Dispose, weak events |
Timer / CancellationTokenSource registration |
Not disposed | Dispose; use PeriodicTimer in a BackgroundService |
| DI root scope | Transient IDisposable resolved from root provider |
Create a scope per unit of work |
HttpClient per call / IMemoryCache without limits |
Unbounded growth | IHttpClientFactory; size limits |
| Captured closures | Lambda captures a large object in a long-lived delegate | Capture only what is needed |
A notification service was OOM-killed every 9 hours at its 2 GB limit. Three gcdumps showed Subscription objects growing by 200,000 an hour, rooted through a singleton event PriceChanged that per-request handlers subscribed to and never left. Unsubscribing in Dispose flattened the heap at 450 MB over a 24-hour soak test, and restarts stopped.
Checks that the candidate can run a memory leak investigation methodically and fix the cause rather than the symptom.
Green flags
Red flags
working set ─┬─ managed GC heap (gc-heap-size counter)
│ ├─ Gen0 / Gen1 / Gen2
│ ├─ LOH (>= 85,000 bytes)
│ └─ POH (pinned)
└─ native: runtime, JIT code, thread stacks, unmanaged buffers,
native libraries (SQL client, gRPC, image codecs)
If only the native part grows, gcdump won't help. Use dotnet-dump (and !maddress / eeheap) or native tools.
dotnet-gcdump collect asks the runtime (through EventPipe) to run a full, blocking, compacting GC and emit GCBulkNode and GCBulkEdge events describing every live object, its type and size, and the references between objects. The tool turns that into a graph. There are no field values, so it's tens of MB rather than GB, and it carries little personal data, unlike a full dump. For very large heaps it may sample objects and scale counts.
In Visual Studio (open .gcdump → 'Compare with baseline') or PerfView (Heap Snapshots → 'Diff'):
string and byte[] at first; look for your types whose count rises steadily, then see which framework types hang off them. PriceQuote ◀── Entry<string,PriceQuote>[] ◀── ConcurrentDictionary ◀── static PriceCache._items
(GC root: static)
The GC frees only unreachable objects. A leak in .NET is always something reachable that you no longer need: a collection that only grows, a long-lived object holding a reference to a short-lived one (events, callbacks, CancellationToken.Register), or a scope that is never disposed (IServiceProvider root scope tracks every transient IDisposable it creates).
dotnet-dump: finalizequeue).loh-size and consider GCSettings.LargeObjectHeapCompactionMode or pooling large buffers.Run a soak test (hours, steady load) and plot gc-heap-size and Gen 2 size. A healthy service shows a sawtooth that returns to the same baseline. Add an alert on post-GC heap size trend in Azure Monitor so the next leak is caught early.
List<object> per request; load it and watch dotnet-counters.Capturing and comparing snapshots, then the leak found and its fix.
# Watch the shape first
dotnet-counters monitor -n Notify.Api --counters System.Runtime[gc-heap-size,gen-2-gc-count,working-set]
# Three snapshots under the same steady load
dotnet-gcdump collect -n Notify.Api -o 1.gcdump
sleep 600; dotnet-gcdump collect -n Notify.Api -o 2.gcdump
sleep 600; dotnet-gcdump collect -n Notify.Api -o 3.gcdump
# Quick text view of the largest types (then diff in Visual Studio or PerfView)
dotnet-gcdump report 3.gcdump | head -20
namespace Notify.Api;
public sealed record PriceChange(string Sku, decimal Price);
public sealed class PriceFeed // registered as a singleton
{
public event EventHandler<PriceChange>? PriceChanged;
public void Publish(PriceChange change) => PriceChanged?.Invoke(this, change);
}
// BEFORE: a scoped service subscribes to a singleton's event and never leaves.
// The singleton's delegate list now roots every request's handler forever.
//
// public sealed class PriceWatcher(PriceFeed feed)
// {
// public void Start() => feed.PriceChanged += OnChanged;
// private void OnChanged(object? s, PriceChange c) { /* ... */ }
// }
// AFTER: unsubscribe when the scope is disposed.
public sealed class PriceWatcher : IDisposable
{
private readonly PriceFeed _feed;
public PriceWatcher(PriceFeed feed)
{
_feed = feed;
_feed.PriceChanged += OnChanged;
}
private void OnChanged(object? sender, PriceChange change)
{
// handle the change for this request
}
public void Dispose() => _feed.PriceChanged -= OnChanged; // breaks the root
}
// Program.cs
// builder.Services.AddSingleton<PriceFeed>();
// builder.Services.AddScoped<PriceWatcher>(); // DI disposes it at the end of the request
PriceQuote smaller just delays the OOM. Instead: Break the reference that keeps it alive.A leak investigation is a routine, not heroics: confirm with counters, diff snapshots, follow the root, fix, soak. The senior part is making it cheap next time: memory alerts on post-GC heap trend rather than raw working set, dotnet-monitor collection rules that take a gcdump automatically when the heap crosses a threshold, and a soak test in the pipeline for long-running services. I also treat container memory limits as part of the design: DOTNET_GCHeapHardLimit or the container-aware defaults mean the GC knows its budget, so an OOM-kill really means a leak or a sizing error, not a lazy GC.
| Tool | When it fits | Cost | When not to |
|---|---|---|---|
| dotnet-gcdump diff | Managed growth | Blocking full GC per snapshot | Native memory |
dotnet-dump + SOS (gcroot, dumpheap) |
Need field values, finaliser queue, native | Large sensitive file, process pause | First look at a simple leak |
| Visual Studio / dotMemory locally | Reproducible leak | Needs a repro | Production-only behaviour |
| dotnet-monitor trigger | Leak appears after hours | Sidecar to run and secure | Short-lived processes |
The container is keeping objects alive because it promised to dispose them. Every scope, including the root, tracks the transient IDisposables it creates until the scope ends; for the root that means process shutdown. Typical causes are resolving from app.Services or from an IServiceProvider injected into a singleton (which is the root), or a scope created once and never disposed. ValidateScopes doesn't catch it.
Find the type and call site from the gcdump's retention path (ServiceProviderEngineScope → disposables), then either create a scope per operation with IServiceScopeFactory.CreateAsyncScope() when several scoped services are needed, or use a factory whose result you dispose with using when it's one object. The cost of leaving it: a growing Gen2 heap, longer full GCs and eventual OOM kills. Verify with dotnet-counters over several hours.
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.
The .NET diagnostics tools all talk to the runtime over its diagnostics IPC channel, so they work on Windows, Linux and in containers without a debugger.
I start with counters because they are cheap, then pick the heavier tool the symptom points to. The trade-off is overhead and data sensitivity: a full dump contains every secret in memory.
How to tell it (STAR)
**S:** At [company] our notification pods were being OOM-killed roughly every [9 hours], causing short bursts of failed pushes. **T:** I was asked to find the cause rather than keep raising the memory limit. **A:** I confirmed with dotnet-counters that the managed heap was growing after each full GC, took three gcdumps through dotnet-monitor, and compared them in Visual Studio. The growing type was our per-request PriceWatcher, rooted by a singleton's event. I made it unsubscribe on Dispose and ran a 24-hour soak test. **R:** Memory flattened at [450 MB], OOM restarts went from [16 a day] to zero, and we added an alert and an automatic gcdump rule so the next leak is caught in minutes.
Last updated 23 Nov 2026.