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

📚 Interview question

A queue-processing worker service using EF Core gets slower every day after a deployment, starts acting on stale data, and is eventually OOM-killed with around 500k entities tracked. Walk me through how you would diagnose it and what you would change.

A production scenario: a BackgroundService that holds one DbContext for its lifetime, so the change tracker grows without bound, the identity map returns stale in-memory values, and the process runs out of memory; covers diagnosis with dotnet-counters, dotnet-gcdump and Application Insights, the fix with a scope or IDbContextFactory per message, and prevention.

Senior RealWorldScenario Advanced background-service change-tracking dbcontext-lifetime dotnet-counters ef-core memory-leak

🎯 Key points

  • Symptom pattern: throughput falls and memory climbs steadily from each restart = something accumulating, here tracked entities
  • Root cause: one DbContext created in the BackgroundService constructor or ExecuteAsync and used for every message
  • Identity map returns already-tracked instances with their old values, so the worker acts on stale data and breaks business rules
  • Evidence: dotnet-counters (GC heap, gen 2 count, EF active-db-contexts stuck at 1), dotnet-gcdump, Azure Monitor container memory, Application Insights SaveChanges duration trend
  • With concurrent message handlers (MaxConcurrentCalls > 1) a shared context also throws 'A second operation was started on this context instance'
  • Fix: a new DbContext per message via IServiceScopeFactory.CreateAsyncScope() or IDbContextFactory<T>
  • Mitigation while fixing: scheduled restarts or ChangeTracker.Clear() per message
  • Prevention: soak test, memory and duration alerts, idempotent handlers, a worker template with a scope per unit of work

⏱ 30-second answer

A steady climb from every restart means something is accumulating. In a worker the usual culprit is a DbContext created once (in the constructor or at the top of ExecuteAsync) and used for every message. The change tracker never forgets: each message adds entities, DetectChanges gets slower on every save, memory grows into gen 2, and the identity map returns already-tracked instances with their old values, which explains the stale data.

I'd confirm with dotnet-counters (GC heap, gen 2, EF active-db-contexts stuck at 1), a dotnet-gcdump full of InternalEntityEntry, and Application Insights showing SaveChanges duration rising. Mitigate with restarts or ChangeTracker.Clear(), then fix properly: a new context per message via IServiceScopeFactory.CreateAsyncScope() or IDbContextFactory<T>. The trade-off is negligible: contexts are cheap to create; long-lived ones are not.

🗣 Full answer (senior)

How I would answer this in an interview

"The shape of the symptoms tells me a lot before I touch a tool. Fast after a restart, slower every hour, memory climbing, and eventually killed: that's accumulation, not a bad query. Add 'acting on stale data' and I'm already suspicious of a long-lived DbContext, because the identity map is the one thing that both grows forever and hands back old values. A tracking query for an entity that's already tracked returns the tracked instance and keeps its in-memory values, even if another service changed the row an hour ago.

For example, at [company] we had [a payments reconciliation worker] reading from [Azure Service Bus]. It was a BackgroundService, and someone had resolved the DbContext once at the top of ExecuteAsync inside a scope that lived for the whole process, because it 'worked in testing'. I attached dotnet-counters and saw the GC heap growing about [150 MB an hour] with frequent gen 2 collections, and the EF Core active-db-contexts counter flat at one. A gcdump showed [~480k] InternalEntityEntry objects. Application Insights showed each SaveChanges getting slower, and the 'stale data' bug was a merchant status changed by the admin portal that the worker never saw, because its tracked copy said 'active'. We restarted it on a schedule that afternoon, then changed it to create a scope per message, and [memory has been flat at ~200 MB and throughput steady since].

The fix is not to tune the tracker, it's to give each unit of work its own context, which is what EF Core is designed for. In a hosted service that means IServiceScopeFactory.CreateAsyncScope() per message, so scoped dependencies work too, or IDbContextFactory<T> if only the context is needed. The mistake I see is people adding ChangeTracker.Clear() and calling it done. It stops the memory growth, but the context still outlives its purpose, and anything else scoped in that long-lived scope has the same problem."


Symptom to cause

Symptom Mechanism
Throughput drops steadily after each restart DetectChanges scans an ever-growing tracked set on every save
Memory climbs, gen 2 collections rise Entries and snapshots stay referenced by the context
Stale data Tracking queries return already-tracked instances with old values
OOM-killed in containers Tracked set exceeds the memory limit
Occasional identity-conflict exceptions A message attaches an entity whose key is already tracked from an earlier message

Diagnosis toolkit

