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

📚 Interview question

You need to load 5 million rows nightly and update a million existing rows with EF Core on Azure SQL. How do you choose between SaveChanges batching, ExecuteUpdate, SqlBulkCopy and table-valued parameters? Cover batch size, transaction log and locking, and how you would measure the options.

Covers large-scale writes from .NET to SQL Server: SaveChanges batching and MaxBatchSize, chunked ExecuteUpdate, SqlBulkCopy into staging tables with MERGE, table-valued parameters, transaction log, lock escalation and how to benchmark them.

Senior Theory Advanced azure-sql bulk-operations ef-core executeupdate performance sqlbulkcopy

🎯 Key points

  • SaveChanges batches commands (SQL Server provider default MaxBatchSize 42; configurable) but still sends one statement per row and tracks every entity
  • ExecuteUpdate / ExecuteDelete: one set-based statement, no tracking, no SaveChanges interceptors, chunk by key range
  • SqlBulkCopy streams rows with TDS bulk insert into a staging table; triggers and check constraints are skipped unless FireTriggers / CheckConstraints are set
  • Staging table + MERGE or UPDATE ... JOIN for upserts and bulk updates
  • Table-valued parameters for thousands of rows in a set-based statement
  • Chunk size trades round trips against log, lock escalation (about 5,000 locks) and restart cost; pick it by measuring
  • Bulk paths bypass concurrency tokens and audit interceptors: handle them in the SQL
  • Measure rows per second, avg_log_write_percent, blocking and worker memory with production-sized data

⏱ 30-second answer

Pick by volume and shape. SaveChanges batches commands (the SQL Server provider defaults to 42 statements per batch) but still runs one statement per row and tracks every entity, so it is fine for thousands of rows, not millions. ExecuteUpdate/ExecuteDelete run one set-based statement with no tracking; for a million rows I chunk by key range so each transaction stays short. For 5 million inserts, SqlBulkCopy streams rows using the bulk-insert protocol, ideally into a staging table, followed by a set-based MERGE or UPDATE ... JOIN. Table-valued parameters suit thousands of rows sent into one statement. Batch size trades round trips against transaction log growth, lock escalation (about 5,000 locks) and Azure SQL log rate limits. I decide by measuring rows per second and log usage on production-sized data.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I ask is how many rows and what shape: inserts, updates by a rule, or upserts from a file. EF Core's SaveChanges is great for business transactions, but for millions of rows it's the wrong tool. It does batch, the SQL Server provider sends up to 42 statements per round trip by default, but each row is still its own INSERT or UPDATE, every entity sits in the change tracker, and DetectChanges gets slower as the tracker grows.

For updates that follow a rule, like 'mark all orders older than 90 days as archived', ExecuteUpdate sends one UPDATE statement and never loads the rows. At a million rows I still chunk it, say 10,000 to 50,000 rows per statement by primary key range, because one giant UPDATE holds locks, escalates to a table lock and fills the transaction log, and on Azure SQL log generation is rate-governed by the service tier. For the nightly 5 million row load, I use SqlBulkCopy into a staging table. It uses the bulk insert protocol, so it reaches hundreds of thousands of rows per second, and the staging table keeps the live table untouched until a set-based MERGE or UPDATE ... FROM ... JOIN applies the changes in chunks. For a few thousand rows from an API call, a table-valued parameter into one statement is a nice middle ground.

For example, at [company] we had a nightly product feed of [about 4 million rows] that ran through SaveChanges and took [over two hours]. I [moved it to SqlBulkCopy into a staging table and a chunked MERGE], and it dropped to [about 6 minutes]. The mistake I see is picking a batch size or a library from a blog post. I measure rows per second, log usage and blocking on a copy of production, because Azure SQL tier limits change the answer."


Options by volume

Option Rows Mechanism Tracks entities Fires SaveChanges interceptors
SaveChanges with AddRange Up to tens of thousands One statement per row, batched (default 42 per round trip) Yes Yes
ExecuteUpdate / ExecuteDelete Any, chunked One set-based statement No No (command interceptors still see it)
Table-valued parameter Thousands One statement over a TVP No No
SqlBulkCopy Hundreds of thousands to millions TDS bulk insert stream No No
Third-party (e.g. EFCore.BulkExtensions) Large Wraps SqlBulkCopy and MERGE Optional No

