You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 35 - An internal exception was caught) #2103
We are using Entity Framework 7 with the Microsoft.Data.SqlClient package version 5.1.1. The issue we are facing is the following stack trace appears in groups in our logs every few hours from all our services that use a common routine for loading a database connection. From the logs these issues are typically cleared up within 30seconds, but during that time there is significant errors (10-15).
These errors are all happening from different services (hosted in a AKS cluster) within the same time framework.
I will add that all the services connect to the Azure SQL Database using Private endpoints, and will stop happening after 15-30 seconds. The interval between the errors is random, anywhere from 30minutes to 4 hours so I am at a complete loss where to look.
Microsoft.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 35 - An internal exception was caught)
---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.
---> System.Net.Sockets.SocketException (104): Connection reset by peer
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.Stream.Read(Span`1 buffer)
at System.Net.Sockets.NetworkStream.Read(Span`1 buffer)
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.Read(Span`1 buffer)
at System.Net.Security.SslStream.EnsureFullTlsFrameAsync[TIOAdapter](CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at System.Net.Security.SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at Microsoft.Data.SqlClient.SNI.SNITCPHandle.Receive(SNIPacket& packet, Int32 timeoutInMilliseconds)
at ....
ClientConnectionId:4d28a01d-2de1-4540-b1ca-9e9ef9cd9501
Further technical details
Microsoft.Data.SqlClient version: 5.1.1
.NET target: dotnet core 7
SQL Server version: Azure Sql
Operating system: Debian Linux - Docker
Reacted by Preben Huybrechts, Egor Shulga, Florian Pierrel, Maxim Cherednik and ventii
Reacted by Kar Martikyan, Martijn van Meerten, Dmytro Gokun, Egor Shulga, David Beavon and Krystian Mikrut
Looks like we experience the exact same problem in our Azure Container App. The exact same code does not produce this exception when run in Service Fabric environment
@DavoudEshtehari After some further investigation, here's my findings:
This is a transient network exception;
The real difference is not between Service Fabric/Kubernetes, but about OS. When running on ServiceFabric, we use Windows OS and this SqlException than comes back with an SqlError where Number = 10053. When run on Kubernetes/Linux, we get an SqlException where Number = 0.
But when we get an exception with Number=0 we do not detect it as transient and have to abort the current operation and write error information to the our log.
So, to me this looks like a SqlClient/Linux bug where SqlException.Number is not populated properly. Do you agree?
@Nico-VanHaaster Do you think this also describes your situation?
@ErikEJ You are right. And both of those issues are closed. So, the logical question comes: how do we detect transient errors in an OS-independent manner? Is it even possible with the current codebase?
In talking with the ODBC driver team, for their Linux implementation, they actually have translations from Linux into the equivalent Windows error codes to try and maintain prior Windows-only behavior under error conditions. So it sounds like this is an enhancement we need to make in our managed SNI layer that's used by non-Windows clients. I bet this would be helped by implementing #649...
Let me share my piece of investigation. Recently we observed a spike of errors, which are exactly the same as the topic starter had, and this also impacted our production systems, so we had to take the closest look as we could.
So, we followed the guess, that on linux the code of the underlying problem is not correctly initialized (it is left as 0), thus the built-in retry mechanism simply misses the case when it should be retried. To track it down we added additional logging to AppInsights (which was injected into the ShouldRetryOn method of an ExecutionStrategy of DbContext).
And these are the results: on the image you can see that the SqlException.Errors[0].Number [02] is 0, and that is exactly the property that is used in the built-in retry mechanism of the SqlClient. But we can also see that SqlException.InnerException.InnerException.SocketErrorCode is 10054 [14], and this code is exactly one of the list of retryable codes.
So, it seems that retry mechanism design assumes the SocketErrorCode is copied into SqlError.Number, which obviously does not happen in our case in our environment. May I ask for an advice from the maintainers, what could be the next place to search for the source of the trouble? Where the creation of SqlException is performed?
guys if your connections are on AKS and connecting to a "public" azure SQL
using the default AKS outbound load balancer
try changing the default outbound nat rule aksOutboundRule idle timeout from the stock 30 minutes down to 4 minutes
Yes your idle connections won't last as long, but this helped me reduce me weird connection errors to zero
No errors now for the past 3 days
p.s. if you manually change it and do ANY KIND OF UPDATE to the aks cluster, it will look at the current settings and "correct" them back to 30min, so if you want to test this make sure you modify the setting in AKS itself or don't touch anything in AKS!
so use --nat-gateway-idle-timeout DO NOT USE the service label! thats for INbound connections only NOT OUTbound
The errors won't go away completely, but they will be drastically reduced.
So, we still need a fix to properly detect dropped TCP connections and stop trying to write data it.
I'm hitting this issue during local development with mssql running a docker container elsewhere on my LAN:
.NET Dev Machine: osx-arm64 (MacOS 15)
SQL Server: mcr.microsoft.com/mssql/server:2025-latest
Microsoft.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 35 - An internal exception was caught)
---> System.IO.IOException: Unable to read data from the transport connection: Operation timed out.
---> System.Net.Sockets.SocketException (60): Operation timed out
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow)
at System.Net.Sockets.NetworkStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.SNI.SNINetworkStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at System.Net.Security.SslStream.EnsureFullTlsFrameAsync[TIOAdapter](CancellationToken cancellationToken, Int32 estimatedSize)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.ExecutionContextCallback(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.MoveNext()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox box, Boolean allowInlining)
at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext()
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox box, Boolean allowInlining)
at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
at Microsoft.Data.SqlClient.SNI.SNINetworkStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext()
at System.Threading.ThreadPool.<>c.<.cctor>b__52_0(Object state)
at System.Net.Sockets.SocketAsyncEventArgs.TransferCompletionCallbackCore(Int32 bytesTransferred, Memory`1 socketAddress, SocketFlags receivedFlags, SocketError socketError)
at System.Net.Sockets.SocketAsyncEngine.System.Threading.IThreadPoolWorkItem.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
at System.Threading.Thread.StartCallback()
--- End of stack trace from previous location ---
--- End of inner exception stack trace ---
at Microsoft.Data.SqlClient.SNI.SNINetworkStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.SNI.SslOverTdsStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at System.Net.Security.SslStream.EnsureFullTlsFrameAsync[TIOAdapter](CancellationToken cancellationToken, Int32 estimatedSize)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](Memory`1 buffer, CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at Microsoft.Data.SqlClient.SNI.SNISslStream.ReadAsync(Memory`1 buffer, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__195_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
at I3V.Espi.FastEndpoints.OData.GetRuntimeEntitySetEndpoint.HandleAsync(GetRuntimeEntitySetRequest req, CancellationToken ct) in /Users/rsaunderson/Source/solutions/esi-bitbucket/I3V.Espi.FastEndpoints.OData/Endpoints/GetRuntimeEntitySetEndpoint.cs:line 63
at I3V.Espi.FastEndpoints.OData.GetRuntimeEntitySetEndpoint.HandleAsync(GetRuntimeEntitySetRequest req, CancellationToken ct) in /Users/rsaunderson/Source/solutions/esi-bitbucket/I3V.Espi.FastEndpoints.OData/Endpoints/GetRuntimeEntitySetEndpoint.cs:line 68
at FastEndpoints.Endpoint`2.ExecAsync(CancellationToken ct)
at FastEndpoints.Endpoint`2.ExecAsync(CancellationToken ct)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context)
at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context)
at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
ClientConnectionId:e4b98d00-1d78-4a9e-945c-6be4eea234cd
The issue reports intermittent SqlException (TCP Provider, error 35 — "Connection reset by peer") surfacing in bursts across multiple AKS-hosted services connecting to Azure SQL via private endpoints, self-resolving within ~30 seconds. This points to transient network/socket resets at the TCP/TLS layer (SNITCPHandle.Receive/SNINetworkStream.ReadAsync/SslStream) rather than an application-level bug, and is consistent with known gaps in how SqlClient classifies and retries such transport-level failures (see #4665, which tracks SqlException.IsTransient incorrectly returning false for this same TCP error 35). Given the long-running nature (reported since 2023, still active with fresh repro comments through 2025), recurring reactions/comments, and impact across many users, this warrants a P2 investigation into transient-fault classification and connection resiliency/retry handling for this error class.
Next Steps
Assign this issue to Copilot coding agent to investigate whether SqlException error 35 ("Connection reset by peer") should be classified as transient in SqlErrorCollection/SqlException.IsTransient handling, and whether connection resiliency (ConnectRetryCount/ConnectRetryInterval) or pooling logic in the managed/native SNI TCP read path should proactively detect and recover from these mid-stream resets instead of surfacing them directly to the caller.
Since this is likely infrastructure/network-adjacent (Azure SQL private endpoints, AKS), consider asking affected users whether Azure-side network resets, idle timeouts on private endpoints, or NSG/firewall session limits correlate with the burst timing, to help narrow whether a SqlClient-side retry fix alone would mitigate this.
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.
Activity
Kaur-Parminder commentedon Jul 26, 2023
@Nico-VanHaaster Thanks for reporting. We will try to reproduce it on our end and update the issue.
dmytro-gokun commentedon Oct 10, 2023
Looks like we experience the exact same problem in our Azure Container App. The exact same code does not produce this exception when run in Service Fabric environment
dmytro-gokun commentedon Oct 10, 2023
@Kaur-Parminder Did you have a chance to investigate this?
DavoudEshtehari commentedon Oct 10, 2023
@dmytro-gokun, It's a different environment configuration and I'd suggest connecting Azure Support for further assistant with it.
dmytro-gokun commentedon Oct 16, 2023
@DavoudEshtehari After some further investigation, here's my findings:
And this is where the difference happen. When we have 10053, we know it's a transient exception and retry it. For example, EF has this code to find if an exception is transient: https://github.com/dotnet/efcore/blob/release/8.0/src/EFCore.SqlServer/Storage/Internal/SqlServerTransientExceptionDetector.cs
But when we get an exception with Number=0 we do not detect it as transient and have to abort the current operation and write error information to the our log.
So, to me this looks like a SqlClient/Linux bug where SqlException.Number is not populated properly. Do you agree?
@Nico-VanHaaster Do you think this also describes your situation?
ErikEJ commentedon Oct 16, 2023
Looks related to #1773 and #1902
dmytro-gokun commentedon Oct 16, 2023
@ErikEJ You are right. And both of those issues are closed. So, the logical question comes: how do we detect transient errors in an OS-independent manner? Is it even possible with the current codebase?
David-Engel commentedon Oct 20, 2023
In talking with the ODBC driver team, for their Linux implementation, they actually have translations from Linux into the equivalent Windows error codes to try and maintain prior Windows-only behavior under error conditions. So it sounds like this is an enhancement we need to make in our managed SNI layer that's used by non-Windows clients. I bet this would be helped by implementing #649...
egorshulga commentedon Nov 2, 2023
Let me share my piece of investigation. Recently we observed a spike of errors, which are exactly the same as the topic starter had, and this also impacted our production systems, so we had to take the closest look as we could.
So, we followed the guess, that on linux the code of the underlying problem is not correctly initialized (it is left as 0), thus the built-in retry mechanism simply misses the case when it should be retried. To track it down we added additional logging to AppInsights (which was injected into the
ShouldRetryOnmethod of anExecutionStrategyofDbContext).And these are the results: on the image you can see that the
SqlException.Errors[0].Number[02] is0, and that is exactly the property that is used in the built-in retry mechanism of the SqlClient. But we can also see thatSqlException.InnerException.InnerException.SocketErrorCodeis10054[14], and this code is exactly one of the list of retryable codes.So, it seems that retry mechanism design assumes the
SocketErrorCodeis copied intoSqlError.Number, which obviously does not happen in our case in our environment. May I ask for an advice from the maintainers, what could be the next place to search for the source of the trouble? Where the creation ofSqlExceptionis performed?33 remaining items
KLuuKer commentedon Jun 17, 2025
guys if your connections are on AKS and connecting to a "public" azure SQL
using the default AKS outbound load balancer
try changing the default outbound nat rule
aksOutboundRuleidle timeout from the stock 30 minutes down to 4 minutesYes your idle connections won't last as long, but this helped me reduce me weird connection errors to zero
No errors now for the past 3 days
p.s. if you manually change it and do ANY KIND OF UPDATE to the aks cluster, it will look at the current settings and "correct" them back to 30min, so if you want to test this make sure you modify the setting in AKS itself or don't touch anything in AKS!
so use
--nat-gateway-idle-timeoutDO NOT USE the service label! thats for INbound connections only NOT OUTboundKLuuKer commentedon Jun 18, 2025
The errors won't go away completely, but they will be drastically reduced.
So, we still need a fix to properly detect dropped TCP connections and stop trying to write data it.
KLuuKer commentedon Jun 18, 2025
Errors are back to once per hour, so it only helped for a short while.... ☹
rsaunderson-i3v commentedon Jun 18, 2025
I'm hitting this issue during local development with mssql running a docker container elsewhere on my LAN:
.NET Dev Machine: osx-arm64 (MacOS 15)
SQL Server: mcr.microsoft.com/mssql/server:2025-latest
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\Native SNIAnalysis
The issue reports intermittent
SqlException(TCP Provider, error 35 — "Connection reset by peer") surfacing in bursts across multiple AKS-hosted services connecting to Azure SQL via private endpoints, self-resolving within ~30 seconds. This points to transient network/socket resets at the TCP/TLS layer (SNITCPHandle.Receive/SNINetworkStream.ReadAsync/SslStream) rather than an application-level bug, and is consistent with known gaps in how SqlClient classifies and retries such transport-level failures (see #4665, which tracksSqlException.IsTransientincorrectly returningfalsefor this same TCP error 35). Given the long-running nature (reported since 2023, still active with fresh repro comments through 2025), recurring reactions/comments, and impact across many users, this warrants a P2 investigation into transient-fault classification and connection resiliency/retry handling for this error class.Next Steps
SqlExceptionerror 35 ("Connection reset by peer") should be classified as transient inSqlErrorCollection/SqlException.IsTransienthandling, and whether connection resiliency (ConnectRetryCount/ConnectRetryInterval) or pooling logic in the managed/native SNI TCP read path should proactively detect and recover from these mid-stream resets instead of surfacing them directly to the caller.