SqlClient: Intermittent Unknown error 258 with no obvious cause

Describe the bug

On occasions we will see the following error

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): Unknown error 258
   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 System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)

However, SQL Server shows no long running queries and is not using a lot of it’s resources during the periods where this happens.

It looks to be more of an intermittent connection issue but we’re unable to find any sort of root cause.

To reproduce

We’re not sure of the reproduction steps. I’ve been unable to reproduce this myself by simulating load. From what we can tell this is more likely to happen when the pod is busy (not through just HTTP, but handling events from an external source) but equally it can happen randomly when nothing is really happening on the pod which has caused us quite a substantial amount of confusion.

Expected behavior

Either more information on what the cause might be, or some solution to the issue. I realise the driver might not actually know the issue and it may really be a timeout to it’s point of view. We’re not entirely sure where the problem lies yet, which is the biggest issue.

Further technical details

Microsoft.Data.SqlClient version: 3.0.1 .NET target: Core 3.1 SQL Server version: Microsoft SQL Azure (RTM) - 12.0.2000.8 Operating system: Docker Container - mcr.microsoft.com/dotnet/aspnet:3.1

Additional context

  • Running in AKS, against Elastic Pools.
  • SQL Server shows no long running queries
  • We sometimes get a TimeoutEvent from the metrics that are collected from the pool. On occasions when we do get them, the error_state will be different.
    • For example, we had one this morning that was 145. We don’t know what this means can find no information on what these relate to. I’ve raised a ticket with the Azure Docs team to look at this. I’ll add more onto this when they happen as we’ve not been keeping track of the error_state codes as we’re not sure if they’re even relevant.
  • This might be related to this ticket - https://github.com/dotnet/SqlClient/issues/647
    • However we don’t see the ReadSniSyncOverAsync
  • We do have event counter metrics being exported to Prometheus but have found no obvious indicators that something is wrong

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 25
  • Comments: 81 (17 by maintainers)

Most upvoted comments

In our project, we also discovered that issue quite often, recently. After weeks of debugging, I was able to deterministically reproduce this issue. I am not quite sure if this is the cause for any of the incidents mentioned above, though.

In our case the issue occurs with Entity Framework when the following criteria is met:

  • A long-running query is being executed
  • The query will not finish within the configured command timeout
  • Iteration will be stopped, prematurely:
void Main()
{
    const string longRunningQuery =
        """
        WITH TenRows AS (
            SELECT Value FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) TenRows (Value)
        ),
        
        ThousandRows AS (
            SELECT A.Value A, B.Value B, C.Value C from TenRows as A, TenRows as B, TenRows as C
        )
        
        SELECT A.A
        FROM ThousandRows A, ThousandRows as B, ThousandRows as C;
        """;

    var context = new TestContext();
    
    context.Database.SetCommandTimeout(1);
    
    var values = context.Database.SqlQueryRaw<int>(longRunningQuery);
    
    foreach (var value in values)
    {
        break;
    }
}

// You can define other methods, fields, classes and namespaces here
public class TestContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost; Integrated Security=True");
    }
}

The reason is that the underlying data reader is being disposed (closed) when the enumerator is being disposed. This does not cancel the underlying db command. See also: https://learn.microsoft.com/en-us/dotnet/api/microsoft.data.sqlclient.sqldatareader.close?view=sqlclient-dotnet-standard-5.2#remarks

Interestingly, querying the data to completion may take longer than the configured command timeout in total. But as soon as the reader is being closed the timeout seems to kick in. In the example above, the instruction pointer will “hang” on the closing foreach bracket for the amount of time configured.

The code above can be rewritten to something which is similar to:

const string longRunningQuery =
    """
    WITH TenRows AS (
        SELECT Value FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) TenRows (Value)
    ),
    
    ThousandRows AS (
        SELECT A.Value A, B.Value B, C.Value C from TenRows as A, TenRows as B, TenRows as C
    )
    
    SELECT A.A
    FROM ThousandRows A, ThousandRows as B, ThousandRows as C;
    """;

var connection = new SqlConnection("Server=localhost; Integrated Security=True");
var command = connection.CreateCommand();

