Skip to content

Hangs in ExecuteReaderAsync #915

Closed as not planned
Closed as not planned

Description

@liranc

Describe the bug

Every once in a while, our app (Azure Function v3 runs on a dedicated plan, Windows host, .Net Core 3.1, Azure SQL, Dapper extensions) starts to throw many InvalidOperationException with the message:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

This seems to happen sporadically (could be a few times per day), without any clear "trigger" (the function is isn't serving any unusual amounts of requests. Actually, it's usually underutilized).
Also, the SQL server isn't busy at all at this time (<5% utilization, without any long running queries).

We've enabled SqlClient's tracing functionality and found that when this happens, all of a sudden connections completely stop to return to the pool and after some time (sometimes 30 seconds, sometimes 60 seconds), they all return to the pool together.
Also, the same function host connects to two separate SQL servers (so, we have two separate connection pools). Despite these are separate servers that are used to serve different traffic (and execute different stored procedures), the exact same behavior is observed in both connection pools at the same time.

According to the logs, the "hang" isn't related to disposing/closing the connections. Instead, it seems that the delay happens between the call to ExecuteReaderAsync and EndExecuteReaderAsync.
We've also checked SQL Server's audit log for the same time frame and we can see that the stored procedure completed immediately, so there were no long running queries at that time.

Below is a sample log of such a scenario. Note the jump in time between 4:54:44.757 and 4:55:09.787:

timestamp [Local Time]	message
2/15/2021, 4:55:09.788 PM	ScopeLeave - 67659
2/15/2021, 4:55:09.788 PM	PoolerTrace - <prov.DbConnectionPool.PutNewObject|RES|CPOOL> 1, Connection 163, Pushing to general pool.
2/15/2021, 4:55:09.788 PM	PoolerTrace - <prov.DbConnectionInternal.DeactivateConnection|RES|INFO|CPOOL> 163, Deactivating
2/15/2021, 4:55:09.788 PM	PoolerTrace - <prov.DbConnectionPool.DeactivateObject|RES|CPOOL> 1, Connection 163, Deactivating.
2/15/2021, 4:55:09.788 PM	PoolerTrace - <prov.DbConnectionInternal.PrePush|RES|CPOOL> 163, Preparing to push into pool, owning connection 0, pooledCount=0
2/15/2021, 4:55:09.788 PM	PoolerTrace - <prov.DbConnectionInternal.CloseConnection|RES|CPOOL> 163 Closing.
2/15/2021, 4:55:09.788 PM	CorrelationTrace - <sc.SqlConnection.Close|API|Correlation> ObjectID 3286, ActivityID 8eb731f2-4ffb-47f2-b5c4-d9b5bb310cdb:1
2/15/2021, 4:55:09.788 PM	ScopeEnter - <sc.SqlConnection.Close|API> 3286
2/15/2021, 4:55:09.788 PM	ScopeLeave - 67658
2/15/2021, 4:55:09.788 PM	ScopeEnter - <sc.SqlDataReader.Close|API> 1
2/15/2021, 4:55:09.788 PM	ScopeLeave - 67657
2/15/2021, 4:55:09.788 PM	ScopeEnter - <sc.SqlDataReader.Close|API> 1
2/15/2021, 4:55:09.788 PM	ScopeLeave - 67654
2/15/2021, 4:55:09.787 PM	ScopeLeave - 67655
2/15/2021, 4:55:09.787 PM	ScopeLeave - 67656
2/15/2021, 4:55:09.787 PM	ScopeEnter - <sc.SqlDataReader.Read|API> 1
2/15/2021, 4:55:09.787 PM	ScopeEnter - <sc.SqlDataReader.NextResult|API> 1
2/15/2021, 4:55:09.787 PM	ScopeEnter - <sc.SqlDataReader.NextResultAsync|API> 1
2/15/2021, 4:55:09.787 PM	ScopeLeave - 67652
2/15/2021, 4:55:09.787 PM	ScopeLeave - 67653
2/15/2021, 4:55:09.787 PM	ScopeEnter - <sc.SqlDataReader.Read|API> 1
2/15/2021, 4:55:09.787 PM	ScopeEnter - <sc.SqlDataReader.ReadAsync|API> 1
2/15/2021, 4:55:09.787 PM	CorrelationTrace - <sc.SqlCommand.EndExecuteReaderAsync|Info|Correlation> ObjectID3260, ActivityID 8eb731f2-4ffb-47f2-b5c4-d9b5bb310cdb:1
2/15/2021, 4:54:44.757 PM	Trace - <sc.SqlCommand.ExecuteReader|INFO> 3260, Command executed as RPC.
2/15/2021, 4:54:44.757 PM	CorrelationTrace - <sc.SqlCommand.ExecuteReaderAsync|API|Correlation> ObjectID 3260, behavior=16, ActivityID 38ccce37-36c4-40fe-a99e-d47e8fb99097:1
2/15/2021, 4:54:44.757 PM	Trace - <sc.SqlCommand.set_CommandType|API> 3260, 40
2/15/2021, 4:54:44.757 PM	Trace - <sc.SqlCommand.set_CommandTimeout|API> 3260, 120
2/15/2021, 4:54:44.757 PM	Trace - <sc.SqlCommand.set_CommandText|API> 3260, String Value = 'sp_XXXXXXXXXXXX'
2/15/2021, 4:54:44.757 PM	ScopeLeave - 67149
2/15/2021, 4:54:44.757 PM	Trace - <sc.SqlCommand.set_Connection|API> 3260, 3286
2/15/2021, 4:54:44.757 PM	ScopeEnter - <prov.DbConnectionHelper.CreateDbCommand|API> 3286
2/15/2021, 4:54:44.757 PM	Trace - <prov.DbConnectionHelper.ConnectionString_Get|API> 3286
2/15/2021, 4:54:44.757 PM	ScopeLeave - 67148
2/15/2021, 4:54:44.756 PM	PoolerTrace - <prov.DbConnectionInternal.ActivateConnection|RES|INFO|CPOOL> 163, Activating
2/15/2021, 4:54:44.756 PM	PoolerTrace - <prov.DbConnectionInternal.PostPop|RES|CPOOL> 163, Preparing to pop from pool,  owning connection 0, pooledCount=0
2/15/2021, 4:54:44.756 PM	PoolerTrace - <prov.DbConnectionPool.GetFromGeneralPool|RES|CPOOL> 1, Connection 163, Popped from general pool.
2/15/2021, 4:54:44.756 PM	PoolerTrace - <prov.DbConnectionPool.GetConnection|RES|CPOOL> 1, Getting connection.
2/15/2021, 4:54:44.756 PM	CorrelationTrace - <sc.SqlConnection.Open|API|Correlation> ObjectID 3286, ActivityID 38ccce37-36c4-40fe-a99e-d47e8fb99097:1
2/15/2021, 4:54:44.756 PM	ScopeEnter - <sc.SqlConnection.Open|API|Correlation> ObjectID 3286, ActivityID 38ccce37-36c4-40fe-a99e-d47e8fb99097:1
2/15/2021, 4:54:44.756 PM	Trace - <prov.DbConnectionHelper.ConnectionString_Set|API> 3286, 'Data Source=XXXXXXXXXX;Initial Catalog=XXXXXXXXXX;Persist Security Info=True;Max Pool Size=200;Multiple Active Result Sets=False;Connect Timeout=30;Encrypt=True;Trust Server Certificate=False'
2/15/2021, 4:54:44.756 PM	Trace - <prov.DbConnectionHelper.ConnectionString_Set|API> 3286, 'Data Source=XXXXXXXXXX;Initial Catalog=XXXXXXXXXX;Persist Security Info=True;Max Pool Size=200;Multiple Active Result Sets=False;Connect Timeout=30;Encrypt=True;Trust Server Certificate=False'