EFCore.BulkExtensions is dual-licensed: free under a community licence for organisations under US$1 million annual revenue, otherwise commercial. Check the licence before adopting it; an MIT fork exists.

What batch size trades off

Smaller batches Larger batches
More round trips Fewer round trips
Short transactions, little blocking Long transactions, lock escalation past ~5,000 locks
Log can truncate between batches Large log use; Azure SQL log rate throttling
Easy restart from a checkpoint Large rework on failure

Production example

A nightly product feed [in a system I worked on] inserted and updated about 4 million rows through SaveChanges in 1,000-entity chunks and took over two hours, with the worker reaching 3 GB of memory. SqlBulkCopy into a heap staging table (about 90 seconds) followed by a MERGE in 50,000-row key ranges (about 4 minutes) brought the job to about 6 minutes and 200 MB of memory.

🔍 What the interviewer is checking

Checks that the candidate can pick the right write mechanism for the volume, understands the database-side costs (log, locks, Azure SQL governance), and measures instead of guessing.

Green flags

  • Knows SaveChanges batches but is row-oriented and tracks entities
  • Chunks ExecuteUpdate and explains lock escalation and log growth
  • Uses SqlBulkCopy into staging with a set-based apply
  • Mentions Azure SQL log rate limits and how to observe them
  • Notes that bulk paths bypass interceptors and audit logic

Red flags

  • Loops over entities with SaveChanges per row
  • Runs one giant transaction for millions of rows
  • Picks a library without considering licensing or what it bypasses

📚 Learn in depth

1. What SaveChanges sends

AddRange(10,000 entities) -> SaveChanges
  DetectChanges over the tracker
  -> batch 1: INSERT ...; INSERT ...; (up to MaxBatchSize = 42 statements, or a MERGE ... OUTPUT for generated keys)
  -> batch 2: ...
  -> ~240 round trips, one transaction

The SQL Server provider combines inserts for the same table, often using MERGE ... OUTPUT or INSERT ... OUTPUT to read generated keys back, but it is still row-oriented and every entity keeps a snapshot in memory. You can change the batch with UseSqlServer(cs, o => o.MaxBatchSize(100)); the default came from benchmarks, so measure before changing it.

2. ExecuteUpdate and chunking

UPDATE [o] SET [o].[Status] = 3
FROM [Orders] AS [o]
WHERE [o].[CreatedAt] < @cutoff AND [o].[Status] = 1 AND [o].[Id] > @from AND [o].[Id] <= @to

One statement updates every matching row server-side. Unchunked, a million-row UPDATE takes row or page locks until SQL Server escalates to a table lock (it tries at about 5,000 locks on one object), blocking every reader not using RCSI, and the whole change must fit in the log until it commits. Chunking by key range keeps each transaction small; on Azure SQL with accelerated database recovery and the full recovery model, the log can then be backed up and reused. EF Core 10 also lets ExecuteUpdate take a normal lambda for setters, which makes conditional setters easier to build.

3. SqlBulkCopy

SqlBulkCopy uses the TDS bulk load protocol: rows stream in large buffers without a statement per row. Key options: BatchSize (rows per commit), EnableStreaming with an IDataReader or IAsyncEnumerable source to avoid buffering everything, SqlBulkCopyOptions.TableLock for faster loads into an empty staging heap, and ColumnMappings. It inserts only; updates and upserts happen in SQL afterwards.

file / API  ->  IDataReader  ->  SqlBulkCopy  ->  staging heap  ->  MERGE in key ranges  ->  live table

4. Table-valued parameters

A user-defined table type lets you send a DataTable or IEnumerable<SqlDataRecord> as one parameter and join it in a set-based statement. Good for thousands of rows per call; the parameter is materialised in tempdb, and very large TVPs are slower than bulk copy.

5. Azure SQL limits

