Skip to content

Huge performance problem with async #1562

Open

Description

@equist

We are trying to scale an application that uses ASP.NET Identity (which is all async) and we have huge performance issues with all async work against SqlClient (we believe it has boiled down to this). We have investigated and tried many different things for a couple of weeks, and we now have very little isolated code that performs more or less equally bad all the time. The code has implementation of both sync and async calls with huge differences between them. We have read about the issues for big fields, but we see the problem on all our queries (without any big fields) and the reproduced slow calls below has no large fields.

We run in Azure with an App Service plan of P1V2 scaled to two instances and an SQL Azure Premium P1: 125 DTUs. We don't see any performance problems at all in SQL Azure. We have a VNET with a private link between the App Service and SQL Azure. We use Azure Load test to run the tests (and we can share the tests too if needed). We also get similar results when testing locally.
We use Stackify Retrace for monitoring and have enabled that through their extension.

Sync code performance when running 10 instances with 250 threads:
90%: 4,69 sek
Average: 1,417 sek
Open Connection: <0,001 sek
Select Logins: 0,002 sek

Azure_load_test_sync_10_instances
Stackify_overview_sync_10_instances
Stackify_details_sync_10_instances

Async code performance when running 10 instances with 250 threads:
90%: 5,38 sek
Average: 2,235 sek
Open Connection: 1,624 sek
Select Logins: 0,298 sek

Azure_load_test_async_10_instances
Stackify_overview_async_10_instances
Stackify_details_async_10_instances

Sync code performance when running 45 instances with 250 threads, each thread making 10 calls after each other:
90%: 40,21 sek
Average: 17,502 sek
Open Connection: <0,001 sek
Select Logins: 0,006 sek

Azure_load_test_sync_45_instances
Stackify_overview_sync_45_instances
Stackify_details_sync_45_instances

Async code performance when running 45 instances with 250 threads, each thread making 10 calls after each other:
90%: 80,97 sek
Average: 35,080 sek
Open Connection: 19,634 sek
Select Logins: 7,975 sek

Azure_load_test_async_45_instances
Stackify_overview_async_45_instances
Stackify_details_async_45_instances

Table script:

CREATE TABLE [security].[AspNetUserLogin](
	[LoginProvider] [nvarchar] (100) NOT NULL,
	[ProviderKey] [nvarchar] (100) NOT NULL,
	[TenantId] [uniqueidentifier] NOT NULL,
	[ProviderDisplayName] [nvarchar] (450) NULL,
	[UserId] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_AspNetUserLogin] PRIMARY KEY CLUSTERED 