Tool What to look for
dotnet-counters monitor --counters System.Runtime,Microsoft.EntityFrameworkCore GC heap size, gen 2 count, active-db-contexts, save-changes-per-second
dotnet-gcdump collect Top types by count: InternalEntityEntry, your entity types
Application Insights Dependency duration trend for SaveChanges, message processing time, restarts
Code search DbContext resolved in a constructor or once in ExecuteAsync; AddSingleton capturing it

Production example

After moving to a scope per message, the worker's memory stayed flat at [~200 MB] instead of reaching [3 GB] in [~20 hours], message processing p95 dropped from [~1.8 s] at end of day to a steady [~60 ms], and the stale-status incidents stopped.

🔍 What the interviewer is checking

Checks whether the candidate can read symptoms over time, connect them to DbContext lifetime and the identity map, use the right diagnostic tools, and fix the lifetime rather than the symptom.

Green flags

  • Recognises the accumulation pattern and suspects a long-lived context.
  • Explains stale data via the identity map.
  • Uses dotnet-counters and a heap snapshot to prove it.
  • Fixes with a scope or factory per message and mentions idempotency.

Red flags

  • Starts by tuning queries or adding indexes.
  • Registers the context as a singleton.
  • Stops at ChangeTracker.Clear() or scheduled restarts.

📚 Learn in depth

1. Why hosted services are the classic trap

ASP.NET Core request:  scope created per request -> DbContext disposed at end   (bounded)
BackgroundService:     registered as a singleton  -> no request scope at all
                       inject DbContext directly -> ValidateScopes throws (good)
                       create ONE scope at start -> context lives for the process (bad)

AddDbContext registers the context as scoped. Injecting it straight into a hosted service fails validation in Development, so people work around it by creating a scope once, which defeats the purpose.

2. How staleness arises

09:00 worker loads Merchant 7 (Status = Active)      -> tracked
09:30 admin portal sets Merchant 7 Status = Suspended  (different process)
10:00 worker queries Merchant 7 with tracking
      -> SQL runs, row says Suspended
      -> identity map already has Merchant 7 -> returns tracked instance, Status = Active

EF Core does not overwrite tracked entities with query results; that protects unsaved local changes in a normal unit of work, but in a long-lived context it means old data wins.

3. Growth arithmetic

If each message tracks ~20 entities and the worker handles 25,000 messages a day, that's 500,000 tracked entities a day. Every SaveChanges scans all of them, so per-message cost rises linearly over time and total cost quadratically.

4. The fix patterns

loop:
  receive message
  await using scope = scopeFactory.CreateAsyncScope()
  handler = scope.ServiceProvider.GetRequiredService<IMessageHandler>()
  await handler.HandleAsync(message, ct)      // gets a fresh scoped DbContext
  complete message

Or with IDbContextFactory<T> (registered with AddDbContextFactory or alongside AddDbContext): await using var db = await factory.CreateDbContextAsync(ct); per message. With pooling (AddPooledDbContextFactory) creation is cheaper still, and the context is reset when returned.

5. Other things to check in the same review

  • Reads that don't modify should be AsNoTracking().
  • Handlers must be idempotent: Service Bus delivers at least once.
  • Exceptions should not leave a poisoned context: a fresh context per message solves that too.
  • Static caches or singletons holding entity references keep them alive even after the context is gone.

Try it yourself

  1. Write a BackgroundService that creates one context and processes 50,000 fake messages; watch dotnet-counters.
  2. Take a dotnet-gcdump and open it in Visual Studio or PerfView; sort by count.
  3. Change a row from another process and observe the worker reading the old value.
  4. Refactor to CreateAsyncScope() per message and repeat the measurements.
  5. Add a soak test that runs the worker for 30 minutes in CI and asserts the heap stays under a threshold.

💻 Code

Before and after: the worker's processing loop.

// BEFORE: one scope and one DbContext for the life of the process.
public sealed class ReconciliationWorker(IServiceScopeFactory scopes, ServiceBusProcessor processor) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var scope = scopes.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<PaymentsDbContext>();   // lives forever

        processor.ProcessMessageAsync += async args =>
        {
            var msg = args.Message.Body.ToObjectFromJson<SettlementMessage>()!;
            var merchant = await db.Merchants.SingleAsync(m => m.Id == msg.MerchantId); // stale if tracked
            db.Settlements.Add(new Settlement(msg.MerchantId, msg.Amount, merchant.Status));
            await db.SaveChangesAsync();                                              // scans everything ever tracked
            await args.CompleteMessageAsync(args.Message);
        };
        processor.ProcessErrorAsync += _ => Task.CompletedTask;
        await processor.StartProcessingAsync(stoppingToken);
        await Task.Delay(Timeout.Infinite, stoppingToken);
    }
}
namespace Payments.Worker;

