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

📚 Interview question

After a release, your ASP.NET Core API's memory climbs by about 200 MB a day until the app is recycled. The change added a scoped PriceDisplayService that subscribes to a singleton PriceFeed's PriceChanged event, and to IOptionsMonitor.OnChange, in its constructor. Why does this leak, how do you prove it with dotnet-counters and dotnet-gcdump, and how do you fix it?

Observer lifetime mismatch in DI: a scoped subscriber to a singleton subject (event and IOptionsMonitor.OnChange) stays reachable through the delegate invocation list; proving it with dotnet-counters, two dotnet-gcdump snapshots and paths to root; fixing it with IDisposable unsubscription the container calls, moving subscriptions to singletons, lambda pitfalls, weak references, and a WeakReference regression test.

Mid-Level Debugging Intermediate dependency-injection design-patterns dotnet-gcdump events memory-leaks observer

🎯 Key points

  • A subject holds a strong reference to each observer through the delegate's Target, so a singleton publisher keeps every scoped subscriber alive after its request ends
  • IOptionsMonitor<T>.OnChange returns an IDisposable?; ignoring it leaves the callback (and its captured this) registered for the app's lifetime
  • dotnet-counters monitor System.Runtime: GC heap size and gen 2 size climb steadily and never return to baseline after full GCs
  • Two dotnet-gcdump snapshots minutes apart: PriceDisplayService instance count grows; path to root goes PriceFeed → EventHandler invocation list → PriceDisplayService
  • Fix 1: implement IDisposable and unsubscribe; the container disposes scoped services it created when the request scope ends
  • Fix 2 (better): don't subscribe per request; a singleton owns the subscription and caches the latest value, and the scoped service just reads it
  • Lambdas subscribed with += can't be removed with a new lambda; keep the delegate in a field, or use the IDisposable token
  • Regression test: create the service in a scope, dispose the scope, force GC and assert a WeakReference to it is no longer alive

⏱ 30-second answer