(
	[LoginProvider] ASC,
	[ProviderKey] ASC,
	[TenantId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [security].[AspNetUserLogin]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserLogin_AspNetUser_UserId] FOREIGN KEY([UserId])
REFERENCES [security].[AspNetUser] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [security].[AspNetUserLogin] CHECK CONSTRAINT [FK_AspNetUserLogin_AspNetUser_UserId]
GO

Data: The table is empty

ASP.NET Code (.NET 6 and Microsoft.Data.SqlClient 4.1.0 (we have tried with version 5 too). We started with a default .NET 6 template, added support for controllers and removed authorization, https redirection and exception handler.
The controller:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;

namespace SyncAsyncPerf.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoadTestController : ControllerBase
    {
        private const string _connectionString = 
            "Server=tcp:ourserver.database.windows.net;Authentication=Active Directory Managed Identity;Initial Catalog=oursqldb;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Max Pool Size=5000;Min Pool Size=100";

        [HttpGet]
        public IActionResult Get(Guid userId)
        {
            var sql = $"SELECT [LoginProvider], [ProviderKey], [ProviderDisplayName] FROM [security].[AspNetUserLogin]" +
                        $"WHERE [UserId] = @UserId";

            using var connection = new SqlConnection(_connectionString);
            using var command = connection.CreateCommand();

            command.CommandText = sql;
            var parameter = command.CreateParameter();
            parameter.ParameterName = "@UserId";
            parameter.DbType = System.Data.DbType.Guid;
            parameter.Value = userId;
            command.Parameters.Add(parameter);

            connection.Open();

            using var reader = command.ExecuteReader(System.Data.CommandBehavior.SingleResult | System.Data.CommandBehavior.CloseConnection);

            var result = new List<UserLoginInfo>();
            while (reader.Read())
            {
                result.Add(
                    new UserLoginInfo(reader.GetString(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2))
                            );
            }

            return Ok(result);
        }

        [HttpGet("async")]
        public async Task<IActionResult> GetAsync(Guid userId)
        {
            var sql = $"SELECT [LoginProvider], [ProviderKey], [ProviderDisplayName] FROM [security].[AspNetUserLogin]" +
                        $"WHERE [UserId] = @UserId";

            using var connection = new SqlConnection(_connectionString);
            using var command = connection.CreateCommand();

            command.CommandText = sql;
            var parameter = command.CreateParameter();
            parameter.ParameterName = "@UserId";
            parameter.DbType = System.Data.DbType.Guid;
            parameter.Value = userId;
            command.Parameters.Add(parameter);

            await connection.OpenAsync(HttpContext.RequestAborted);

            using var reader = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SingleResult | System.Data.CommandBehavior.CloseConnection, HttpContext.RequestAborted);

            var result = new List<UserLoginInfo>();
            while (await reader.ReadAsync())
            {
                result.Add(
                    new UserLoginInfo(reader.GetString(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2))
                            );
            }

            return Ok(result);
        }
    }
}

Finally, some notes on the connection string. We have tried many different configurations without effecting the underlying problem. If we use defaults for connection pooling the number of errors increases rapidly, especially for async code because of connection timeouts.

