Covers diagnosing a memory leak in a .NET Framework app on IIS: reading the recycle cause (private memory limit, regular time interval), Performance Monitor counters, capturing dumps with ProcDump or Debug Diagnostic Tool, analysing with WinDbg/SOS or PerfView, common legacy leak sources, and low-risk mitigations.
First find why IIS recycles: the System event log (WAS) says whether it hit the private memory limit, a time schedule, or crashed. Then measure: Process\Private Bytes versus .NET CLR Memory# Bytes in all Heaps. If both climb together, it's a managed leak; if only Private Bytes climbs, it's native (COM, unmanaged libraries).
Capture two or three memory dumps as memory grows (ProcDump or DebugDiag), and compare them in WinDbg with SOS (!dumpheap -stat, !gcroot) or PerfView. The growing type and its GC root tell you the cause: usually a static cache, an event subscription or session bloat. Mitigate with low-risk fixes (bounded cache, out-of-process session, recycle at quiet times) and verify with the memory curve. The trade-off: dumps pause the process, so take them carefully.
"I'd start by not guessing. First, why is it recycling? IIS writes WAS events to the System log: 5117 for the private memory limit, 5074 for the scheduled time interval, 5011 when a worker process crashes. If it's the memory limit, I put Performance Monitor counters on the
w3wpprocess: Private Bytes and the CLR's '# Bytes in all Heaps'. If the managed heap grows with private bytes, it's a managed leak; if private bytes grows and the heap is flat, it's native, often a COM component or an unmanaged library.For example, at [company] we had [an MVC 5 ordering portal] that recycled [every three hours]. Because users were on in-process session, every recycle logged them out. I couldn't attach a debugger, so I used ProcDump to take full dumps at [1 GB, 1.5 GB and 2 GB], which only pauses the process for a few seconds each. In WinDbg with SOS,
!dumpheap -statshowed [a dictionary of product objects] growing between dumps, and!gcroottraced it to a static cache in [a pricing helper] keyed by customer, with no eviction. The fix was a few lines: replace it withMemoryCachewith a size limit and expiry. Memory flattened at [600 MB] and recycles went from [eight a day to zero unplanned].The mistake I see is raising the memory limit or scheduling more recycles and calling it fixed. That hides the leak and keeps logging users out. My senior line: on legacy systems, measurement buys you the right to make a small, safe change, instead of a big risky one."
| Step | Tool | What you learn |
|---|---|---|
| 1. Why recycle? | Event Viewer → System, source WAS (5117, 5074, 5011, 5186) | Memory limit, schedule, crash, idle timeout |
| 2. Managed or native? | PerfMon: Process\Private Bytes, .NET CLR Memory\# Bytes in all Heaps, Gen 2 heap size, LOH size |
Where the growth is |
| 3. Capture | procdump -ma -m 1500 <pid> or DebugDiag memory rule |
Full dumps at known sizes |
| 4. Compare | WinDbg + SOS: !dumpheap -stat, !dumpheap -type X, !gcroot; or PerfView heap snapshot diff |
Growing type and what roots it |
| 5. Confirm | Code search for statics, events, caches | The leaking code path |
| 6. Mitigate safely | Config and small code changes | Stops the impact |
| 7. Verify | PerfMon / Application Insights over days | Flat memory curve |
| Cause | What the dump shows | Low-risk fix |
|---|---|---|
Static Dictionary cache |
Big collection rooted by a static field | MemoryCache with SizeLimit and expiry |
| Event subscriptions to long-lived objects | Handlers rooted by a static event | Unsubscribe, or weak events |
HttpRuntime.Cache without expiry |
Cache entries growing | Add expiration and priorities |
| Huge in-process session | SessionStateItemCollection heavy |
Store less; move session to SQL Server |
| Undisposed objects with finalisers | Large finaliser queue (!finalizequeue) |
using; fix Dispose |
| COM / native libraries | Private bytes grow, managed heap flat | DebugDiag native leak tracking; isolate the component |
| Dynamic assemblies (XmlSerializer with custom ctors, Razor compiles) | Growing loader heap / modules | Cache XmlSerializer instances |
In a typical case the dump diff shows one type, such as a pricing DTO, growing from 50,000 to 2 million instances in two hours, rooted by a static ConcurrentDictionary. Bounding the cache to 10,000 entries with a 10-minute expiry keeps memory under 700 MB and removes unplanned recycles, with no change to behaviour that users can see.
Checks that the candidate can diagnose a production memory problem methodically on a legacy stack, with low-risk changes and measurable results.
Green flags
!gcroot or PerfView diffsRed flags
GC.Collect() as the fixWAS (Windows Process Activation Service)
│ monitors w3wp.exe for each app pool
│ triggers: Private Memory Limit (KB), Virtual Memory Limit,
│ Regular Time Interval (default 1740 min = 29 h),
│ Specific Times, Request Limit, config change, crash, idle timeout
▼
Overlapped recycle (default): start new w3wp → new requests go there
→ old w3wp drains (shutdownTimeLimit 90 s) → exits
Overlapped recycling avoids dropped requests, but everything in process is lost: in-process session, HttpRuntime.Cache, static state, warm JIT code. That's why users get logged out with InProc session or Forms authentication tickets tied to session.
If private bytes minus managed heap grows, look at native: COM objects (classic ASP-era components), System.Drawing (GDI+), unmanaged image or PDF libraries, or pinned buffers.
.loadby sos clr (.NET Framework)
!dumpheap -stat types sorted by total size; compare dumps
!dumpheap -type Pricing.QuoteDto list instances
!gcroot <address> path from a root (static, handle, stack) to the object
!finalizequeue objects waiting for finalisation
!eeheap -gc heap sizes per generation
The answer is almost always the path from !gcroot: e.g. static Pricing.Cache._items → Dictionary → Entry[] → QuoteDto. PerfView gives the same information visually and can diff two heap snapshots.
A full dump (-ma) of a 2 GB process freezes it for a few seconds and writes a 2 GB file. Do it on one server out of the load balancer, or at a quiet time, and treat the file as sensitive: it contains customer data from memory, so under the Privacy Act and APP 11 it must be stored securely and deleted after analysis.
Recycling more often is a valid temporary mitigation, at a quiet time with overlapped recycling and out-of-process session. But it hides the growth rate, costs warm-up time (JIT, caches), and if traffic rises the leak will hit the limit between recycles anyway.
List<byte[]> that grows per request; load it with a tool and watch PerfMon counters.procdump -ma and compare !dumpheap -stat output.!gcroot to find the static field holding the list.The leaking static cache and a low-risk replacement that still runs on .NET Framework 4.8 (and on .NET 10 later).
// Before: static, unbounded, never evicted (grows per customer and product)
public static class PriceCache
{
private static readonly Dictionary<string, QuoteDto> Items = new Dictionary<string, QuoteDto>();
private static readonly object Gate = new object();
public static QuoteDto Get(string customerId, string sku, Func<QuoteDto> load)
{
var key = customerId + ":" + sku;
lock (Gate)
{
if (!Items.TryGetValue(key, out var quote))
{
quote = load();
Items[key] = quote; // rooted forever by the static field
}
return quote;
}
}
}
// After: Microsoft.Extensions.Caching.Memory works on net48 and net10.0
namespace Pricing;
using Microsoft.Extensions.Caching.Memory;
public sealed record QuoteDto(string Sku, decimal Price);
public sealed class PriceCache(IMemoryCache cache)
{
public QuoteDto Get(string customerId, string sku, Func<QuoteDto> load) =>
cache.GetOrCreate($"{customerId}:{sku}", entry =>
{
entry.Size = 1; // counts toward SizeLimit
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return load();
})!;
}
// Registration: bound the cache so it can't grow without limit
// var cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 10_000 });
# Capture full dumps when w3wp private bytes pass 1.5 GB (up to 3 dumps)
procdump -ma -m 1500 -n 3 <w3wp-pid> C:\dumps\
# Which w3wp is which app pool?
%windir%\system32\inetsrv\appcmd list wp
!dumpheap. Instead: Compare Private Bytes with # Bytes in all Heaps first.GC.Collect() from code to keep memory down. Why it is wrong: Rooted objects aren't collectable, and forced collections hurt throughput. Instead: Remove the root.Legacy production debugging is about buying certainty cheaply. A dump analysis takes a few hours and usually points to a handful of lines; a rewrite takes months and brings new bugs. I also separate impact from cause: out-of-process session and quiet-time overlapped recycles stop users being logged out today, while the dump work fixes the leak this week. I measure success as a flat Private Bytes curve over several days and zero unplanned WAS 5117 events.
Two more things matter on legacy servers. First, check the app pool configuration itself: several apps sharing one pool means one app's leak recycles all of them, a 32-bit pool (enable32BitAppOnWin64) caps usable memory far lower, and Web Garden (more than one worker process) multiplies in-process caches. Giving the leaking app its own pool is a cheap isolation step. Second, the GC can't help with a leak: in a leak the objects are still reachable from a root, so Gen 2 grows and full collections get longer and more frequent, which shows up as high % Time in GC and CPU before the memory limit is reached.
| Mitigation | When it fits | Cost | When not to |
|---|---|---|---|
| Move session to SQL Server state | Users logged out by recycles | Low; session objects must be serialisable | Session holds huge objects (fix that first) |
| Scheduled overlapped recycle at 3 am | Slow leak while you investigate | Low; warm-up cost | As the permanent fix |
| Separate app pool for the leaking app | Several apps share a pool | Low | Single app already isolated |
Bounded MemoryCache |
Static cache leak | Low | Cache needs to be shared across servers (use Redis) |
| Isolate native component in its own process | Native leak in a COM library you can't fix | Medium | Managed leak |
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.
It means the growth is outside the GC heap: native allocations from COM components, GDI+ (System.Drawing), unmanaged libraries, leaked threads (each reserves a stack, 1 MB by default on Windows) or pinned buffers. Check thread count and handle count counters first, because leaked threads and handles are the most common cause. On .NET Framework, use DebugDiag with a leak-tracking rule, or Windows Performance Recorder heap tracing analysed in WPA (or the Visual Studio native memory snapshot), which record native allocation call stacks. In a managed dump, look for many Bitmap, SafeHandle or COM RCW objects that wrap native memory. On .NET 10 the same approach applies, with dotnet-counters and dotnet-dump for the managed side. Fix by disposing wrappers deterministically or isolating an unfixable native component in a separate process.
How to tell it (STAR)
**S:** Our [ordering portal] on MVC 5 recycled about [eight times a day], and every recycle logged customers out mid-order. **T:** I had to fix it without a big code change and without attaching a debugger to production. **A:** I read the WAS events to confirm it was the memory limit, used PerfMon to show it was a managed leak, then took three dumps with ProcDump and compared them in WinDbg. `!gcroot` led to an unbounded static price cache. I moved session to SQL Server to stop the logouts straight away, then replaced the cache with a bounded `MemoryCache`. **R:** Memory flattened at [about 600 MB], unplanned recycles dropped to [zero], and logout complaints stopped.
Last updated 23 Nov 2026.