It's an Observer lifetime mismatch. The singleton PriceFeed holds every subscriber in its event's invocation list (a strong reference through each delegate's Target), so each request's PriceDisplayService stays reachable long after the request ends. The ignored IDisposable from IOptionsMonitor.OnChange does the same thing.

To prove it: dotnet-counters shows GC heap and gen 2 size climbing without returning to baseline; two dotnet-gcdump snapshots show the PriceDisplayService count growing, with a path to root through PriceFeed → EventHandler → the service.

The fix: unsubscribe in Dispose (the container disposes scoped services at the end of the request), dispose the OnChange token, or better, move the subscription into a singleton that caches the latest price. The trade-off is that per-request subscriptions are almost never what you want; align observer and subject lifetimes.

🗣 Full answer (senior)

How I would answer this in an interview

"The shape of the graph tells you a lot: steady growth with every request, never released by gen 2 collections, means something long-lived is holding request-scoped objects. Here it's the Observer pattern with mismatched lifetimes. PriceFeed is a singleton. When a scoped PriceDisplayService does feed.PriceChanged += OnPriceChanged in its constructor, the feed's delegate now holds a reference to that service through the delegate's Target. The request ends, the scope ends, but the feed still points at the service, so the GC can't collect it, or anything it references: its DbContext, its logger scope, the user's data. One leaked object per request at [~2,000] requests an hour is how you get 200 MB a day. IOptionsMonitor.OnChange is the same pattern: it returns an IDisposable and if you discard it, the monitor keeps your callback, and the closure keeps this.

To prove it, I'd first watch dotnet-counters monitor -p <pid> --counters System.Runtime and confirm GC heap size and gen 2 size climb and don't drop after full collections, which rules out normal gen 0 churn. Then I'd take two dotnet-gcdump collect snapshots ten minutes apart, open them in Visual Studio or PerfView and diff them. The type with a growing count is PriceDisplayService, and 'paths to root' shows PriceFeed → EventHandler<PriceChanged> → the invocation list → PriceDisplayService. That's the proof, and it takes about fifteen minutes in a test environment under load.

For the fix, the quick one is to implement IDisposable, unsubscribe with -= and dispose the OnChange token. The container disposes scoped services it created when the request scope ends, so that's enough. But the real question is why a per-request object is subscribing to a feed at all. Usually the right design is a singleton that owns the subscription and caches the latest price, and the scoped service just reads it. The mistake I see is subscribing with a lambda: feed.PriceChanged += (s, e) => ... can't be removed with -= and a new lambda, because it's a different delegate. Every += needs an owner with the same lifetime as the publisher, or a -= that is guaranteed to run."


Diagnosing it

Step Tool What you're looking for
1. Confirm a managed leak dotnet-counters monitor --counters System.Runtime GC heap size and gen 2 size rising after each gen 2 GC
2. Find what grows dotnet-gcdump collect -p <pid> twice, diff in Visual Studio or PerfView Instance count of PriceDisplayService (and what it holds) increasing
3. Find who holds it Paths to root in the dump PriceFeed → EventHandler<T> → invocation list → service
4. Confirm in production Application Insights memory metrics vs request count Growth proportional to requests, reset on recycle

Fixes, in order of preference

Fix How When
Move the subscription to a singleton Singleton PriceCache subscribes once and stores the latest value The scoped class only needs the current value
Unsubscribe in Dispose IDisposable with -= and _optionsToken?.Dispose() The per-scope subscription is genuinely needed
Keep the delegate Store the handler in a field so -= removes the same delegate You must subscribe with a lambda
Weak subscription Publisher holds WeakReference to subscribers Third-party or plug-in subscribers you can't control

Production example

A quote API leaked about 200 MB a day and was being recycled nightly by an App Service rule. Two gcdumps showed roughly 45,000 live PriceDisplayService instances after a day, each holding a DbContext. Moving the subscription into a singleton cache flattened the gen 2 heap at about 180 MB, removed the nightly recycle, and cut p99 latency by 30% because gen 2 collections dropped from dozens an hour to a handful.

🔍 What the interviewer is checking

Checks whether the candidate can connect the Observer pattern to DI lifetimes, prove a managed leak with the right tools and fix it at the design level.

Green flags

  • Explains that the publisher's delegate references the subscriber via Target.
  • Uses dotnet-counters then two diffed dotnet-gcdump snapshots and paths to root.
  • Knows the container disposes scoped services and uses that hook.
  • Prefers moving the subscription to a singleton.
  • Catches the lambda -= trap and the OnChange token.

Red flags

  • Blames the GC or suggests calling GC.Collect.
  • Fixes it with scheduled recycles.
  • Takes one memory snapshot and guesses.

📚 Learn in depth

1. Why the subscriber can't be collected

Root (static / DI root provider)
  └─▶ PriceFeed (singleton)
        └─▶ PriceChanged : EventHandler<PriceChanged>   (multicast delegate)
              └─▶ invocation list
                    ├─▶ delegate { Target = PriceDisplayService#1, Method = OnPriceChanged }
                    ├─▶ delegate { Target = PriceDisplayService#2, ... }
                    └─▶ ... one per request

The GC collects only what is unreachable from roots. A singleton is rooted by the root service provider for the life of the app, so everything its event references is reachable. Each += creates a new delegate whose Target is the subscriber instance. Nothing about the scope ending removes that edge.

2. IOptionsMonitor.OnChange is the same pattern

OnChange(listener) adds the listener to the monitor's list and returns an IDisposable? that removes it. The monitor is a singleton, and a lambda that uses instance members captures this. Discarding the token leaks the subscriber exactly like an event, and the callback keeps running against an object whose DbContext has already been disposed, which can surface as ObjectDisposedException in logs long after the request.

3. What the container does and doesn't do

  • The container disposes IDisposable scoped and transient services it created when the scope ends. That is your hook for -=.
  • Disposing doesn't remove references held by others. If the service doesn't unsubscribe in Dispose, it's disposed and still reachable.
  • Transient IDisposable services resolved from the root provider are tracked until the app shuts down: a second, related leak to check for.

4. Reading counters and dumps

  • dotnet-counters: watch GC Heap Size, Gen 2 Size, Gen 2 GC Count and % Time in GC. A sawtooth that returns to the same floor is healthy; a rising floor is a leak.
  • dotnet-gcdump captures the managed object graph with only a short pause (it triggers a gen 2 GC), small enough to take in production carefully. Diff two snapshots and sort by count delta. Event leaks show up as your subscriber type plus delegate types (EventHandler<T>, closure classes like <>c__DisplayClass).
  • dotnet-dump plus dumpheap -stat and gcroot <address> gives the same answer from a full dump when you need native memory too.

5. Lambdas, closures and -=

feed.PriceChanged += (s, e) => Update(e);   // delegate A
feed.PriceChanged -= (s, e) => Update(e);   // delegate B: not equal to A, nothing removed

Delegate equality compares target and method. Two lambdas compile to different methods (or a new closure instance), so removal silently does nothing. Store the handler in a field, use a method group, or use an API that returns an IDisposable.

6. Weak subscriptions

A weak event holds the subscriber through a WeakReference<T> so the subscriber can be collected without unsubscribing. WPF has WeakEventManager; there is no general-purpose server-side equivalent in the BCL, so you write a small one or use a library. Weak events cost an extra allocation and a dead-reference sweep, and they hide lifetime bugs rather than fix them, so I keep them for plug-in style cases where I don't control subscribers.

Try it yourself

  1. Reproduce the leak: a singleton with an event, a scoped subscriber, and a load test with bombardier or k6. Watch dotnet-counters.
  2. Take two dotnet-gcdump snapshots, diff them, and follow the path to root to the event.
  3. Add IDisposable with -=, rerun, and confirm the gen 2 floor stays flat.
  4. Subscribe with a lambda and try to remove it with another lambda; confirm the invocation list length with GetInvocationList().Length.
  5. Write the WeakReference regression test from the code example and make it fail by removing Dispose.

💻 Code

Before: a scoped service subscribes to a singleton in its constructor and never lets go.

namespace Quotes;

using Microsoft.Extensions.Options;

public sealed record PriceChanged(string Sku, decimal Price);
public sealed class DisplayOptions { public int DecimalPlaces { get; set; } = 2; }

public sealed class PriceFeed   // registered as a singleton
{
    public event EventHandler<PriceChanged>? PriceChanged;
    public void Publish(string sku, decimal price) => PriceChanged?.Invoke(this, new PriceChanged(sku, price));
}

// LEAKS: one instance per request stays reachable from the singleton forever
public sealed class LeakyPriceDisplayService
{
    private decimal _last;
    private int _decimals;

    public LeakyPriceDisplayService(PriceFeed feed, IOptionsMonitor<DisplayOptions> options)
    {
        feed.PriceChanged += (_, e) => _last = e.Price;             // lambda captures this; can't be removed
        options.OnChange(o => _decimals = o.DecimalPlaces);          // IDisposable discarded
        _decimals = options.CurrentValue.DecimalPlaces;
    }

    public string Format() => Math.Round(_last, _decimals).ToString();
}

Fix 1: unsubscribe deterministically; the container calls Dispose when the request scope ends.

namespace Quotes;

using Microsoft.Extensions.Options;

public sealed class PriceDisplayService : IDisposable
{
    private readonly PriceFeed _feed;
    private readonly IDisposable? _optionsSubscription;
    private decimal _last;
    private int _decimals;

    public PriceDisplayService(PriceFeed feed, IOptionsMonitor<DisplayOptions> options)
    {
        _feed = feed;
        _feed.PriceChanged += OnPriceChanged;                        // method group: -= removes the same delegate
        _optionsSubscription = options.OnChange(o => _decimals = o.DecimalPlaces);
        _decimals = options.CurrentValue.DecimalPlaces;
    }

    private void OnPriceChanged(object? sender, PriceChanged e) => _last = e.Price;

    public string Format() => Math.Round(_last, _decimals).ToString();

    public void Dispose()
    {
        _feed.PriceChanged -= OnPriceChanged;
        _optionsSubscription?.Dispose();
    }
}

Fix 2 (preferred): one subscription, owned by a singleton with the same lifetime as the feed.

namespace Quotes;

using System.Collections.Concurrent;

public sealed class PriceCache : IDisposable     // singleton: subscribes once for the life of the app
{
    private readonly PriceFeed _feed;
    private readonly ConcurrentDictionary<string, decimal> _latest = new();

    public PriceCache(PriceFeed feed)
    {
        _feed = feed;
        _feed.PriceChanged += OnPriceChanged;
    }

    private void OnPriceChanged(object? sender, PriceChanged e) => _latest[e.Sku] = e.Price;

    public decimal? Get(string sku) => _latest.TryGetValue(sku, out var p) ? p : null;

    public void Dispose() => _feed.PriceChanged -= OnPriceChanged;
}

// Scoped consumers just read; they never subscribe
public sealed class QuoteService(PriceCache cache)
{
    public decimal? PriceFor(string sku) => cache.Get(sku);
}

// Program.cs
// builder.Services.AddSingleton<PriceFeed>();
// builder.Services.AddSingleton<PriceCache>();
// builder.Services.AddScoped<QuoteService>();

Regression test: prove the subscriber is collectable after its scope ends.

namespace Quotes.Tests;

using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;

public class PriceDisplayServiceLeakTests
{
    [Fact]
    public void Subscriber_is_collectable_after_scope_disposal()
    {
        var services = new ServiceCollection();
        services.AddSingleton<PriceFeed>();
        services.AddOptions<DisplayOptions>();
        services.AddScoped<PriceDisplayService>();
        using var root = services.BuildServiceProvider();

        WeakReference weak = ResolveInScope(root);   // separate method so no local keeps it alive

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        Assert.False(weak.IsAlive);
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static WeakReference ResolveInScope(IServiceProvider root)
    {
        using var scope = root.CreateScope();
        return new WeakReference(scope.ServiceProvider.GetRequiredService<PriceDisplayService>());
    }
}

⚠ Common mistakes

  • Mistake: Subscribing to a singleton's event from a scoped or transient service without unsubscribing. Why it is wrong: The singleton's delegate keeps every instance reachable, so memory grows with request count. Instead: Unsubscribe in Dispose, or move the subscription into a singleton.
  • Mistake: Discarding the IDisposable returned by IOptionsMonitor<T>.OnChange. Why it is wrong: The monitor keeps the callback and its captured this for the life of the app. Instead: Store the token and dispose it with the owner, or subscribe only from singletons.
  • Mistake: Subscribing with a lambda and unsubscribing with another identical-looking lambda. Why it is wrong: They are different delegates, so -= removes nothing. Instead: Use a method group or keep the delegate in a field.
  • Mistake: Assuming the container disposing the service removes the subscription. Why it is wrong: Dispose only does what you write in it; the publisher still references the object. Instead: Put -= in Dispose and test it.
  • Mistake: Diagnosing with a single memory snapshot. Why it is wrong: One snapshot shows what's big, not what's growing. Instead: Take two dotnet-gcdump snapshots under steady load and diff instance counts.
  • Mistake: Treating a nightly app recycle as the fix. Why it is wrong: It hides the leak, and gen 2 GC pressure still hurts latency between recycles. Instead: Find the root and fix the lifetime.
  • Mistake: Reaching for weak events by default. Why it is wrong: They hide lifetime design problems and add overhead. Instead: Align lifetimes first; use weak references only for subscribers you can't control.

🏛 Senior insight: trade-offs

Event leaks in services are almost always a design smell before they're a memory bug: a short-lived object is reacting to a long-lived stream. The fix that lasts is aligning lifetimes, so the long-lived thing owns the subscription and short-lived things read state. Deterministic Dispose is the second line, and a WeakReference test makes the rule enforceable.

Option When it fits Cost When not to
Singleton owns subscription, caches state Scoped code only needs the latest value One shared cache to make thread-safe Each scope needs its own stream of events
IDisposable + -= in the subscriber Per-scope subscription is genuinely needed Must remember every += Subscriber lifetime isn't controlled by the container
IObservable<T> / OnChange token API returns a subscription object Token must be stored and disposed Fire-and-forget subscriptions
Weak events Plug-ins or third-party subscribers Extra allocations, hidden lifetimes Your own code where you control lifetimes

Measure the fix the same way you found it: the gen 2 floor in dotnet-counters should go flat under the same load, and the diffed instance count should stay near the number of in-flight requests.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate explains the leak as a forgotten event subscription Why: Checks event handler conventions, async handlers and event leak diagnosis in more depth
    How to answer

    The convention is EventHandler<TEventArgs> with object? sender and an immutable args object, EventArgs.Empty when there is no data, and a protected virtual OnXxx method that raises it. The big production risk is leaks: the publisher's delegate holds a strong reference to every subscriber, so a singleton or static publisher keeps short-lived subscribers alive forever. I find them with a heap dump and gcroot, which shows the path through the event's delegate, and fix them by unsubscribing in Dispose or using a weak event. Async handlers are async void, so I keep them thin and catch everything inside.

  2. When: Candidate mentions the lambda captured this or can't be unsubscribed Why: Checks how lambdas capture this and why closures extend lifetimes
    How to answer

    A closure is a lambda or local function plus the variables it captures. The compiler moves those variables into fields of a hidden display class, so the method and the lambda share the same variable. That's why capture is by variable, not by value. In a for loop all lambdas share one loop variable, while foreach gets a fresh one per iteration since C# 5. Every lambda in a scope shares one display class, and capturing this keeps the whole object alive, which can leak memory through timers and caches. In hot paths I use static lambdas with explicit state.

  3. When: Candidate talks about a singleton holding a scoped object Why: Checks the related captive dependency problem between singletons and scoped services
    How to answer

    A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.

    ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.

    The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.

🛠 Real-world problems: how you handle them

Scoped subscriber to a singleton price feed leaked 200 MB a day
Situation
Quote API for [company] on Azure App Service ([2] instances, Australia East), about [2,000] requests an hour per instance. A release added live price formatting through a scoped service subscribed to a singleton feed.
Signals
App Service memory working set rising ~200 MB a day per instance; an auto-heal rule recycling at [1.5 GB] nightly; p99 latency creeping up through the day; occasional `ObjectDisposedException` from a `DbContext` in logs with no active request.
Investigation
`dotnet-counters monitor --counters System.Runtime` in staging under a k6 load test showed the gen 2 floor rising after every gen 2 GC. Two `dotnet-gcdump` snapshots ten minutes apart, diffed in Visual Studio, showed `PriceDisplayService` and its `DbContext` growing by roughly one per request. Paths to root led to `PriceFeed.PriceChanged`. A second root came from an `IOptionsMonitor.OnChange` closure.
Resolution
Immediate: reverted the release so the auto-heal recycles stopped. Real fix: a singleton `PriceCache` now subscribes once and stores the latest prices; the scoped service reads from it. The `OnChange` subscription moved into the singleton and its token is disposed.
Prevention
WeakReference regression test for any scoped service that touches a singleton's events; a code-review checklist item ('every += has an owner with the publisher's lifetime'); an Application Insights alert on working-set growth per request; removed the auto-heal recycle so leaks surface.

How to tell it (STAR)

**S:** At [company], our quote API's memory climbed about 200 MB a day and we were hiding it with a nightly recycle. **T:** I was asked to find the cause and remove the recycle. **A:** I reproduced it in staging under load, used `dotnet-counters` to confirm the gen 2 floor was rising, then diffed two `dotnet-gcdump` snapshots and followed the path to root: a singleton price feed's event was holding every request's `PriceDisplayService`, plus an `IOptionsMonitor.OnChange` closure. I moved the subscription into a singleton cache and added a WeakReference test. **R:** Memory flattened at about [180 MB], we removed the recycle, and p99 latency dropped by [30%] because gen 2 collections nearly disappeared.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me