Azure SQL governs log generation rate per service tier, so a bulk load can be throttled no matter how fast the client is: waits show as LOG_RATE_GOVERNOR. Hyperscale and Business Critical have different limits. Scaling up for the load window or spreading work over time are both valid answers.

6. Measuring

  • BenchmarkDotNet or a simple stopwatch harness with a production-sized dataset.
  • sys.dm_db_resource_stats for avg_log_write_percent and CPU during the load.
  • sys.dm_tran_locks and blocked-process reports for escalation and blocking.
  • dotnet-counters for allocation rate and GC heap size in the worker.

Try it yourself

  1. Insert 200,000 rows with AddRange + SaveChanges, then with SqlBulkCopy, and compare rows per second and peak memory.
  2. Run a 1 million row ExecuteUpdate with and without chunking while another session reads the table; watch sys.dm_tran_locks for escalation.
  3. Change MaxBatchSize to 10, 42 and 200 and benchmark a 20,000-row insert.
  4. Load a staging table with SqlBulkCopy and write a chunked MERGE; check avg_log_write_percent in sys.dm_db_resource_stats.
  5. Send 5,000 rows through a TVP and compare with the same data via SqlBulkCopy.

💻 Code

A nightly import: SqlBulkCopy into staging, then a chunked set-based apply; plus a chunked ExecuteUpdate for rule-based updates.

namespace Shop.Imports;

using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

public sealed record ProductFeedRow(string Sku, string Name, decimal Price);

public sealed class ProductFeedImporter(ShopDbContext db, ILogger<ProductFeedImporter> logger)
{
    public async Task ImportAsync(IAsyncEnumerable<ProductFeedRow> rows, CancellationToken ct)
    {
        var connection = (SqlConnection)db.Database.GetDbConnection();
        await db.Database.OpenConnectionAsync(ct);
        try
        {
            await db.Database.ExecuteSqlAsync($"TRUNCATE TABLE staging.ProductFeed", ct);

            using var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, externalTransaction: null)
            {
                DestinationTableName = "staging.ProductFeed",
                BatchSize = 50_000,          // rows per commit: keeps log use bounded
                EnableStreaming = true,
                BulkCopyTimeout = 0
            };
            bulk.ColumnMappings.Add(nameof(ProductFeedRow.Sku), "Sku");
            bulk.ColumnMappings.Add(nameof(ProductFeedRow.Name), "Name");
            bulk.ColumnMappings.Add(nameof(ProductFeedRow.Price), "Price");

            await bulk.WriteToServerAsync(await ToDataTableAsync(rows, ct), ct);

            // Apply in key ranges so each transaction stays short and lock escalation is avoided.
            var maxId = await db.Database.SqlQuery<int>($"SELECT ISNULL(MAX(Id), 0) AS [Value] FROM staging.ProductFeed").SingleAsync(ct);
            for (var from = 0; from < maxId; from += 50_000)
            {
                var to = from + 50_000;
                var affected = await db.Database.ExecuteSqlAsync($"EXEC dbo.ApplyProductFeedRange @From = {from}, @To = {to}", ct);
                logger.LogInformation("Applied feed rows {From}-{To}: {Affected} changed", from, to, affected);
            }
        }
        finally
        {
            await db.Database.CloseConnectionAsync();
        }
    }

    // Kept simple for the example; for very large feeds implement an IDataReader over the stream instead.
    private static async Task<DataTable> ToDataTableAsync(IAsyncEnumerable<ProductFeedRow> rows, CancellationToken ct)
    {
        var table = new DataTable();
        table.Columns.Add("Sku", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Price", typeof(decimal));
        await foreach (var r in rows.WithCancellation(ct)) table.Rows.Add(r.Sku, r.Name, r.Price);
        return table;
    }
}

