How to Configure HttpClient connection keep-alive in C#

By FoxLearn Published on Mar 11, 2025   214
When using a single instance of SqlConnection to interact with a database, the connection is pooled, meaning it can be reused for subsequent requests to improve performance.

By default, idle connections are kept open for 30 seconds. However, the connection can be closed by the server or other external factors regardless of client-side configurations.

There are two key settings that control how long a database connection remains in the pool. You can configure these settings in both .NET Framework and .NET Core. Below is a table that highlights the settings, their default values, and the properties you can use to modify them:

SettingDefault.NET Framework.NET Core
Idle connection timeout30 secondsSqlConnection.ClearPoolSqlConnection.ClearAllPools
Max connection lifetimeForeverSqlConnection.ConnectionTimeoutSqlConnection.PooledConnectionLifetime

In this article, I’ll explain how to modify these settings in both .NET Framework and .NET Core, how to close a connection immediately, and discuss server-side considerations.

Monitoring Database Connections

You can use tools like SQL Server Profiler to monitor the database connections and observe how the connection pooling settings affect the behavior. Instead of going into detailed results in each section, I’ll describe the high-level impact.

I’m running a local SQL Server instance on port 1433 and executing SQL commands in a console app running locally.

Here’s what the SQL Server logs look like when a connection is made:

TCP    127.0.0.1:1433         0.0.0.0:0              LISTENING
TCP    [::1]:2867             [::1]:1433             ESTABLISHED
TCP    [::1]:1433             [::]:0                 LISTENING
TCP    [::1]:1433             [::1]:2867             ESTABLISHED

Changing the Idle Connection Timeout

By default, an idle connection is closed after 30 seconds. If a connection is idle and not executing commands, it will be considered unused. Below, I change the idle connection timeout to 2 minutes.

In .NET Framework

Use SqlConnection.ClearPool to change the idle connection timeout:

// Create a new SqlConnection instance
var sqlConnection = new SqlConnection("your_connection_string");

// Set the idle timeout for connections in the pool
SqlConnection.ClearPool(sqlConnection);

Note: You can apply this setting globally by modifying the connection string to set the Connect Timeout parameter.

In .NET Core

Use SqlConnection.PooledConnectionIdleTimeout to adjust the idle timeout:

// Configure SqlConnection to have a custom idle timeout
var connectionString = "Server=localhost;Database=YourDatabase;Integrated Security=True;";
var sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();

Results

When making a request, a connection is opened, and once the request is completed, the connection enters an idle state.

If the idle connection timeout is set to 2 minutes, here are the possible outcomes:

  • Another query is executed within 2 minutes: The connection is still available, and it will be reused. The idle timer is reset.
  • No further query is executed within 2 minutes: The connection remains idle and is closed automatically after the timeout.

This behavior shows that the connection can stay open indefinitely if it is frequently reused before the timeout expires.

Changing the Max Connection Lifetime

By default, connections can remain open forever as long as they are being used. If this is not desirable, you can limit the maximum lifetime of a connection. Below, I will show how to set the maximum connection lifetime to 5 minutes.

In .NET Framework

Use SqlConnection.ConnectionTimeout to limit the maximum lifetime of a connection:

// Create the SqlConnection instance
var sqlConnection = new SqlConnection("your_connection_string");

// Set the max connection lifetime
sqlConnection.ConnectionTimeout = 300; // 5 minutes in seconds

In .NET Core

Use SqlConnection.PooledConnectionLifetime to change the maximum connection lifetime:

// Set the maximum connection lifetime to 5 minutes
var connectionString = "Server=localhost;Database=YourDatabase;Integrated Security=True;Pooling=true;Max Pool Size=100;PooledConnectionLifetime=300;";
var sqlConnection = new SqlConnection(connectionString);

Results

You can periodically send queries to test the connection lifetime:

while (true)
{
    var command = new SqlCommand("SELECT * FROM Stocks WHERE Symbol = 'MSFT'", sqlConnection);
    var result = command.ExecuteReader();
    Console.WriteLine(result);

    await Task.Delay(TimeSpan.FromMinutes(1));
}

This approach sends queries every 1 minute. Since the connection lifetime is set to 5 minutes, after the first connection is made, the connection will be closed and a new connection opened after 5 minutes.

Closing the Connection Immediately

In case you want to close the connection immediately after the request is done, simply add the Connection: close header. In the case of database connections, you can manage this behavior by clearing the connection pool.

// Clear the connection pool to close all connections immediately
SqlConnection.ClearAllPools();

Server-side Configuration

Just as client-side settings control the idle timeout and connection lifetime, the server-side also has a role in connection management. SQL Server, for example, has a setting known as Remote Query Timeout that can impact connection handling. External factors such as server load or timeouts can also influence connection closure.

Here’s an example of configuring SQL Server’s connection timeout:

-- SQL Server example of setting a connection timeout
EXEC sp_configure 'remote query timeout', 300;
RECONFIGURE;

Configuring connection pooling is crucial for optimizing performance, but it also requires a balance between client-side and server-side settings. By adjusting both the idle connection timeout and the maximum connection lifetime, you can control how long connections remain active and optimize resource utilization. Always remember that these settings may be impacted by server-side configurations as well, so ensure your server’s settings are aligned with your application’s needs.