command.CommandText = longRunningQuery;
command.CommandTimeout = 1; // seconds

connection.Open();

var reader = command.ExecuteReader();

// Closing/Disposing the reader will drain all pending records. If the time this takes,
// starting from the close attempt, will exceed the command timeout, error 258 will be thrown.
// If the associated command would have been canceled, the code would work fine:
//
//command.Cancel();
//
// Remarks: If we read the reader from user code regularly, the timeout won't have any
// effect. At least when the first record is being delivered in time:
//
//while (reader.Read());

reader.Close();

Thus, in my opinion, the issue is related with https://github.com/dotnet/efcore/issues/24857. Although the underlying issue is ADO.NET related, OR mappers like EF Core IMO must address this somehow, as it lacks an API to actually cancel the query.

Our scenarios, for example, are a little more complicated. We attempt to stream out data from the database over HTTP to a client while performing some transformation. When this kind of transformation fails for some reason, this leads to the error and even hides the original exception due to the underlying finally block:

async Task Main()
{
    await StreamToClient(CancellationToken.None);
}

async Task StreamToClient(CancellationToken cancellationToken)
{
    const string longRunningQuery =
        """
        WITH TenRows AS (
            SELECT Value FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) TenRows (Value)
        ),
        
        ThousandRows AS (
            SELECT A.Value A, B.Value B, C.Value C from TenRows as A, TenRows as B, TenRows as C
        )
        
        SELECT A.A
        FROM ThousandRows A, ThousandRows as B, ThousandRows as C;
        """;

    var context = new TestContext();

    context.Database.SetCommandTimeout(1);

    var records = context.Database.SqlQueryRaw<int>(longRunningQuery).AsAsyncEnumerable();

    await foreach (var record in records.WithCancellation(cancellationToken))
    {
        var transformedRecord = await Transform(record, cancellationToken);
        
        // Send to client
    }
}

async Task<string> Transform(int record, CancellationToken cancellationToken)
{
    await Task.Yield();
    
    throw new InvalidOperationException();
}

// You can define other methods, fields, classes and namespaces here
public class TestContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost; Integrated Security=True");
    }
}

image

Even cancellation triggers the error, although it is internally bound to cancelling the db command eventually:

async Task Main()
{
    using var cts = new CancellationTokenSource();
    
    cts.CancelAfter(TimeSpan.FromSeconds(2));
    
    await StreamToClient(cts.Token);
}

async Task StreamToClient(CancellationToken cancellationToken)
{
    const string longRunningQuery =
        """
        WITH TenRows AS (
            SELECT Value FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) TenRows (Value)
        ),
        
        ThousandRows AS (
            SELECT A.Value A, B.Value B, C.Value C from TenRows as A, TenRows as B, TenRows as C
        )
        
        SELECT A.A
        FROM ThousandRows A, ThousandRows as B, ThousandRows as C;
        """;

    var context = new TestContext();

    context.Database.SetCommandTimeout(1);

    var records = context.Database.SqlQueryRaw<int>(longRunningQuery).AsAsyncEnumerable();

    await foreach (var record in records.WithCancellation(cancellationToken))
    {
        var transformedRecord = await Transform(record, cancellationToken);
        
        // Send to client
    }
}

async Task<string> Transform(int record, CancellationToken cancellationToken)
{
    await Task.Yield();
    
    return record.ToString();
}

// You can define other methods, fields, classes and namespaces here
public class TestContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost; Integrated Security=True");
    }
}

If we add an interceptor cancelling the command on reader close, the issue goes away, immediately:

void Main()
{
    const string longRunningQuery =
        """
        WITH TenRows AS (
            SELECT Value FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) TenRows (Value)
        ),
        
        ThousandRows AS (
            SELECT A.Value A, B.Value B, C.Value C from TenRows as A, TenRows as B, TenRows as C
        )
        
        SELECT A.A
        FROM ThousandRows A, ThousandRows as B, ThousandRows as C;
        """;

    var context = new TestContext();
    
    context.Database.SetCommandTimeout(1);
    
    var values = context.Database.SqlQueryRaw<int>(longRunningQuery);
    
    foreach (var value in values)
    {
        break;
    }
}