using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;

public sealed record SettlementMessage(Guid MessageId, int MerchantId, decimal Amount);

// AFTER: a scope (and so a fresh DbContext) per message.
public sealed class ReconciliationWorker(
    IServiceScopeFactory scopes, ServiceBusProcessor processor, ILogger<ReconciliationWorker> log) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        processor.ProcessMessageAsync += async args =>
        {
            await using var scope = scopes.CreateAsyncScope();
            var handler = scope.ServiceProvider.GetRequiredService<SettlementHandler>();
            var msg = args.Message.Body.ToObjectFromJson<SettlementMessage>()!;
            await handler.HandleAsync(msg, args.CancellationToken);
            await args.CompleteMessageAsync(args.Message, args.CancellationToken);
        };
        processor.ProcessErrorAsync += e =>
        {
            log.LogError(e.Exception, "Service Bus error from {Source}", e.ErrorSource);
            return Task.CompletedTask;
        };
        await processor.StartProcessingAsync(stoppingToken);
        try { await Task.Delay(Timeout.Infinite, stoppingToken); }
        catch (OperationCanceledException) { }
        await processor.StopProcessingAsync(CancellationToken.None);
    }
}

public sealed class SettlementHandler(PaymentsDbContext db)   // scoped: new context per message
{
    public async Task HandleAsync(SettlementMessage msg, CancellationToken ct)
    {
        // Idempotent: Service Bus is at-least-once.
        if (await db.Settlements.AnyAsync(s => s.MessageId == msg.MessageId, ct)) return;

        var status = await db.Merchants.AsNoTracking()            // read-only: always fresh, never tracked
            .Where(m => m.Id == msg.MerchantId)
            .Select(m => m.Status)
            .SingleAsync(ct);

        db.Settlements.Add(new Settlement(msg.MerchantId, msg.Amount, status) { MessageId = msg.MessageId });
        await db.SaveChangesAsync(ct);                            // tracks one entity
    }
}
// Program.cs
builder.Services.AddDbContext<PaymentsDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Payments")));
builder.Services.AddScoped<SettlementHandler>();
builder.Services.AddHostedService<ReconciliationWorker>();

⚠ Common mistakes

  • Mistake: Creating one scope or DbContext at the start of ExecuteAsync and reusing it for every message. Why it is wrong: the tracker grows forever, saves slow down, memory climbs and tracked instances go stale. Instead: a scope or IDbContextFactory context per message.
  • Mistake: Raising MaxConcurrentCalls on the Service Bus processor while handlers share one context. Why it is wrong: DbContext is not thread-safe, so overlapping async handlers throw "A second operation was started on this context instance" or corrupt tracker state. Instead: each concurrent handler gets its own scope and context.
  • Mistake: Treating ChangeTracker.Clear() per message as the full fix. Why it is wrong: it bounds the tracker but leaves a long-lived context and any other scoped services in that scope living for the whole process. Instead: use it only as a mitigation, then scope per unit of work.
  • Mistake: Registering the DbContext as a singleton to silence the scope validation error. Why it is wrong: it creates exactly this leak and makes the context shared across concurrent handlers. Instead: keep AddDbContext scoped and create scopes in the worker.
  • Mistake: Diagnosing by guessing at queries first. Why it is wrong: a steady climb from each restart is accumulation, not a slow query. Instead: plot memory and processing time against time since restart, confirm with counters, then take a heap snapshot to find what accumulates and who holds it.
  • Mistake: Using tracking queries for reference data in workers. Why it is wrong: tracked copies go stale and add to the tracker. Instead: AsNoTracking() projections, or a cache with an explicit expiry.
  • Mistake: Restarting the worker on a schedule and leaving it. Why it is wrong: it hides the bug, and stale data still appears between restarts. Instead: fix the lifetime and keep the restart only until the fix ships.
  • Mistake: Assuming messages are processed exactly once after the fix. Why it is wrong: Service Bus is at-least-once, and a crash after save but before complete redelivers. Instead: make handlers idempotent with a message id.

🏛 Senior insight: trade-offs

Long-lived processes turn every small per-unit cost into a leak. My rule for workers is that a unit of work (a message, a batch, a timer tick) gets its own DI scope, and nothing scoped lives outside it. That one rule prevents tracker growth, stale identity-map reads, poisoned contexts after exceptions and concurrency bugs from shared contexts. I also want a soak test and a memory alert for every worker, because these bugs never show in a five-minute test.

Option When it fits Cost When not to
CreateAsyncScope() per message Handlers with several scoped dependencies A scope per message (cheap) —
IDbContextFactory<T> per message Only the context is needed Manual disposal When other scoped services must share the context
Pooled factory Very high message rates Must not keep state on the context Contexts with per-instance state you don't reset
ChangeTracker.Clear() Emergency mitigation, or chunked batch jobs Context still long-lived As the permanent fix for a worker

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions DetectChanges cost or chunking. Why: Checks change tracker performance knowledge for batch work.
    How to answer

    Every tracked entity costs an entry, an identity-map slot and an original-values snapshot, and DetectChanges scans all of them on every SaveChanges (and on Entries()/Entry()). On one long-lived context the tracked set keeps growing, so each save gets slower and the total becomes roughly quadratic, while memory climbs until the job runs out.

    The fixes:

    • Chunk: save every few hundred to few thousand entities, then ChangeTracker.Clear() or use a new context per chunk.
    • Read with AsNoTracking() or projections.
    • Turn off AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.
    • For set-based changes, skip the tracker with ExecuteUpdate/ExecuteDelete, or SqlBulkCopy for millions of inserts.

    The trade-off: chunking gives up all-or-nothing atomicity, and bypassing the tracker skips interceptors and domain logic.

  2. When: Candidate mentions processing messages concurrently with one context. Why: Checks that the candidate knows DbContext is not thread-safe and how to parallelise.
    How to answer

    A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.

  3. When: Candidate mentions scoped services inside a singleton hosted service. Why: Checks understanding of captive dependencies and ValidateScopes.
    How to answer

    A captive dependency is a shorter-lived service captured by a longer-lived one, usually a scoped DbContext held by a singleton. The scoped instance stops being per-request: in production it is shared across threads (EF's "second operation" exceptions), serves stale data from its identity map, keeps growing its change tracker and is never disposed.

    ValidateScopes = true makes the provider throw when a singleton's graph contains a scoped service or a scoped service is resolved from the root. The host enables it only in Development by default; turn it on everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }). The cost is a small check on resolution and a one-off graph walk at start-up, far cheaper than the outage. Fix by aligning lifetimes, or creating per-operation instances with IDbContextFactory<T> or IServiceScopeFactory.

🛠 Real-world problems: how you handle them

Reconciliation worker leaking tracked entities and reading stale merchant status
Situation
A [payments reconciliation] worker on Azure Container Apps (Australia East) processes [~25,000] Service Bus messages a day into Azure SQL; settlements must use the merchant's current status for compliance.
Signals
Message processing p95 rising from [~60 ms] after each restart to [~1.8 s] by evening; container OOM-killed every [~20 hours] at its [3 GB] limit; a [suspended] merchant received settlements hours after suspension.
Investigation
dotnet-counters on the container showed GC heap growing [~150 MB/hour], gen 2 collections climbing and `active-db-contexts` constant at 1. A dotnet-gcdump showed [~480k] `InternalEntityEntry` objects. Application Insights showed `SaveChanges` dependency time rising steadily. Code review found a scope and `DbContext` created once in `ExecuteAsync`; reproducing the status change locally confirmed the tracked copy won over the database row.
Resolution
Same day: scheduled restarts every [6 hours] and a manual review of settlements for suspended merchants. Fix: a DI scope per message with a scoped handler, `AsNoTracking` projection for merchant status, and idempotency on message id; deployed the next day.
Prevention
A 30-minute soak test in CI asserting heap stays under [400 MB]; Azure Monitor alerts on container memory and processing time; a worker template with a scope per message; a review checklist item for `DbContext` lifetimes in hosted services.

How to tell it (STAR)

**S:** At [company], our [payments reconciliation] worker got slower every day after a release, was OOM-killed roughly daily, and once paid a merchant hours after they'd been suspended. **T:** I led the investigation because it was both a stability and a compliance issue. **A:** dotnet-counters showed steady heap growth with one `DbContext` alive the whole time, and a gcdump showed nearly half a million tracked entities. The worker created one context at start-up, so the identity map kept serving the old merchant status. I put scheduled restarts in place that afternoon, then changed the worker to create a scope per message, read the status with no tracking, and made the handler idempotent. **R:** Memory has stayed flat at [~200 MB], p95 is a steady [~60 ms], and there have been [no] stale-status settlements since.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me