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

📚 Interview question

Your import job tracks hundreds of thousands of entities and SaveChanges keeps getting slower. How does change tracker cost grow with the number of tracked entities, how do you keep it fast for large batches (chunking, ChangeTracker.Clear(), AutoDetectChangesEnabled), and when do you skip it with ExecuteUpdate or ExecuteDelete?

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.

Senior Theory Advanced bulk-operations change-tracking ef-core executeupdate memory performance

🎯 Key points

  • Each tracked entity costs an entry, an identity-map slot and an original-values snapshot, all long-lived objects that get promoted to gen 2
  • DetectChanges is O(tracked entities × properties) and runs on every SaveChanges, Entries() and Entry()
  • Saving repeatedly on one growing context makes total cost roughly quadratic, plus longer gen 2 GC pauses
  • Chunk the work: a few hundred to a few thousand entities per SaveChanges, then ChangeTracker.Clear() or a new context
  • AutoDetectChangesEnabled = false around bulk Add loops, then DetectChanges once (restore in finally)
  • AsNoTracking for all reads in the job; projections where possible
  • ExecuteUpdate / ExecuteDelete (EF Core 7+) for set-based changes: one statement, no tracker, SaveChanges interceptors don't run, so apply audit rules in the call
  • Chunking gives up atomicity: make imports idempotent, or wrap steps that must commit together in one explicit transaction

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 each SaveChanges. If an import keeps one context and calls SaveChanges every 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], call SaveChanges, then ChangeTracker.Clear(), and for the 'mark everything not in the feed as discontinued' step use one ExecuteUpdate instead 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. ExecuteUpdate and ExecuteDelete send one set-based statement with no entities in memory, but they bypass SaveChanges interceptors, 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, SqlBulkCopy beats EF Core by an order of magnitude. The mistake I see is turning off AutoDetectChangesEnabled globally as a 'performance setting': that just makes modified entities silently not save. Chunking and the right tool for each step is what scales."


Where the time and memory go

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

Choosing the tool

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

Production example

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

🔍 What the interviewer is checking

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

  • Explains DetectChanges scanning every tracked entity and the quadratic growth.
  • Uses chunking with ChangeTracker.Clear() or a context per chunk.
  • Knows ExecuteUpdate/ExecuteDelete and their trade-offs (no interceptors, tracked state stale).
  • Measures with dotnet-counters or a memory profile.

Red flags

  • Disables auto-detect globally without understanding it.
  • Saves per row or keeps one context for the whole job.
  • Thinks a bigger MaxBatchSize fixes it.

📚 Learn in depth

1. What one tracked entity costs

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.

2. Why it becomes quadratic

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.

3. When DetectChanges runs automatically

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.

4. Clear() vs a new context

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.

5. ExecuteUpdate and ExecuteDelete

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.

6. Measuring

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.

Try it yourself

  1. Insert 100,000 rows saving every 1,000 on one context; plot time per chunk. Repeat with Clear() after each save.
  2. Run dotnet-counters against both versions and compare GC heap size and gen 2 collections.
  3. Take a dotnet-gcdump mid-run and count InternalEntityEntry instances.
  4. Replace a load-modify-save loop over 50,000 rows with ExecuteUpdateAsync and compare duration and logged SQL.
  5. Call db.Entry(x) inside a loop of 10,000 tracked entities with auto-detect on and off and time it.

💻 Code

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

⚠ Common mistakes

  • Mistake: Keeping one context for a whole import and calling 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.
  • Mistake: Setting 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.
  • Mistake: Loading 100,000 entities to set one flag on each. Why it is wrong: it tracks and snapshots every entity and sends 100,000 UPDATEs. Instead: ExecuteUpdate with a Where.
  • Mistake: Using 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.
  • Mistake: Expecting tracked entities to reflect an 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.
  • Mistake: Calling 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.
  • Mistake: Making the chunk the whole file to stay atomic. Why it is wrong: one huge transaction holds locks and log space and still has the tracker problem. Instead: chunk and make the import idempotent (upsert by natural key, run id), or load into a staging table and merge.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions DetectChanges or batching. Why: Checks the SaveChanges pipeline details behind the cost.
    How to answer

    SaveChanges runs a pipeline:

    1. 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).
    2. Ordering: builds commands per entity and sorts them by the foreign-key graph, so principals are inserted before dependants and dependants deleted before principals.
    3. Batching: groups commands into as few round trips as possible (SQL Server's default MaxBatchSize is 42).
    4. Transaction: wraps them in an implicit transaction when more than one statement is needed, or joins your explicit one.
    5. Fix-up: on SQL Server, 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.

  2. When: Candidate mentions AsNoTracking for the reads in the job. Why: Checks the cost differences between tracking modes.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Supplier feed import slowing to a crawl and running out of memory
Situation
A [retail catalogue] service imports a nightly supplier feed of [~500k] products into Azure SQL (Australia East) from an Azure Container Apps job; prices must be live before [6 am AEST].
Signals
Job duration grew from [~20 minutes] to [over 2 hours]; the container restarted with OOMKilled at [~3.8 GB]; morning price checks failed; Application Insights showed each `SaveChanges` dependency taking longer than the last.
Investigation
`dotnet-counters` showed GC heap climbing steadily and frequent gen 2 collections; `active-db-contexts` stayed at 1 for the whole run. A `dotnet-gcdump` mid-run showed [~400k] `InternalEntityEntry` objects. Code review found one context for the whole job, `SaveChanges` every 1,000 rows, tracking reads of reference data, and a loop loading every product to flag discontinued items.
Resolution
Immediately: increased the container memory to finish that night's run. Then: chunked at [2,000] rows with `ChangeTracker.Clear()` after each save, switched reference-data reads to `AsNoTracking`, replaced the discontinued-flag loop with one `ExecuteUpdate`, and made the import idempotent by upserting on supplier and SKU with a run id.
Prevention
A load test with a [600k-row] synthetic feed in CI weekly; an alert on job duration and container memory; a guideline that batch jobs use `IDbContextFactory` and clear the tracker per chunk; an ADR on when to use `ExecuteUpdate` vs `SaveChanges`.

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.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me