Any idea on what could cause this behavior?

To reproduce

Seems to happen sporadically without a clear "trigger" (still, could happen a few times per day).
We're unable to reproduce this issue reliably. Even when we try to reproduce it in a test environment, with 10x the traffic, there's no guarantee it will reproduce.

Expected behavior

The function shouldn't hang and the connection should return to the pool.

Further technical details

Microsoft.Data.SqlClient version: 2.0.1
.NET target: Core 3.1
SQL Server version: Azure SQL
Operating system: Azure Functions v3, dedicated plan (Windows host)
Using Dapper extensions

Activity

  1. cheenamalhotra commented on Feb 16, 2021

    @cheenamalhotra
    Member

    Hi @liranc

    We are aware of this issue and it's mainly due to thread pool starvation that queued threads take a long time to execute and queries eventually timeout. It varies on different environments but is mainly observed on Unix platforms, and yes not consistently reproducible due to the nature of the issue.

    Our recommendation at this point is to either use "Sync" queries, which have better performance in Unix.
    Or if you need to use "Async", you need to limit queries running at same time to ensure they can complete and return connections back to pool.

    We are looking into this issue (similar to #422).

  2. liranc commented on Feb 16, 2021

    @liranc
    Author

    @cheenamalhotra we're using a Windows host. Does the mentioned issue applies for Windows as well? And, does the recommendation to switch to synchronous APIs is still relevant in this case?

  3. cheenamalhotra commented on Feb 16, 2021

    @cheenamalhotra
    Member

    No, if your Azure Function App uses a Windows host, that makes it unrelated to known issues then.

    Is it possible you can create and upload a repro case where Azure function calls a similar stored procedure and hit this error?
    Please use our latest driver version v2.1.1 to rule out any issues we fixed already.

  4. scottsauber commented on Feb 16, 2021

    @scottsauber

    I’m seeing the same behavior locally. The same code works on 2.0.1 and lower but 2.1 and 2.1.1 has the issue. I’m on macOS.

    It’s pretty concerning to me to see “don’t use async” suggested when you see on the ASP.NET Core side to “don’t make blocking calls” as the suggestion over there which is contradictory.

    Also as far as thread pool starvation goes, this happens locally and it’s a single DB call for a single page so it seems strange that the thread pool is being starved in that scenario. But I’m no expert in that area.

  5. scottsauber commented on Feb 16, 2021

    @scottsauber

    Happy to help repro this if you need a better repro.

  6. cheenamalhotra commented on Feb 16, 2021

    @cheenamalhotra
    Member

    Hi @scottsauber

    In light of #422 issue I would recommend that, mainly if your application creates lots of parallel connections and queries.
    Of course Async should be always faster than Sync, and that's correct recommendation, it's an issue in the driver where things get blocked.

    The same code works on 2.0.1 and lower but 2.1 and 2.1.1 has the issue.

    Please provide us with your repro as that would be of great help to investigate this gap!

  7. msallin commented on Mar 16, 2021

    @msallin

    I'm to sure if this is the same but we hunt a issue in prod for a long time.
    dotnet/efcore#24169

  8. cheenamalhotra commented on Mar 19, 2021

    @cheenamalhotra
    Member

    @msallin

    If you have a handy repro we can try to reproduce and investigate, please upload the same.

  9. msallin commented on May 20, 2021

    @msallin

    I don't have a repro. We aren't able to reproduce it locally. What's interesting however is, that we have some slow queries on SQL server (means they compete with 700ms instead of 70ms). There is very much noise all around, but we think we see in such a situation we more queries which timeout (time out is about 10s).

    We can tell that it isn't related to thread pool starvation due to the counters we use to monitor, due to the missing Kestrel warnings and mainly due to the traces about the thread pool we captured from the runtime.

    Also interesting: It happens in bursts. There is not one SQL command which times out but multiple in a row.

    EDIT:
    We use EF Core and the async methods. Now we rewrote an application to use sync methods. I will let you know if this helps with the timeouts. If it's really a problem with EF Core / SQL-Client and async the result will be that we see some queries which take longer but no timeouts anymore.

  10. cheenamalhotra commented on May 21, 2021

    @cheenamalhotra
    Member

    Hi @msallin

    Could you try with our recent releases v2.1.3 and v3.0.0-preview3 released recently? Nuget

  11. msallin commented on May 22, 2021

    @msallin

    Does 3.0.0 work with the current ef core?
    We will give it a try with another app. We encounter this problem with all our services.
    I will report back, if switching to sync methods helps and if the usage of the v3 helps.

  12. ErikEJ commented on May 22, 2021

    @ErikEJ
    Contributor

    @msallin yes, both 2.1 and 3.0 work with EF Core

  13. clement911 commented on Mar 23, 2022

    @clement911

    We are seeing similar sporadic issues.

    Queries that return fast from another machine or from SSMS sometimes get stuck and time out for no reason when executed via the SqlClient.

    How can we go about debugging this?

    This is the call stack we see

    Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
     ---> System.ComponentModel.Win32Exception (258): The wait operation timed out.
       at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteReader(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
       at Microsoft.Data.SqlClient.SqlCommand.EndExecuteReaderInternal(IAsyncResult asyncResult)
       at Microsoft.Data.SqlClient.SqlCommand.EndExecuteReaderAsync(IAsyncResult asyncResult)
       at Microsoft.Data.SqlClient.SqlCommand.EndExecuteReaderAsyncCallback(IAsyncResult asyncResult)
       at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
    --- End of stack trace from previous location ---
    

    Which ones of the following async functions is prone to such sporadic issues?
    command.ExecuteReaderAsync, reader.ReadAsync, conn.OpenAsync?

    UPDATE:
    we run on Azure App service / Windows with .NET 6 and Microsoft.Data.SqlClient, Version=4.0.0.0

  14. clement911 commented on Mar 23, 2022

    @clement911

    @msallin , did switching to sync calls fix the issue?

  15. msallin commented on Mar 24, 2022

    @msallin

    We stopped investigating the issue. I can tell that one part was infrastructure-related. However, there was an interesting phenomenon: We see from time to time slow queries in the SQL-Server profiler but it takes factors longer until they are completed in the application.

  16. timaiv commented on Jun 13, 2023

    @timaiv

    Reproducible on Windows 10. .NET 7.
    Hangs on 30 sec. (or 10 sec).
    Switching to sync calls fixes the issue.

    <PackageVersion Include="Microsoft.Data.SqlClient" Version="5.2.0-preview2.23159.1" />
    
  17. roji commented on Jun 13, 2023

    @roji
    Member

    @timaiv sounds like that could be #593.

  18. David-Engel commented on Jun 11, 2024

    @David-Engel
    Contributor

    Too generic without specific use case to reproduce.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions