Covers EF Core change tracker performance at scale: per-entity memory for entries and snapshots, DetectChanges cost proportional to the tracked set, the quadratic slowdown of save-per-row on one context, chunking with ChangeTracker.Clear() or a context per chunk, disabling AutoDetectChanges safely, and when to bypass the tracker with ExecuteUpdate, ExecuteDelete or SqlBulkCopy.
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.
"The change tracker is built for request-sized units of work. For each tracked entity EF Core keeps an internal entry, a slot in the identity map and a snapshot of every property's original value, so memory is roughly the entity again plus overhead. The real problem is
DetectChanges: it compares every tracked entity with its snapshot, and it runs automatically on eachSaveChanges. If an import keeps one context and callsSaveChangesevery 1,000 rows, the first save scans 1,000 entities, the hundredth scans 100,000. Total work grows with the square of the row count, which is exactly the 'it starts fast and gets slower and slower' curve, and the GC has to keep promoting all those objects to gen 2.For example, at [company] we had [a nightly product feed import] of [~500k] rows that went from [minutes in testing] to [over two hours and an OutOfMemoryException] in production. The fix was boring: read reference data with
AsNoTracking, process in chunks of [2,000], callSaveChanges, thenChangeTracker.Clear(), and for the 'mark everything not in the feed as discontinued' step use oneExecuteUpdateinstead of loading entities. [It went to about six minutes with flat memory around 300 MB.]I also know when the tracker is the wrong tool altogether.
ExecuteUpdateandExecuteDeletesend one set-based statement with no entities in memory, but they bypassSaveChangesinterceptors, so audit columns or soft-delete logic implemented there won't run, and tracked entities in the same context aren't updated. For millions of plain inserts,SqlBulkCopybeats EF Core by an order of magnitude. The mistake I see is turning offAutoDetectChangesEnabledglobally as a 'performance setting': that just makes modified entities silently not save. Chunking and the right tool for each step is what scales."
| Cost | Grows with | Mitigation |
|---|---|---|
| Entity + entry + snapshot memory | Tracked entities | Chunk + Clear(), no-tracking reads |
DetectChanges CPU |
Tracked entities × properties | Fewer tracked, or disable auto-detect around Add loops |
| Identity-map lookups during queries | Tracked entities | No-tracking reads |
| Gen 2 GC pauses | Long-lived object graph | Short-lived contexts |
| Round trips | Number of SaveChanges and batch size |
One save per chunk, batching |
| Task | Tool | Why |
|---|---|---|
| Insert/update with per-row logic, 10k–1M rows | Chunked SaveChanges + Clear() |
Keeps domain logic and interceptors |
| Same change to many rows | ExecuteUpdate |
One statement, nothing tracked |
| Delete many rows | ExecuteDelete (in batches with Take on huge tables if locking matters) |
One statement |
| Millions of plain inserts | SqlBulkCopy or a TVP |
Minimal logging, streaming |
With one context and a save every [1,000] rows, a [500k-row] import took [2h 10m] and peaked at [3.8 GB] before failing; chunking with Clear() and replacing a load-and-flag loop with ExecuteUpdate took it to [~6 minutes] at a flat [~300 MB], with gen 2 collections dropping from [hundreds] to [a handful].
Checks whether the candidate understands why change tracker cost grows with the tracked set and can choose between chunking, tuning and bypassing it.
Green flags
DetectChanges scanning every tracked entity and the quadratic growth.ChangeTracker.Clear() or a context per chunk.ExecuteUpdate/ExecuteDelete and their trade-offs (no interceptors, tracked state stale).Red flags
MaxBatchSize fixes it.your entity object (fields)
InternalEntityEntry (state, flags, references)
original values snapshot (one slot per property; value types boxed or stored in typed arrays)
identity map entry (key -> entry)
relationship snapshot (navigations and FKs for fix-up)
For a 20-property entity this can easily be a few hundred bytes to a kilobyte on top of the entity itself.
chunk size c, total rows n, one context, save after each chunk:
save 1 scans c, save 2 scans 2c, ... save n/c scans n
total scanned = c(1 + 2 + ... + n/c) ≈ n² / 2c
with Clear() after each save:
every save scans c
total scanned = n
For n = 500,000 and c = 1,000 that is about 125 million entity comparisons versus 500,000.
SaveChanges/SaveChangesAsync, ChangeTracker.Entries(), DbContext.Entry(), ChangeTracker.HasChanges(), and DbSet.Local access. Calling Entry() inside a loop over tracked entities therefore triggers a scan per iteration, another quadratic trap. With AutoDetectChangesEnabled = false, none of these scan, and you call ChangeTracker.DetectChanges() once yourself.
ChangeTracker.Clear() (EF Core 5+) detaches every entity in one operation, much faster than detaching individually. A new context per chunk achieves the same and also resets any other state; with IDbContextFactory<T> it is cheap. Either way, nothing tracked survives between chunks, so references to entities from earlier chunks are now detached.
await db.Products
.Where(p => p.SupplierId == supplierId && p.LastSeenInFeed < runStartedAt)
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.IsDiscontinued, true)
.SetProperty(p => p.ModifiedAt, runStartedAt), ct);
UPDATE [p]
SET [p].[IsDiscontinued] = CAST(1 AS bit),
[p].[ModifiedAt] = @runStartedAt
FROM [Products] AS [p]
WHERE [p].[SupplierId] = @supplierId AND [p].[LastSeenInFeed] < @runStartedAt
They execute immediately (not on SaveChanges), are not batched with tracked changes, don't update tracked instances, and skip SaveChanges interceptors. In EF Core 10 the setters argument can also be a regular lambda with statements, which makes conditional setters easier. A single UPDATE of millions of rows holds locks and grows the log, so for very large tables run it in key ranges.
dotnet-counters monitor --counters Microsoft.EntityFrameworkCore,System.Runtime -n ImportJob shows active-db-contexts, total-save-changes, save-changes-per-second, GC heap size and gen 2 counts. A memory snapshot (dotnet-gcdump) of a slowing job will show huge numbers of InternalEntityEntry objects.
Clear() after each save.dotnet-counters against both versions and compare GC heap size and gen 2 collections.dotnet-gcdump mid-run and count InternalEntityEntry instances.ExecuteUpdateAsync and compare duration and logged SQL.db.Entry(x) inside a loop of 10,000 tracked entities with auto-detect on and off and time it.A chunked import with a bounded tracker, and a set-based step that skips it.
namespace Catalogue.Import;
using Microsoft.EntityFrameworkCore;
public sealed record FeedRow(string Sku, string Name, decimal Price);
public sealed class ProductFeedImporter(IDbContextFactory<CatalogueDbContext> factory, TimeProvider clock)
{
private const int ChunkSize = 2_000; // measure: usually 500-5,000 is the sweet spot
public async Task ImportAsync(int supplierId, IAsyncEnumerable<FeedRow> rows, CancellationToken ct)
{
var runStartedAt = clock.GetUtcNow();
await using var db = await factory.CreateDbContextAsync(ct);
var buffer = new List<FeedRow>(ChunkSize);
await foreach (var row in rows.WithCancellation(ct))
{
buffer.Add(row);
if (buffer.Count == ChunkSize)
{
await SaveChunkAsync(db, supplierId, buffer, runStartedAt, ct);
buffer.Clear();
}
}
if (buffer.Count > 0) await SaveChunkAsync(db, supplierId, buffer, runStartedAt, ct);
// Set-based: one UPDATE, no entities in memory. Bypasses SaveChanges interceptors,
// so ModifiedAt is set explicitly here.
await db.Products
.Where(p => p.SupplierId == supplierId && p.LastSeenInFeed < runStartedAt && !p.IsDiscontinued)
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.IsDiscontinued, true)
.SetProperty(p => p.ModifiedAt, runStartedAt), ct);
}
private static async Task SaveChunkAsync(CatalogueDbContext db, int supplierId, List<FeedRow> chunk,
DateTimeOffset runStartedAt, CancellationToken ct)
{
var skus = chunk.Select(r => r.Sku).ToList();
var existing = await db.Products // tracked: we will modify these
.Where(p => p.SupplierId == supplierId && skus.Contains(p.Sku))
.ToDictionaryAsync(p => p.Sku, ct);
foreach (var row in chunk)
{
if (!existing.TryGetValue(row.Sku, out var product))
{
product = new Product { SupplierId = supplierId, Sku = row.Sku };
db.Products.Add(product);
}
product.Name = row.Name;
product.Price = row.Price;
product.LastSeenInFeed = runStartedAt;
}
await db.SaveChangesAsync(ct); // scans only this chunk
db.ChangeTracker.Clear(); // keep the tracked set bounded
}
}
dotnet-counters monitor -n Catalogue.Import --counters Microsoft.EntityFrameworkCore,System.Runtime
SaveChanges periodically. Why it is wrong: the tracked set grows, so each DetectChanges scans everything saved so far: quadratic time and unbounded memory. Instead: ChangeTracker.Clear() or a new context after each chunk.AutoDetectChangesEnabled = false globally for speed. Why it is wrong: property changes on tracked entities are no longer detected and are silently not saved. Instead: disable it only around bulk Add loops and call DetectChanges() once, restoring it in finally.ExecuteUpdate with a Where.ExecuteUpdate/ExecuteDelete where audit or soft delete lives in a SaveChangesInterceptor. Why it is wrong: they bypass SaveChanges, so those rules don't run. Instead: set audit columns in the call, or keep that path on SaveChanges.ExecuteUpdate. Why it is wrong: it changes rows in the database only; tracked instances keep old values. Instead: run it before loading, or Clear()/reload afterwards.db.Entry(entity) inside a loop over thousands of tracked entities. Why it is wrong: each call triggers DetectChanges. Instead: call DetectChanges once and use ChangeTracker.Entries() once, or disable auto-detect for the loop.The tracker is a unit-of-work tool, and its costs are linear in what it holds. When a job is slow I ask two questions: how many entities are tracked at the slowest point, and does each step need per-entity logic at all? Usually most of the job is set-based work dressed up as a loop. I also design imports to be idempotent, because chunking gives up atomicity: a rerun after a failure must converge on the same result. Where an ExecuteUpdate and a SaveChanges really must succeed or fail together, I wrap both in db.Database.BeginTransactionAsync() (with the execution strategy's ExecuteAsync if retries are on) rather than reaching for TransactionScope, and keep that transaction short so it doesn't hold locks across the whole import.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Chunk + Clear() |
Per-row logic, tens of thousands to millions of rows | Not atomic across chunks | When the whole set must commit together |
AutoDetectChangesEnabled = false |
Large Add-only loops |
You must call DetectChanges |
Code that modifies tracked entities |
ExecuteUpdate/ExecuteDelete |
Same change to many rows | Bypasses interceptors and tracked state | Per-row domain rules |
| Explicit transaction around steps | A set-based step and a tracked save must commit together | Locks held for the transaction | Spanning a whole multi-minute import |
SqlBulkCopy / staging + MERGE |
Millions of inserts or upserts | Plain ADO.NET, no graph fix-up | Small or graph-shaped data |
SaveChanges runs a pipeline:
DetectChanges: compares every tracked entity with its original-values snapshot and marks changed properties Modified (skipped if AutoDetectChangesEnabled is false, so you must call it yourself).MaxBatchSize is 42).INSERT ... OUTPUT INSERTED.[Id] returns identity keys and UPDATE ... OUTPUT INSERTED.[RowVersion] returns new row versions; EF Core replaces temporary keys, propagates them to foreign keys, then marks everything Unchanged.The trade-off: one call gives atomicity and few round trips, but its cost grows with every tracked entity.
A tracking query (the default) adds every entity to the change tracker: EF Core keeps an identity map (one instance per key) and a snapshot of original values, so SaveChanges can detect edits. That costs memory and time.
AsNoTracking() skips both: fastest and leanest, but if the same row appears twice (e.g. the same customer on many orders via Include), you get separate instances.AsNoTrackingWithIdentityResolution() also skips the snapshot, but uses a temporary identity map during that query, so duplicates share one instance; the tracker is thrown away afterwards.I use tracking for entities I will modify, AsNoTracking for reads, and identity resolution when a no-tracking graph has shared references.
How to tell it (STAR)
**S:** At [company], our nightly supplier import of [~500k] products had grown from [20 minutes] to over two hours and then started crashing out of memory, so prices weren't updated by [6 am]. **T:** I owned the fix. **A:** I watched it with dotnet-counters and took a gcdump, which showed hundreds of thousands of tracked entities in one long-lived context, with each `SaveChanges` scanning all of them. I chunked the import with `ChangeTracker.Clear()` after each save, made reference reads no-tracking, replaced a load-and-flag loop with a single `ExecuteUpdate`, and made the import idempotent so a rerun is safe. **R:** It now runs in [about 6 minutes] with flat memory around [300 MB], and it hasn't missed the deadline since.
Last updated 23 Nov 2026.