// You can define other methods, fields, classes and namespaces here
public class TestContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost; Integrated Security=True");
        optionsBuilder.AddInterceptors(new CommandCancelingInterceptor());
    }
}

public class CommandCancelingInterceptor : DbCommandInterceptor
{
    public override InterceptionResult DataReaderClosing(DbCommand command, DataReaderClosingEventData eventData, InterceptionResult result)
    {
        command.Cancel();

        return base.DataReaderClosing(command, eventData, result);
    }
}

I saw some people using Dapper. We’re using Dapper in our project as well. However, I did not yet attempt to reproduce the issue with Dapper. I am pretty sure, though, that any OR mapper is affected that behaves in the same way.

I hope this helps some of you guys and I’d be interested if the other things you tried might correlate with our observation. We also tried to scale up the database or adjust some screws and it helped. But I think this was due to the query we were executing always “scratched” on the default command timeout of 30 seconds, exceeding it only occasionally. And scaling up the database lead to reader disposal finishing in time.

It doesn’t help that 258 seems to be used for a wide range of problems. Your query is slow? Unknown error 258. The network is congested? Unknown error 258. The DBA didn’t like the way you looked at him? UNKNOWN ERROR 258.

Hello, Azure Support just told us that the product group identified the issue and will fix it Q4 2022.

Regards,

The issue can be easily reproduced by running an aspnet core web api project in a Linux container and making multiple concurrent calls to an endpoint to query a SQL Server database immediately after the service starts. The cost of opening each new thread on Linux appears to be very high, and making 30 concurrent queries with no available threads in the thread pool can take more than 60 seconds. If you do the same test running the service on Windows, it works perfectly.

The only workaround for us to get this to work on Linux is to set the ThreadPool.MinThreads to a high number.

We are also experiencing this issue with Linux App Services against Azure SQL. We only began seeing this after migrating our App Services from Windows to Linux.

@dazinator we only tested containers on different Linux host Systems to see if it’s possible related to a certain kernel version or not but seems like it’s not, as said we stopped testing after the issue disappeared after migrating the sql server to a newer version, just wanted to share our experience maybe it helps others somehow

Azure Support just told us that the product group identified the issue and will fix it Q4 2022.

@DLS201 any chance you have more information on this? Maybe a link to a bug or something? We are investigating this issue currently and would like to know what MSFT knows…

Just want to clarify one misconception.

The cost of opening each new thread on Linux appears to be very high, and making 30 concurrent queries with no available threads in the thread pool can take more than 60 seconds.

While the cost of creating new threads is higher on Linux than on Windows, for example. It’s not that cost that slows things down. The system thread pool implementation in .NET is designed to spin up new threads slowly, in a very conservative manner. If a library or application is spawning many tasks that hold threads for any length of time, it will take a while for the system thread pool to add threads to service the waiting queue of tasks.

For those moving to PostgreSQL to mitigate these issues, what are you using for the migration from MS SQL to PostgreSQL?