Activity

  1. DavoudEshtehari commented on Mar 28, 2022

    @DavoudEshtehari
    Contributor

    Hi @equist

    Thank you for sharing here.
    For the record, could you specify the OS and target framework in use?

  2. added
    Performance 📈
    on Mar 28, 2022
  3. equist commented on Mar 28, 2022

    @equist
    Author

    .NET 6 on Windows. The App Service, SQL Azure and VNET are all in the same Azure region (North Europe). We see simlar problems when running locally (on a dev box) even though not with same load.

    I've read those, but #1206 seemed to only happen intermitent, but we reproduce this all the time and never with acceptable results for async method.
    I've also read #601, which lead us to set min pool size and to make a manual call to the service to "warm it up" before running the tests, but as shown we still have bad results.

  4. KonnectSalon commented on Apr 4, 2022

    @KonnectSalon

    Having the same issue here... It's an async issue with the SQL client for large fields - Changing the nvarchar(max) to nvarchar(255) for example helped alot.

  5. equist commented on Apr 4, 2022

    @equist
    Author

    Having the same issue here... It's an async issue with the SQL client for large fields - Changing the nvarchar(max) to nvarchar(255) for example helped alot.

    Large fields is an identified issue since earlier, but we get slow performance for small fields too.

  6. KonnectSalon commented on Apr 4, 2022

    @KonnectSalon

    Having the same issue here... It's an async issue with the SQL client for large fields - Changing the nvarchar(max) to nvarchar(255) for example helped alot.

    Large fields is an identified issue since earlier, but we get slow performance for small fields too.

    I removed all async db calls but can’t in the identity which is causing me issues.

    Seems like sqlclient is just broken for async.

  7. equist commented on May 11, 2022

    @equist
    Author

    When switching to Linux App Service the problems disappeared. We haven't tested the downscaled example used in this issue, but the full application is scaling very well on Linux.

  8. timothyeckert commented on Apr 28, 2023

    @timothyeckert

    Chiming in with, we are seeing this issue as well and can see it reported within our APM tool. Rolling back to sync call cuts the time in half.

  9. bedpans commented on Nov 7, 2024

    @bedpans

    Async performance is completely unacceptable. In one particular instance changing from ToListAsync to ToList reduced execution time from 18 minutes to 7 seconds. That is 150x speed up. This happens when we are retrieving 3 rows each one having nvarchar(max) column with 25,000,000 characters of data.

  10. moved this from To triage to Backlog in SqlClient Boardon Dec 23, 2025
  11. added
    Repro Available ✔️
    on Dec 23, 2025
  12. TonyValenti commented on Feb 13, 2026

    @TonyValenti

    Is this issue still an issue?
    Looking at:
    https://steven-giesel.com/blogPost/dd7ab934-c311-45e0-9a04-9a28c624b957/tolistasync-is-fast-again-in-entity-framework-kind-of

    It looks like async calls might be fast.

    We were thinking about migrating our sync calls to async but wanted confirmation first.

  13. TonyValenti commented on Feb 14, 2026

    @TonyValenti

    Do you think these flags might be unnecessary in .net 11? Is there an ETA for the fix?

  14. ErikEJ commented on Feb 14, 2026

    @ErikEJ
    Contributor

    There is no connection between SqlClient and .NET releases.

    If you test the flags and provide feedback, there could be a chance that they will be turned on by default in a future release of SqlClient, I guess.

  15. TonyValenti commented on Feb 25, 2026

    @TonyValenti

    These changes are great. Please turn them on by default in an upcoming release.

  16. paulmedynski commented on Mar 27, 2026

    @paulmedynski
    Contributor

    AppContext switch mitigation (v7.0.0)

    For the DONE token processing overhead specifically, SqlClient 7.0.0 includes a switch that forces synchronous reads in TryProcessDone, avoiding the snapshot/replay cost for that token:

    AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.MakeReadAsyncBlocking", true);

    Trade-off: This blocks the calling thread while reading the 12-byte DONE token, so it reduces per-call latency at the expense of thread pool scalability. It may help in scenarios where async overhead per query is the primary concern and concurrency is moderate.

    For the broader async read overhead (multi-packet PLP data), there is also an experimental continuation path:

    AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseCompatibilityProcessSni", false);
    AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseCompatibilityAsyncBehaviour", false);

    This enables resume-from-offset snapshot replay for large column reads. Both switches must be set together (the first gates the second). Set these before opening any SqlConnection, as switch values are cached on first access. These paths are experimental — please report any issues.

  17. moved this from Backlog to In validation in SqlClient Boardon Mar 31, 2026
  18. added
    Performance 📈
    and removed
    Performance 📈
    on Jun 10, 2026
  19. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  20. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug (Performance)
    Environment All required environment details provided for investigation (Microsoft.Data.SqlClient 4.1.0 / 5.x, .NET 6, SQL Azure Premium P1 (also reproduced with SQL Server generally), Windows App Service — later comments note the issue disappears on Linux App Service; full repro code and expected-vs-actual behavior included)
    Area Area\Async
    Duplicates Potentially related: #593 (parent, "Reading large data async is extremely slow"), #601, #1206 (both referenced in-thread as related known issues)
    Regression Not indicated as a regression from a specific version — reported as a long-standing behavioral gap between sync and async paths, still present as of SqlClient 7.0.0

    Analysis

    This is a long-running, well-documented performance issue (open since March 2022, still active) showing ExecuteReaderAsync/ReadAsync significantly slower than their synchronous counterparts under load, notably for OpenAsync and DONE-token processing overhead, even without large field values. Recent maintainer activity (comment from @paulmedynski, 2026-03-27) confirms SqlClient 7.0.0 ships two opt-in AppContext switch mitigations — Switch.Microsoft.Data.SqlClient.MakeReadAsyncBlocking (forces sync reads for the DONE token) and the paired UseCompatibilityProcessSni / UseCompatibilityAsyncBehaviour switches (experimental resume-from-offset snapshot replay for multi-packet PLP/large-column reads) — but these remain opt-in/experimental rather than default. Severity: P2 (known workaround exists via switches; broad community impact on async scalability, not a crash/data-corruption issue).

    Next Steps

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #1562 · copilot · auto · 70.4 AIC · ⌖ 13.2 AIC · ⊞ 11.9K · ◷

  21. kemsky commented on Nov 12, 2026

    @kemsky

    @paulmedynski, I've added the last two switches yesterday, today we got the first problem:

    Bug report: high CPU (~50%) sustained

    Environment

    • App: Web (ASP.NET Core, backend)
    • Runtime: 10.0.14 win-x64
    • SQL Client 7.0.3
    • Data collected via: dotnet-stack report -p <PID>

    Symptom

    • Sustained ~50% CPU (≈ 2 half-busy threads on a multi-core box)
    • Observed on a live process; snapshot of all managed thread stacks attached (stacks.txt)

    Evidence (from thread dump)

    • 2 of 17 threads flagged CPU_TIME (TIDs 0x1458, 0xC0C); all other threads idle/waiting

    • Both hot threads have identical stacks, deep in SqlClient TDS parsing:

      Microsoft.Data.SqlClient.TdsParser.TryReadPlpUnicodeCharsWithContinue
      Microsoft.Data.SqlClient.TdsParser.TryReadSqlStringValue
      Microsoft.Data.SqlClient.TdsParser.TryReadSqlValue
      Microsoft.Data.SqlClient.SqlDataReader.TryReadColumnInternal
      Microsoft.Data.SqlClient.SqlDataReader.ReadAsyncExecute
      
    • TryReadPlpUnicodeCharsWithContinue is the decoder for large nvarchar(max) (PLP) columns — CPU is spent decoding big string values streamed from SQL Server

    stacks.txt

    Can upgrading to 7.1.1 help with that?

  22. kemsky commented on Nov 13, 2026

    @kemsky

    7.1.1 did not help, it stalls almost immediately, stacktrace is different:

    Thread (0x1608):
      CPU_TIME
      Microsoft.Data.SqlClient!Microsoft.Data.SqlClient.TdsParser.TryReadSqlStringValue(class Microsoft.Data.SqlClient.SqlBuffer,unsigned int8,int32,class System.Text.Encoding,bool,class Microsoft.Data.SqlClient.TdsParserStateObject)
      Microsoft.Data.SqlClient!Microsoft.Data.SqlClient.TdsParser.TryReadSqlValue(class Microsoft.Data.SqlClient.SqlBuffer,class Microsoft.Data.SqlClient.SqlMetaDataPriv,int32,class Microsoft.Data.SqlClient.TdsParserStateObject,value class Microsoft.Data.SqlClient.SqlCommandColumnEncryptionSetting,class System.String,class Microsoft.Data.SqlClient.SqlCommand)
      Microsoft.Data.SqlClient!Microsoft.Data.SqlClient.SqlDataReader.TryReadColumnInternal(int32,bool,bool)
      Microsoft.Data.SqlClient!Microsoft.Data.SqlClient.SqlDataReader.ReadAsyncExecute(class System.Threading.Tasks.Task,class System.Object)
      Microsoft.Data.SqlClient!Microsoft.Data.SqlClient.SqlDataReader.ContinueAsyncCall(class System.Threading.Tasks.Task,class SqlDataReaderBaseAsyncCallContext`1<!!0>)
      System.Private.CoreLib.il!System.Threading.Tasks.ContinuationResultTaskFromResultTask`2[System.__Canon,System.__Canon].InnerInvoke()
      System.Private.CoreLib.il!System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(class System.Threading.Thread,class System.Threading.ExecutionContext,class System.Threading.ContextCallback,class System.Object)
      System.Private.CoreLib.il!System.Threading.Tasks.Task.ExecuteWithThreadLocal(class System.Threading.Tasks.Task&,class System.Threading.Thread)
      System.Private.CoreLib.il!System.Threading.ThreadPoolWorkQueue.Dispatch()
      System.Private.CoreLib.il!System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()
      System.Private.CoreLib.il!System.Threading.Thread.StartCallback()
    

    SQL Server 2019, Web Edition

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area\AsyncPerformance 📈Repro Available ✔️

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions