📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A legacy ASP.NET MVC 5 app on .NET Framework 4.8 and IIS keeps growing in memory and the application pool recycles every few hours, logging users out. You can't change much code and can't attach a debugger in production. How do you find the cause and fix it?

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.

Senior Debugging Advanced dotnet-framework iis legacy-migration memory-leak production-debugging windbg

🎯 Key points

  • Confirm why the pool recycles: WAS events in the System log (5117 private memory limit, 5074 time interval, 5011 crash), and check the app pool recycling settings
  • If Private Bytes and # Bytes in all Heaps climb together it is a managed leak; if only Private Bytes climbs it is native
  • Capture two or three dumps as memory grows: ProcDump -ma or DebugDiag rules on private bytes
  • Analyse with WinDbg + SOS (!dumpheap -stat, !gcroot) or PerfView heap snapshots diffed over time; a rooted object can't be collected however often the GC runs
  • Typical legacy causes: static collections and caches, event handler subscriptions, HttpRuntime.Cache without limits, undisposed objects, session bloat
  • In-process session is lost on recycle, so users are logged out; move session out of process as a mitigation
  • Low-risk fixes: bounded caches, unsubscribe events, overlapped recycle at quiet times, out-of-process session
  • Verify the fix by comparing the memory curve and recycle count before and after

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 w3wp process: 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 -stat showed [a dictionary of product objects] growing between dumps, and !gcroot traced it to a static cache in [a pricing helper] keyed by customer, with no eviction. The fix was a few lines: replace it with MemoryCache with 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 by step

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

Usual suspects in legacy ASP.NET

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can diagnose a production memory problem methodically on a legacy stack, with low-risk changes and measurable results.

Green flags

  • Starts with the recycle reason in the WAS event log
  • Separates managed and native leaks using counters
  • Uses multiple dumps and !gcroot or PerfView diffs
  • Proposes small, safe fixes and immediate mitigations
  • Treats dumps as sensitive data

Red flags

  • Raises memory limits or calls GC.Collect() as the fix
  • Wants to rewrite the app before diagnosing
  • Doesn't know how to get a dump without a debugger

📚 Learn in depth

1. How IIS recycling works

WAS (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.

2. Managed versus native

  • Private Bytes = all committed memory private to the process (managed heap + native heaps + thread stacks + JIT code).
  • # Bytes in all Heaps = the managed GC heap (Gen 0, 1, 2 and LOH).

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.

3. Reading a dump with SOS

.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.

4. Taking dumps safely

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.

5. Why not just recycle more often?

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.

Try it yourself

  1. Write a small MVC app with a static List<byte[]> that grows per request; load it with a tool and watch PerfMon counters.
  2. Take two dumps with procdump -ma and compare !dumpheap -stat output.
  3. Use !gcroot to find the static field holding the list.
  4. Open the same dumps in PerfView and use the heap diff view.
  5. Set an app pool private memory limit in a test IIS and find event 5117 in the System log when it recycles.

💻 Code

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

⚠ Common mistakes

  • Mistake: Raising the app pool memory limit or adding more scheduled recycles as the fix. Why it is wrong: It hides the leak and users still lose in-process session. Instead: Use it only as a temporary mitigation while you find the root cause.
  • Mistake: Taking one dump. Why it is wrong: One snapshot can't show what is growing. Instead: Take two or three at increasing sizes and compare.
  • Mistake: Assuming a managed leak without checking counters. Why it is wrong: Native leaks (COM, GDI+, unmanaged libraries) won't show in !dumpheap. Instead: Compare Private Bytes with # Bytes in all Heaps first.
  • Mistake: Calling 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.
  • Mistake: Taking dumps on a live server at peak without warning. Why it is wrong: The process freezes for seconds and the dump holds personal data. Instead: Pull one server from the load balancer or wait for a quiet period, and store dumps securely.
  • Mistake: Rewriting the module because it is old. Why it is wrong: It is high risk and the leak is usually a few lines. Instead: Make the smallest change that removes the root, behind a test.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions capturing a dump Why: Checks depth on dump capture and analysis tools
    How to answer

    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.

  2. When: Candidate separates managed and native memory Why: Checks they can go beyond SOS when the leak is native
    How to answer

    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.

🛠 Real-world problems: how you handle them

MVC 5 portal recycling every three hours and logging users out
Situation
An [online ordering portal] on ASP.NET MVC 5, .NET Framework 4.8, on [two] IIS servers behind a load balancer, with in-process session. [About 1,500] business customers place orders during business hours.
Signals
Help desk tickets about being logged out mid-order; WAS event 5117 (private memory limit) in the System log [eight times a day]; PerfMon showed w3wp Private Bytes climbing [about 400 MB an hour] with # Bytes in all Heaps rising in step.
Investigation
Confirmed a managed leak from the counters. Took one server out of the load balancer at a time and captured three full dumps with `procdump -ma` at [1, 1.5 and 2 GB]. In WinDbg with SOS, `!dumpheap -stat` showed [QuoteDto] instances growing from [60,000 to 1.9 million]; `!gcroot` traced them to a static `Dictionary` in [PriceCache]. Cross-checked with PerfView's heap diff.
Resolution
Immediate: switched session to SQL Server mode so recycles no longer logged users out, and moved the scheduled recycle to [3 am]. Real fix: replaced the static dictionary with a size-limited `MemoryCache` with a 10-minute expiry, a [20-line] change covered by a unit test, released in the next weekly deployment.
Prevention
Application Insights alert on private bytes growth rate; CA rules and a review checklist item flagging new static mutable collections; a soak test in the pipeline that runs [two hours] of recorded traffic and fails if memory grows past a threshold.

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.

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me