Finding memory leaks in high-throughput .NET services
When memory climbs until the container is killed, guessing wastes days. A repeatable way to go from "it's using too much memory" to the line of code holding on to it.
In a service that handles thousands of requests or messages a second, a small leak doesn't stay small. Memory climbs for hours, the garbage collector works harder, latency rises, and eventually the process is killed for exceeding its memory limit. Restarting buys time but hides the cause.
1. Confirm it's a leak, not a busy heap
Watch the runtime counters on the live process first:
dotnet-counters monitor -p <pid> --counters System.Runtime
Look at GC heap size and generation 2 size after full collections. A healthy service rises and falls with load. A leak shows a floor that keeps moving up even when traffic drops.
2. Take two snapshots, not one
A single snapshot shows what's big. Two snapshots taken some time apart show what's growing, which is what you actually need.
dotnet-gcdump collect -p <pid> # lightweight, heap types and counts
dotnet-dump collect -p <pid> # full dump when you need object contents
Compare type counts between the two. The type whose count grows with traffic is usually your suspect.
3. Ask who is holding on
In a full dump, dumpheap -stat lists types by total size, and gcroot <address> shows the chain of references keeping an object alive. That chain almost always ends in one of a few places:
- A static or singleton collection used as a cache with no size limit or expiry
- Event handlers that subscribe to a long-lived object and never unsubscribe
- Per-tenant or per-connection state that is created on connect and never removed on disconnect
- Large buffers over 85,000 bytes, which go on the large object heap and fragment it when allocated per request
4. Fix the ownership, then move state out if needed
Most fixes are about ownership: give caches a size limit and expiry, unsubscribe handlers, dispose per-connection state. When a service genuinely needs a lot of shared state, moving it out of process into Redis keeps the service's own heap small and predictable, and lets you scale instances without each one holding a full copy.
5. Know your container limit
When a memory limit is set on the container, the .NET garbage collector sizes its heap from that limit, by default 75% of it. If your limit is tight and your workload has spikes, you'll see frequent collections long before you see an out-of-memory kill. Set limits from measured usage, not guesses.
Make it visible next time
Put GC heap size, generation 2 size, GC count and pause time on the same dashboard as throughput. The next leak then shows up as a trend on a graph, not as a 3 a.m. restart.
Dealing with this in your own system? We do this work for a living. The first call is free.
Book a call