public sealed class OrderArchiver(ShopDbContext db)
{
    // Rule-based update without loading entities, chunked by primary key.
    public async Task<int> ArchiveAsync(DateTime cutoff, CancellationToken ct)
    {
        var total = 0;
        var maxId = await db.Orders.MaxAsync(o => (int?)o.Id, ct) ?? 0;
        for (var from = 0; from < maxId; from += 20_000)
        {
            var to = from + 20_000;
            total += await db.Orders
                .Where(o => o.Id > from && o.Id <= to && o.CreatedAt < cutoff && o.Status == OrderStatus.Paid)
                .ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, OrderStatus.Archived), ct);
        }
        return total;
    }
}
-- Applies one key range of the staging table (staging.ProductFeed has an IDENTITY Id).
CREATE OR ALTER PROCEDURE dbo.ApplyProductFeedRange @From int, @To int AS
BEGIN
    SET NOCOUNT ON;
    MERGE dbo.Products WITH (HOLDLOCK) AS t
    USING (SELECT Sku, Name, Price FROM staging.ProductFeed WHERE Id > @From AND Id <= @To) AS s
        ON t.Sku = s.Sku
    WHEN MATCHED AND (t.Name <> s.Name OR t.Price <> s.Price) THEN
        UPDATE SET t.Name = s.Name, t.Price = s.Price
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (Sku, Name, Price) VALUES (s.Sku, s.Name, s.Price);
END

⚠ Common mistakes

  • Mistake: Importing millions of rows with AddRange and one SaveChanges. Why it is wrong: one statement per row, a huge tracker and one enormous transaction. Instead: SqlBulkCopy into staging and a set-based apply.
  • Mistake: One unchunked ExecuteUpdate over a million rows at peak time. Why it is wrong: lock escalation blocks readers and the log grows until commit. Instead: chunk by key range (start around 10,000 to 50,000 rows and tune by measurement; the right size depends on row width, indexes and the service tier) and run off-peak or with RCSI on.
  • Mistake: Forgetting that ExecuteUpdate and bulk copy bypass the change tracker. Why it is wrong: audit columns set in a SaveChangesInterceptor, concurrency tokens and in-memory entities are not updated, and no optimistic concurrency check happens. Instead: set audit columns explicitly in the statement (SetProperty(o => o.ModifiedAt, now)), add the expected RowVersion to the WHERE when a row-level check matters, and clear or reload tracked entities afterwards.
  • Mistake: Assuming SqlBulkCopy behaves like INSERT. Why it is wrong: by default it does not fire triggers and does not check CHECK or FOREIGN KEY constraints, which leaves constraints marked untrusted. Instead: set SqlBulkCopyOptions.FireTriggers and CheckConstraints when the target relies on them, or load a staging table without constraints and let the MERGE into the real table enforce them. Note that EF Core 7+ also needs HasTrigger(...) configured on tables with triggers, because its default OUTPUT clause fails on them.
  • Mistake: Treating a failed bulk copy as all-or-nothing. Why it is wrong: with BatchSize set and no external transaction, each batch commits on its own, so a failure leaves a partial load. Instead: load staging, truncate and reload it on failure, apply to the live table in idempotent chunks, and record a checkpoint; wrap transient failures (Azure SQL errors such as 40613) in a retry around the whole chunk.
  • Mistake: Bulk copying straight into the live table. Why it is wrong: a failed load leaves partial data and the table is locked during the load. Instead: load staging, validate, then apply.
  • Mistake: Raising MaxBatchSize to 1,000 because bigger seems faster. Why it is wrong: SQL Server has a 2,100 parameter limit per command and gains flatten quickly. Instead: benchmark a few values on real data.
  • Mistake: Adopting a bulk library without checking its licence. Why it is wrong: EFCore.BulkExtensions needs a commercial licence above the revenue threshold. Instead: review the licence, use the MIT fork, or write the SqlBulkCopy code yourself.
  • Mistake: Ignoring Azure SQL log rate limits. Why it is wrong: the load is throttled (LOG_RATE_GOVERNOR waits) regardless of client speed. Instead: watch avg_log_write_percent in sys.dm_db_resource_stats or the Azure portal's Log IO percentage metric, chunk, and scale the tier for the window if needed.

🏛 Senior insight: trade-offs

At scale the bottleneck moves from the .NET code to the database's log and locks, so the senior answer is about the shape of the work: stream rows in with bulk copy, transform set-based in SQL, commit in chunks, and make the job restartable from the last committed chunk. I keep EF Core for the business transactions around it and accept that bulk paths bypass interceptors, which means audit fields and domain events must be handled explicitly there.

