Skip to content

A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 35 - An internal exception was caught) #2103

Open

Description

@Nico-VanHaaster

Describe the bug

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

Activity

  1. Kaur-Parminder commented on Jul 26, 2023

    @Kaur-Parminder
    Contributor

    @Nico-VanHaaster Thanks for reporting. We will try to reproduce it on our end and update the issue.

  2. dmytro-gokun commented on Oct 10, 2023

    @dmytro-gokun

    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

  3. dmytro-gokun commented on Oct 10, 2023

    @dmytro-gokun

    @Kaur-Parminder Did you have a chance to investigate this?

  4. DavoudEshtehari commented on Oct 10, 2023

    @DavoudEshtehari
    Contributor

    @dmytro-gokun, It's a different environment configuration and I'd suggest connecting Azure Support for further assistant with it.

  5. dmytro-gokun commented on Oct 16, 2023

    @dmytro-gokun

    @DavoudEshtehari After some further investigation, here's my findings:

    1. This is a transient network exception;
    2. 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.

    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?

  6. ErikEJ commented on Oct 16, 2023

    @ErikEJ
    Contributor

    Looks related to #1773 and #1902

  7. dmytro-gokun commented on Oct 16, 2023

    @dmytro-gokun

    @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?

  8. added
    Up-for-Grabs 🙌
    and removed on Oct 19, 2023
  9. David-Engel commented on Oct 20, 2023

    @David-Engel
    Contributor

    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...

  10. egorshulga commented on Nov 2, 2023

    @egorshulga

    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?

    image

  11. 33 remaining items

  12. KLuuKer commented on Jun 17, 2025

    @KLuuKer

    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

  13. KLuuKer commented on Jun 18, 2025

    @KLuuKer

    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.

  14. KLuuKer commented on Jun 18, 2025

    @KLuuKer

    Errors are back to once per hour, so it only helped for a short while.... ☹

  15. rsaunderson-i3v commented on Jun 18, 2025

    @rsaunderson-i3v

    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
    
  16. removed this from the 6.1-preview2 milestone on Jun 23, 2025
  17. moved this from To triage to Backlog in SqlClient Boardon Oct 28, 2025
  18. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  19. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Native SNI
    Duplicates Potentially related: #4665, #2192, #2405 (closed)
    Regression Not indicated

    Analysis

    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.
    • Recommend reviewing SqlException.IsTransient returns false for TCP Provider error 35 (broken pipe) — transport-level failures should be considered transient #4665 (transient classification for error 35) and Connection gets stuck in SNITCPHandle.TryConnectParallel #2192 (SNITCPHandle connection stuck) as closely related root-cause candidates before starting new investigation, to avoid duplicate work.
    • 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.

    Generated by SqlClient Issue Auto-Triage for #2103 · copilot · auto · 65.1 AIC · ⌖ 13.1 AIC · ⊞ 11.9K · ◷

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

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions