Skip to content

perf: refactor SqlBulkCopy async loops to async/await and eliminate per-row task allocations - #4685

Open
PauloHMattos wants to merge 6 commits into
dotnet:mainfrom
PauloHMattos:perf/sqlbulkcopy-writetoserverasync
Open

PauloHMattos wants to merge 6 commits into
dotnet:mainfrom
PauloHMattos:perf/sqlbulkcopy-writetoserverasync

Conversation

@PauloHMattos

Copy link
Copy Markdown

Description

This PR fixes a long-standing performance and memory allocation bottleneck in SqlBulkCopy when streaming rows asynchronously from a DbDataReader or SqlDataReader source.

While troubleshooting heavy GC pressure during large async bulk copies, we traced the issue back to how SqlBulkCopy handled per-row and per-column continuations. For every single row read, ReadFromRowSourceAsync was wrapping ReadAsync in a ContinueWith(...).Unwrap() delegate chain—even when the underlying socket buffer already had the data ready. On top of that, CopyColumnsAsync and CopyRowsAsync relied on a hand-rolled state machine built around TaskCompletionSource<object> and AsyncHelper.ContinueTaskWithState. For a 100,000-row ingestion, this churned through over 200,000 ThreadPool work items and generated tens of megabytes of short-lived heap allocations.

What Changed

  • Short-circuited synchronous reads: Updated ReadFromRowSourceAsync to check readTask.Status == TaskStatus.RanToCompletion inline. If data is already buffered, it updates _hasMoreRowToCopy directly and returns null without spinning up a task continuation wrapper.
  • Modernized loops with async/await: Replaced the legacy TaskCompletionSource setup with direct C# async/await continuation helpers (CopyColumnsAsyncContinued and CopyRowsLoopAsync).
  • Zero-allocation fast path: The primary row and column loops now run strictly synchronously until I/O actually pends (task != null). If all writes for a row complete synchronously, no async state machine is ever allocated.

Benchmark Summary (100,000 Rows)

Shape Source Batch Size Base Time PR Time Time Δ Base Alloc PR Alloc Alloc Δ
Strings SqlDataReader 0 347.0 ms 190.9 ms -45.0% 70.01 MB 13.61 MB -80.6%
Strings SqlDataReader 10000 213.2 ms 207.5 ms -2.7% 70.00 MB 13.62 MB -80.5%
Strings DataTable 0 288.4 ms 113.2 ms -60.7% 3.13 MB 3.11 MB -0.6%
Strings DataTable 10000 345.5 ms 163.7 ms -52.6% 3.11 MB 3.11 MB 0.0%
Wide SqlDataReader 0 1,948.6 ms 1,634.7 ms -16.1% 254.92 MB 199.63 MB -21.7%
Wide SqlDataReader 10000 1,666.1 ms 1,112.4 ms -33.2% 254.93 MB 199.61 MB -21.7%
Wide DataTable 0 893.5 ms 1,123.0 ms +25.7% 63.38 MB 63.40 MB 0.0%
Wide DataTable 10000 1,333.5 ms 565.8 ms -57.6% 63.41 MB 63.39 MB 0.0%
Numeric SqlDataReader 0 265.6 ms 213.5 ms -19.6% 77.33 MB 20.95 MB -72.9%
Numeric SqlDataReader 10000 300.4 ms 552.6 ms +84.0% 77.33 MB 20.93 MB -72.9%
Numeric DataTable 0 128.7 ms 129.6 ms +0.7% 38.19 MB 38.18 MB 0.0%
Numeric DataTable 10000 196.8 ms 201.8 ms +2.5% 38.18 MB 38.18 MB 0.0%

Note on Outliers: The time regressions in Numeric (Batch 10000) and Wide (Batch 0) reflect environmental noise (CPU/GC contention during execution on a local laptop with parallel processes running), as memory allocations consistently dropped by 70–80% across all async scenarios.

Full benchmark code is available here: https://github.com/PauloHMattos/SqlClientBulkCopyBenchmark

Issues

Fixes #716

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

Replaces the hand-rolled TaskCompletionSource + AsyncHelper.ContinueTaskWithState
state machine in the innermost column-copy loop with async/await.

CopyColumnsAsync now runs a straight-line loop over the row's columns and
returns null while every WriteBulkCopyValue completes synchronously (the
existing Task-or-null contract its caller relies on). The first time a write
pends it hands the remainder of the row to a new async helper,
CopyColumnsAsyncContinued, which awaits only the writes that actually pend.
This removes the per-column TaskCompletionSource, the CopyColumnsAsyncSetupContinuation
closure, and the recursive re-entry.

The unused 'source' parameter on CopyColumnsAsync is dropped: the only caller
(CopyRowsAsync) always called CopyColumnsAsync(0) with no source, so the
source-completion branch was dead code.