Option When it fits Cost When not to
SaveChanges batching Business writes, up to tens of thousands of rows Tracking memory, row-by-row SQL Millions of rows
Chunked ExecuteUpdate Rule-based updates or deletes Bypasses tracking and SaveChanges interceptors Per-row logic that needs domain code
SqlBulkCopy + staging + MERGE Nightly loads, feeds, migrations More SQL to maintain Small, interactive writes
TVP Thousands of rows from one request User-defined type to version Millions of rows

I measure rows per second, avg_log_write_percent, blocking and worker memory on a production-sized copy, and I record the chosen batch size and why in the job's README or an ADR.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ExecuteUpdate or SqlBulkCopy Why: Checks the mid-level detail of bulk options and what skipping the change tracker means
    How to answer

    For set-based changes use ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+): one UPDATE/DELETE statement, no entities loaded, and in EF Core 10 the setters can be a normal lambda. For inserts, AddRange + SaveChanges already batches commands (default 42 statements per batch on SQL Server) with MERGE ... OUTPUT for keys, which is fine up to tens of thousands of rows. Beyond that, SqlBulkCopy streams rows with the bulk-load protocol and is an order of magnitude faster; for upserts use a staging table + MERGE or a table-valued parameter. Third-party libraries wrap these, but check their licences. Skipping the change tracker has costs: tracked entities go stale, SaveChanges interceptors (audit, soft delete) don't run, and concurrency tokens aren't checked. The trade-off is raw speed versus the safety nets EF normally gives you.

  2. When: Candidate mentions the change tracker slowing down large batches Why: Checks they know how tracker cost grows and how ChangeTracker.Clear() and chunking help
    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.

  3. When: Candidate mentions chunking or committing in batches Why: Checks they design for idempotency and checkpoints rather than all-or-nothing
    How to answer

    Make each chunk idempotent and record progress. Load into a staging table with a batch id, apply changes with a set-based MERGE keyed on the business key so re-running a chunk changes nothing, and write the last committed key range to a checkpoint table in the same transaction as the chunk. On restart, read the checkpoint and continue. Keep the import's input (file or snapshot) immutable so a re-run sees the same data.

🛠 Real-world problems: how you handle them

Nightly product feed taking over two hours
Situation
A retail platform imported a supplier feed of [about 4 million] products nightly into Azure SQL [General Purpose, 8 vCores] using a .NET worker and EF Core. The job had to finish before [5 am] when Australian stores opened.
Signals
The job ran past [7 am] on some nights; the worker's memory reached about 3 GB; Azure SQL showed `LOG_RATE_GOVERNOR` waits and `avg_log_write_percent` near 100%; store staff saw stale prices.
Investigation
dotnet-counters showed the GC heap growing through the run; EF Core logs showed batched single-row INSERT and UPDATE statements; `sys.dm_db_resource_stats` showed log write saturation; the code used `AddRange` and `SaveChanges` per 1,000 rows with one long-lived context.
Resolution
Immediately: cleared the change tracker after each chunk to stop the memory growth. Then rewrote the load as `SqlBulkCopy` into a staging heap and a stored procedure applying a `MERGE` per 50,000-row key range, with a checkpoint table for restarts.
Prevention
A run-time and row-count dashboard with an alert if the job is not done by [4 am]; a load test on a production-sized copy before changes; an ADR documenting the bulk path, the batch size chosen and that audit columns are set in the MERGE.

How to tell it (STAR)

**S:** Our nightly supplier feed of about [4 million] products took over two hours and sometimes finished after stores opened, so prices were stale. **T:** I was asked to get it reliably under [30 minutes]. **A:** I measured first: dotnet-counters showed the worker's heap growing to 3 GB, and Azure SQL was saturating its log rate because EF Core sent row-by-row statements. I moved the load to SqlBulkCopy into a staging table, applied changes with a MERGE in 50,000-row ranges so each transaction was short, and added a checkpoint so a failure could resume. **R:** The job now runs in about [6 minutes] using around [200 MB], log waits disappeared, and we haven't missed the [5 am] deadline since.

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me