The main pattern I’ve noticed is that they happen within Microsoft’s proprietary VNET components (private endpoints). They are particularly severe in multi-tenant environments where several customers can be hosted on the same hardware (or even in containers within the same VM.

@dbeavon We have a multi-tenant application running as a docker container on an Azure VM - connecting to Azure SQL over a “private endpoint” (which presents itself as a nic on our vnet). So yes I think this is a good match.

I have not tried deleting the private endpoint and going via the public ip, i will give that a shot. As it stands, we are mid plan refactoring our application to make our most impacted SQL calls in a newly dedicated process (theory being it was something to do with thread pool ramp up when other things are sharing the thread pool - and this not playing well with the was sql client library is written using sync over async and such). So by giving our task a dedicated dotnet process hopefully that will help. However if it doesn’t, aside from being really annoyed, atleast I can give the public IP a go…

It’s too painful to go through support, we are a small team and the level of time required to get this over the line appears too much.

We went the other way, from public IP to private endpoint, if my memory serves me, it was after some advice we received from azure support when we asked to investigate it. It did not help much. What did seem to help (a bit, we still get frequent timeouts / 258), is to have less applications / concurrency on a single ‘vm’ by making our ‘apps’ reserve more cpu’s (on k8s) even thought they do not really need it when looking at the cpu usage.

@SharePointX have you tried increasing the connection timeout to make sure it won’t be timed out while retrieving data from the server and how it affects the execution?

I’d suggest retrieving data in smaller batches if it fails with large portions to find the balance. If the server is not available temporarily (especially over the network), I’d recommend doing the retry pattern on the the application level with the remaining data.

There are some thread starvation scenarios with thread pool and connection pool, which I believe don’t apply to your case with a single-threaded app. I don’t have any idea about warming up the database, you may ask the SQL Server Dev team.

We’ve had this same issue multiple times. Had a ticket open with Microsoft on the SQL side for weeks, in the end they could not find any long running queries, although we had Application Insights reporting some queries taking over 2 minutes, which is also not possible because our .NET SQL command timeout was set to 30 seconds in most cases, and never more than 1 minute. So they ruled out any SQL issue.

We had a separate ticket open with the App Service team (we run on App Service with Linux Docker containers) - and it also completely stumped them - no issues with threadpool, networking etc. In the end I have had to scale up to many more instances than should be necessary, and the issue has not recurred but each instance is only able to handle about 6 requests per second which is super low, given the average API request response time is under 500ms. So no idea of the root cause of this.

When the issue occurred, on our 24 vCore provisioned Azure SQL database, only about 10% usage was reported, so we were nowhere near database resource limits.

@dazinator SQL Server does report on long-running queries, hence why we assumed that the error was happening at the application level. I don’t have the information to hand anymore having left the company but given these were 30+ seconds of waiting, it would have shown up in some of the information tables SQL Server provides.

We spent a considerable amount of time looking into the causes, and it was happening in multiple services for different queries and in different environments, some of which had little to no data that would even cause a 30+ second slowdown.

I understand the need to be thorough but we had run through a lot of the steps you have outlined. I just don’t want this ticket to get lost in the ether because people assume it’s laziness on our part.

@asierpn @dazinator @MichelZ Could you please let me know what was the value of min threads you had set as a workaround?

It depends on your application, you have to test with different values to find the best one for you, we noticed an improvement when we set it to 20, but eventually we increased it to 100.

If you have chronic problems or outages, please open a support ticket with Microsoft and share the outcome here. I think that type of information will allow us to proceed more productively.

I’m a “big-data” developer in Azure, and I have suffered from chronic socket exceptions in multiple Azure platforms - just as everyone else is describing. The main pattern I’ve noticed is that they happen within Microsoft’s proprietary VNET components (private endpoints). They are particularly severe in multi-tenant environments where several customers can be hosted on the same hardware (or even in containers within the same VM.

The problems are related to bugs in Microsofts software-defined-networking components (SDN proxies like “private endpoints” or “managed private endpoints”). I will typically experience these SDN bugs in a large “wave” that impacts me for an hour and then goes away. The problems have been trending for the worse over the past year, and I’ve opened many tickets (Power BI, ADF, and Synapse Spark).

The problems are not likely to happen on normal TCP (public internet ports). Nor are they common on VNET traffic when “peering” is used. It seems to be a problem that is specific to the funky private endpoints in Azure. I would be interested to know if others can related to this pattern? Also, the socket exceptions are not specific to SQL. They impact MSAL, ADLS, REST, etc. The underlying TCP exceptions are generally the same in all cases (“connection reset” or “connection timeout”).

The Microsoft support cases I have already opened have not gone well. We are a small customer and Microsoft has not taken our problems seriously. I think they are already well-aware of the bugs in their private VNET technology and are trying to keep them hidden. They undermine the severity of these problems by repeating the word “transient” over and over like it was some sort of a magical incantation that makes the bugs more acceptable. To me it seems totally unacceptable to have issues (transient or otherwise) that trigger dozens and dozens of socket exceptions a day.

I find that there are lots of Microsoft’s own products that are impacted by these network bugs, notably ADF pipelines. They have had a “VNET IR” that suffers from a massive number of socket exceptions when interacting with resources in the local network (East US). The support teams actually say they have a formalized “policy” to require customers to implement retries on all pipeline activities (they suggest at least three retries with two minute delays in between them). This “policy” is simply a way to avoid the well-known bugs. ADF deployed the VNET IR several years ago and they have probably handled hundreds of CSS tickets about the fragile private endpoints in their managed vnet.

IMPORTANT: Based on a three-year support case with another team (not ADF) I do have bug numbers that apply to private endpoints and these bugs are supposed to be fixed soon (not holding my breath).

The following changes are for the “Azure Network stack”:

Feature ending with x509 : Support map space deletion in VFP without breaking flows. (virtual filtering platform, ie switch?)

The ETA publicized is late 2024

Bug ending with x810 : PE-NC Flow mix up Network team promised to roll it out early 2024.

Sorry for the long post. I think it is easy for everyone to prove that these problems are specific to Azure, and don’t affect on-premise scenarios with Sql Client. The challenge is getting Microsoft to help with them in Azure. I get the sense that there is a substantial lack of honesty and transparency when it comes to networking bugs in Azure. There was only one support scenario where Microsoft was willing to admit to the bugs I’ve experienced in their SDN technology. In every other Azure platform they are refusing to investigate or discuss the so-called “transient” network errors that cause TCP connections to break between resources that are in direct proximity to each other (0 ms latency).

Here is a discussion of ADF’s networking bugs. https://learn.microsoft.com/en-us/answers/questions/1390627/what-is-the-reason-for-networking-problems-in-adf

Hope this helps. I would appreciate it if those impacted by the socket errors would at least confirm that their scenarios involve VNETS, eg. private endpoints in particular, and possibly managed vnets. If you open a support case with Microsoft, please keep a count of the number of times they use the word “transient” (and they always say “communication failure” rather than socket exception).

To continue the conversation about this issue being related to Linux and to hopefully narrow in on an event … our Azure Application Insight logs show that these random timeouts AND application performance issues all started after this Azure East US maintenance window QK0S-TC8 did SOMETHING to Azure functions host on August 17th 9:00PM EST. Something in that host update caused this unknown error 258 to start appearing.

At that point in time, our host went from Linux 5.10.177.1-1.cm1 to Linux 5.15.116.1-1.cm2 and application performance tanked shortly after, and we now have the sudden appearance of these Unkown error 258 throwing exceptions. Some metric digging shows that memory usage (P3V3 with 32GBs) tanked along with performance.

image

No code or db changes on our part, just suddenly the AppInsight logs show kernel 5.15, odd timeout errors, and we presumably can’t access memory. @eisenwinter - you said you tried a few different kernels, did you go back to 5.10? Anyone else seeing this issue on 5.10 or lower?

Update: We converted the function app over to Windows. The sql timeout errors are gone and application performance is restored! 🎉

Just want to mention that we experienced a similar issue and converting to Windows seems to have solved the problem.

Yes, we tried upgrading to .NET 7 and the latest SNI package release (5.1.1). It didn’t fix it. The only thing that has made any difference was the suggestion to bump the min thread count. We bumped it to 20 and now very rarely see the issue (maybe 1/day or so).

Nothing seems to eliminate it so far but the thread count workaround does help.

Turns out our issue was simply a genuine long running (dynamic based on filters the user selects on front end) query hitting the timeout with some filter selections. We had assumed (that magic word) the particular query involved (which happens sporadically) was ok because similar (but not identical) queries were ok. When we intercepted the T-SQL of a query that reached the timeout and re-ran it exactly as is we replicated the timeout and perf issue. Slightly embaressing but there you go - make sure you log the exception and try to intercept the exact T-SQL and re-run it to make sure it’s not just a genuine query perf issue 😉

You mean like:

  • Microsoft.Data.SqlClient v4.1.1
  • .NET 6
  • Docker aspnet:6.0-bullseye-slim
  • Host image: AKSUbuntu-1804gen2containerd-2022.08.29

Hello, We currently face a similar issue since approximately 1 month, with SQL queries facing Win32Exceptions with code 258 and no obvious cause. The DB itself signals no issue with very low DTU usage.