Behavior is unchanged: the synchronous fast path never awaits (no
sync-over-async), and exceptions propagate to the caller (sync) or via the
returned Task (async) exactly as before.
This is the change that resolves the bulk of issue dotnet#716. The async
regression was concentrated in the SqlDataReader (true-async-read) source
path, which scheduled roughly two ThreadPool work items per row.

Two hotspots are rewritten:

1. ReadFromRowSourceAsync: the async branch previously did
   ReadAsync(cts).ContinueWith(...).Unwrap(), allocating a continuation and a
   wrapper Task for every row. It now checks for synchronous completion (return
   null, the Task-or-null fast path) and otherwise awaits the read via a small
   async helper, updating _hasMoreRowToCopy inline.

2. CopyRowsAsync: the hand-rolled TaskCompletionSource +
   AsyncHelper.ContinueTaskWithState re-entry (one continuation per pending row
   write and per pending read) is replaced by a synchronous fast-path loop that
   delegates to an async batch loop (CopyRowsLoopAsync) on the first pend. Writes
   and reads are awaited only when they actually pend, so the synchronous path
   never awaits (no sync-over-async) and stays allocation-free.

CheckForCancellation is removed; cancellation is now a
cts.ThrowIfCancellationRequested() inside the async loop and a
Task.FromCanceled() on the synchronous entry, preserving the prior behavior of
only observing cancellation in async mode. The unused 'source' parameter on
CopyRowsAsync is dropped (its only caller passes none). Per-row semantics are
preserved exactly: WriteByte(SQLROW), CheckAndRaiseNotification after each row,
and the _parserLock release/reacquire around synchronous reads.
@PauloHMattos
PauloHMattos force-pushed the perf/sqlbulkcopy-writetoserverasync branch from 770f154 to f8c0031 Compare September 13, 2026 22:07
@PauloHMattos

Copy link
Copy Markdown
Author

@dotnet-policy-service agree company="Inoa"

@PauloHMattos

Copy link
Copy Markdown
Author

@dotnet-policy-service agree

@cheenamalhotra cheenamalhotra added the Performance 📈 Issues that are targeted to performance improvements. label Sep 14, 2026
@mdaigle mdaigle added this to the 8.0.0-preview1 milestone Sep 18, 2026
@mdaigle mdaigle moved this from To triage to In review in SqlClient Board Sep 23, 2026
@mdaigle

mdaigle commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.10236% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.39%. Comparing base (f2310e9) to head (5636382).
⚠️ Report is 54 commits behind head on main.

Files with missing lines Patch % Lines
...Client/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs 81.10% 24 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4685      +/-   ##
==========================================
- Coverage   66.27%   65.39%   -0.88%     
==========================================
  Files         290      286       -4     
  Lines       45062    68567   +23505     
==========================================
+ Hits        29865    44840   +14975     
- Misses      15197    23727    +8530     
Flag Coverage Δ
CI-SqlClient ?
PR-SqlClient-Project 65.39% <81.10%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

The core asynchronous state machine changed substantially and warrants human validation despite the localized scope.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
What changed in this PR

Refactors SqlBulkCopy async row and column loops to reduce allocations and ThreadPool work.

Changes:

  • Adds synchronous fast paths for completed reads and writes.
  • Replaces continuation-based loops with async/await helpers.
  • Preserves cancellation and batching behavior.
File Description
SqlBulkCopy.cs Optimizes asynchronous bulk-copy processing.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

state: this,
scheduler: TaskScheduler.Default
).Unwrap();
Task<bool> readTask = _dbDataReaderRowSource.ReadAsync(cts);

@cheenamalhotra cheenamalhotra left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes for two reproduced regressions: reader faults can commit partial data, and synchronous EOF can report success despite cancellation. Confirmed against base f2310e9 and head f8c0031 on SQL Server with .NET 8, using native and managed SNI. Please preserve the existing behavior and add regression coverage.

// remain. Only reached when the read did not complete synchronously.
private async Task AwaitReadFromDbDataReaderAsync(Task<bool> readTask)
{
_hasMoreRowToCopy = await readTask.ConfigureAwait(false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Reader faults can now commit partial data

Awaiting a faulted task containing OperationCanceledException changes the helper's status to Canceled. That selects cleanupParser: true, sending BulkCopyDone instead of aborting the batch.

Repro: read two rows, then return Task.FromException<bool>(new OperationCanceledException()), with default options and an uncanceled caller token. Base: Faulted, 0 rows committed. PR: Canceled, 2 rows committed.

Preserve fault-versus-cancellation status across the rewritten helpers, and cover task status and destination row count.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AwaitReadFromDbDataReaderAsync still decides fault versus cancellation from cts.IsCancellationRequested, not readTask.IsFaulted/IsCanceled: a reader that cancels the caller token and then returns a faulted OCE task bypasses the marker and still selects cleanupParser: true, finalizing the partial batch. Conversely, a genuinely canceled reader task with an uncanceled caller token is now wrapped as a fault; synchronous reader OCEs after the row loop has pended also bypass this guard. Preserve antecedent status and synchronous-fault semantics across the new await boundaries, and add task-status/destination-row regressions for those cases.

Auto-replied by the GitHub Copilot app

{
_hasMoreRowToCopy = readTask.Result;
return null;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Synchronous EOF bypasses the final cancellation check

Returning null can reach the unconditional source.SetResult(null) branch in WriteToServerInternalRestContinuedAsync, bypassing its async completion branch's cancellation check.

Repro: use the default DbDataReader.ReadAsync; the final Read() cancels the caller token and returns false. With no pending writes, base returns Canceled; PR returns RanToCompletion.

Apply the same final cancellation check to synchronous completion of async bulk copies and add an EOF regression case.

@PauloHMattos

Copy link
Copy Markdown
Author

@cheenamalhotra just pushed the regression tests and fix for P1 (typo in the commit name) and P2.
I'm on vacation right now and using a very underpowered laptop, so I will not run the benchmark again, but It think the fixes are small and will not affect the improvement this PR is making.

Once the review process is finished, if I'm home, I can rerun the benchmark to see where we ended up.

@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

@apoorvdeshmukh apoorvdeshmukh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes on head 9ba026cb220d015e48e962f223e0e7f600397997 compared with base f2310e93f14c2589718551339b7fc7c33a72ca66.

The existing P1 status-preservation fix remains incomplete: faulted reader OCEs can still select partial-batch finalization, while genuine reader cancellation can be converted to a fault. Details and required regression cases are in the follow-up on the existing P1 thread.

The new inline finding identifies unreachable exception unwrapping: the private BulkCopyAbortException escapes instead of the original reader exception. Preserve Faulted status while unwrapping at the actual fault-completion boundary, including initial-read failures.

The synchronous-EOF cancellation source fix is present. Please extend regression coverage for task status, original exception fidelity, destination rows, and post-failure connection behavior. Current-head CI still has a failed aggregate and a canceled job; the author has not rerun performance measurements after the fixes.

This is an AI-assisted, source-inspection review; no local PR builds, SQL reproductions, or benchmarks were executed. CI failure attribution and controlled current-head performance remain verification gaps, not additional proven implementation defects.

Comment on lines +3144 to +3149
Exception inner = task.Exception.InnerException;
if (inner is BulkCopyAbortException abort && abort.InnerException != null)
{
inner = abort.InnerException;
}
source.SetException(inner);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AsyncHelper.ContinueTaskWithState handles faulted tasks itself and never invokes this onSuccess callback, so the new BulkCopyAbortException unwrapping is unreachable. The existing faulted-OCE regression therefore exposes BulkCopyAbortException instead of the original OperationCanceledException, and an initial-read fault never reaches this method. Unwrap at the actual fault-propagation/public-completion boundary while keeping the task Faulted, and extend the regression to assert the original exception type.

@paulmedynski

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Some column/write OperationCanceledException faults are incorrectly converted to cancellation, and added tests violate documented test conventions.

5 open findings

🧠 Review effort: Balanced

Comment on lines +2632 to +2634
private async Task CopyColumnsAsyncContinued(Task pendingWrite, int i)
{
AsyncHelper.ContinueTaskWithState(
task,
source,
state: this,
onSuccess: (object state) =>
await pendingWrite.ConfigureAwait(false);

_stateObj.WriteByte(TdsEnums.SQLROW);

Task writeTask = CopyColumnsAsync(0); // Copy 1 row
Comment on lines +144 to +148
// Regression test: a reader whose ReadAsync returns a *faulted* task carrying
// an OperationCanceledException must surface WriteToServerAsync as Faulted
// (not Canceled) and must not commit the rows already written. A Canceled
// task would select cleanupParser (send BulkCopyDone) and commit partial
// data; a faulted task aborts the batch.
Comment on lines +535 to +539
private static void CreateSingleIntColumnTable(SqlConnection connection, string tableName)
{
DataTestUtility.DropTable(connection, tableName);
using SqlCommand command = connection.CreateCommand();
Helpers.TryExecute(command, $"create table {tableName} (col1 int)");
@apoorvdeshmukh apoorvdeshmukh added the Author attention needed PRs that require author to respond or make updates to PR. label Oct 14, 2026
@github-actions

Copy link
Copy Markdown

@PauloHMattos This pull request has been marked as Author attention needed.

When you have addressed the reviewer feedback and are ready for another review, please post a comment with /ready to remove the label and re-engage reviewers.

@apoorvdeshmukh apoorvdeshmukh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@PauloHMattos Can you address the review comments?

@edwardneal

Copy link
Copy Markdown
Contributor

It's worth noting that #4687 merged earlier this evening, which ported the initial setup phase to use async/await. There'll be some genuine merge conflicts, but it might be easier to address the review feedback now that there's less need to bridge between the per-row native async/await and the outer layers' TaskCompletionSource-based approach.

@PauloHMattos

PauloHMattos commented Oct 24, 2026 •

Copy link
Copy Markdown
Author

It's worth noting that #4687 merged earlier this evening, which ported the initial setup phase to use async/await. There'll be some genuine merge conflicts, but it might be easier to address the review feedback now that there's less need to bridge between the per-row native async/await and the outer layers' TaskCompletionSource-based approach.

@edwardneal There was just 2 conflicts that were easily resolved.
I will not have much time to work on this for the next few days due to work related stuff, so this PR will likely be quiet until the next week.

@cheenamalhotra @apoorvdeshmukh @edwardneal but before I can restart working on this. I need a decision on one behavior question.

Since #4687 made the outer layers of SqlBulkCopy native async/await, an OperationCanceledException that is a fault now makes WriteToServerAsync return a Canceled task with no exception. Examples: a reader returning Task.FromException(new OperationCanceledException()), or ReadAsync/GetValue throwing one synchronously. Before #4687 (f2310e9) the task was Faulted with the original exception. I checked main against SQL Server: the batch is still correctly aborted (0 rows committed), so only the status callers see changed. It wasn't one of the three behavior changes flagged in #4687.

Independently of that, this PR has to keep these errors from being treated as cancellations inside the per-row/per-column loops. Otherwise its new async loops would finalize and commit the partial batch (the P1 repro). That part isn't in question.

What I'd like you to decide is the public contract:

I lean towards A, since the P1 review asked for Faulted with the original exception, and a Canceled status makes reader errors look like user cancellation. I'm happy to go either way.

@edwardneal

Copy link
Copy Markdown
Contributor

Thanks @PauloHMattos, hope the merge helped.

I only expected the three noted behaviour changes from #4687, so the change in the returned Task's state comes as a surprise. Thanks for picking up on this and apologies @cheenamalhotra for missing it earlier.

The conversations around cancellation/exceptions are slightly awkward. I'd draw a distinction between the sources of the exception though:

  • If SqlClient's async code is throwing OperationCancelledExceptions in general, we should treat that as an indication of cancellation. The compiler-generated async state machines will do this, we shouldn't spend our time fighting the state machines by trying to "promote" some cancelled tasks to faulted tasks.
  • Specifically for the parts of SqlClient (such as SqlBulkCopy) where we'll find ourselves calling a user-supplied method we should retain the existing semantics on the way we handle them.

This results in a situation I dislike, but which I think would be too large to change. Assuming a non-signalled CancellationToken, these three ReadAsync implementations would behave differently:

// Returns a Faulted task.
public override Task<bool> ReadAsync(CancellationToken cancellationToken) =>
    Task.FromException<bool>(new OperationCanceledException());

// Throws an exception synchronously.
public override Task<bool> ReadAsync(CancellationToken cancellationToken) =>
    throw new OperationCanceledException();

// Returns a Canceled task.
public override async Task<bool> ReadAsync(CancellationToken cancellationToken) =>
    throw new OperationCanceledException();

The first and second implementations will result in a batch being aborted and all of the previous rows in the batch being discarded. The third will result in the batch being cancelled and all previous rows in the batch being committed. I don't like this distinction, because it means that a client which rewrites their DbDataReader to use modern async/await can find that they've silently changed the commit semantics of the bulk copies which use it.

For compatibility purposes, I'd suggest that we should check the CancellationToken prior to any user-supplied method calls, then wrap any OperationCanceledExceptions received from those method calls in an InvalidOperationException, unless those method calls return tasks which are in the Canceled state. The same principle would apply to both sync and async variations of those methods.

We can then simply allow that translated exception to propagate naturally to the caller without requiring the rest of SqlBulkCopy and all of its upstream callers to think about how the async state machines handle OperationCanceledException. This preserves the batch-handling distinction between faulted reader operations and cancelled reader tasks, and ensures that caller-supplied CancellationTokens are respected.

We'd need to document the new scenario which can generate this exception, but I personally think it'd be a fairly minor change.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Author attention needed PRs that require author to respond or make updates to PR. Performance 📈 Issues that are targeted to performance improvements.

Projects

Status: Waiting for customer

Development

Successfully merging this pull request may close these issues.

Poorer performance using BulkCopy.WriteToServerAsync vs WriteToServer

8 participants