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.
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.
"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 theDbContextonce at the top ofExecuteAsyncinside 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 Coreactive-db-contextscounter flat at one. A gcdump showed [~480k]InternalEntityEntryobjects. Application Insights showed eachSaveChangesgetting 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, orIDbContextFactory<T>if only the context is needed. The mistake I see is people addingChangeTracker.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 | 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 |
| 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 |
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.
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
Red flags
ChangeTracker.Clear() or scheduled restarts.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.
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.
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.
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.
AsNoTracking().BackgroundService that creates one context and processes 50,000 fake messages; watch dotnet-counters.dotnet-gcdump and open it in Visual Studio or PerfView; sort by count.CreateAsyncScope() per message and repeat the measurements.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>();
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.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.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.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.AsNoTracking() projections, or a cache with an explicit expiry.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 |
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:
ChangeTracker.Clear() or use a new context per chunk.AsNoTracking() or projections.AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.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.
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.
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.
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.
Last updated 23 Nov 2026.