SqlClient: Connection string property "Connection Timeout" is not respected.

We have a high-load service which we want to run robustly when SQL server becomes (temporarily) unavailable. To achieve this, we set Connection Timeout (and Command Timeout as well, but that is not important for the purpose of this issue). We then expect connection attempt fail fast if the SQL server is not available. This way, our server will be able to do its job even if the SQL server is down for some time. But, somehow this does not work as expected. Following code emulates our multithreaded server attempting to connect to an (unavailable) SQL server from multiple threads a time:

using System.Diagnostics;
using Microsoft.Data.SqlClient;

const string connectionString = "Server=tcp:noserver.database.windows.net,1433;Database=nodb;User=nouser;Password=nopassword;Connection Timeout=3";
const int numberOfTasks = 1000;

var tasks = new Task[numberOfTasks];

for (var i = 0; i < numberOfTasks; ++i)
{
    tasks[i] = Task.Run(async () =>
    {
        var timer = Stopwatch.StartNew();

        try
        {
            await using var conn = new SqlConnection(connectionString);
            await conn.OpenAsync();
        }
        catch (Exception)
        {
            Console.WriteLine("Connection failed after {0} sec", timer.Elapsed.TotalSeconds);
        }
    });
}

Task.WaitAll(tasks);

When this code is run outputs something like:

Connection failed after 0.5961428 sec
Connection failed after 0.901156 sec
Connection failed after 1.2156149 sec
...
Connection failed after 30.7706116 sec
...
Connection failed after 56.6531985 sec
Connection failed after 56.9537902 sec
....

So, clearly Connection Timeout is not being respected. This causes our server to stall completely when SQL server is down. This is not the way we want it to work 😃. Any idea why we are observing this behavior?

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 17 (7 by maintainers)

Most upvoted comments

It all pretty much comes down to the fact that SqlClient opens physical connections one at a time (and in a separate thread).

https://github.com/dotnet/SqlClient/blob/30cd171e0129ccf80bd95add6191687e987bbd4d/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs#L1150-L1156

That thread synchronously goes through every single open request and tries to open a physical connection:

https://github.com/dotnet/SqlClient/blob/30cd171e0129ccf80bd95add6191687e987bbd4d/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs#L1046-L1072

The way opening a physical connection works is that there are multiple handles (one for getting a connection from a pool, one to open a physical connection, one for errors), so SqlClient just waits for any of them to fire:

https://github.com/dotnet/SqlClient/blob/30cd171e0129ccf80bd95add6191687e987bbd4d/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs#L1189-L1216

At this point timeout (waitForMultipleObjectsTimeout in this case) is 0 so WaitHandle.WaitAny should immediately return a timeout error. But because connections are open sequentially, the handle responsible for opening a physical connection is always set and WaitHandle.WaitAny returns that handle. Essentially, what’s happening is:

  1. Pool’s thread gets a connection request from the queue
  2. Takes a semaphore to open a physical connection
  3. Tries (and fails) to open a physical connection
  4. Releases a semaphore
  5. Repeat

I think you’re experiencing a combination of known issues:

  • #601 (This is due to the fact that even though you try to open “asynchronously” connections in parallel, the connection pool is limited to open only 1 connection “synchronously” at a time)
  • #29 (for OpenAsync() API)

To achieve true parallelism with fail fast support, you’d need to:

  • Disable pooling to allow true parallel execution.
  • Use Open() API to override the SqlConnectionOverrides to “OpenWithoutRetry” instead to disable retries during connection failure.

We are going to bring this support in OpenAsync() soon, fyi PR: #2433, and with #601 getting fixed sometime in future, you will not have to replace API with Open().

Clearly looks like a bug to me.

Every time I say that something looks like a bug I’m usually replied with “it’s by design” 😢 But anyway, one way to fix that is to modify TryGetConnection to immediately exit whenever a timeout is 0:

private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
{
	if (waitForMultipleObjectsTimeout == 0)
	{
		connection = null;
		return false;
	}
	/// other stuff unchanged

It’s not going to help completely since eventually that thread is going to start getting requests with a near-zero timeout (or more like it’s going to fluctuate, as in on the first request it tries to open a physical connection, then skips a few requests because their timeout is going to be 0, then get another with a near-zero timeout and tries to open, then again skips a few, etc), but all in all should be a bit better behavior.

@dmytro-gokun which exact versions of EF Core and SqlClient and SqlClient are you using? It seems like SqlClient 5.1.2 - which EF Core 8.0.2 took a dependency on - introduced new behavior which triggers this (see https://github.com/dotnet/efcore/issues/33399 for more details).