Introduction
Database connections are an important part of almost every ASP.NET Core application. Whenever an API needs to retrieve customer information, save an order, update a product, or execute a database query, it needs a connection to the database.
Opening a new database connection for every operation may appear to be a simple approach, but creating database connections repeatedly can introduce unnecessary overhead. Establishing a connection involves communication between the application and database server, authentication, network operations, and resource allocation.
To avoid repeating this work, .NET database providers use connection pooling. Instead of creating a completely new physical connection every time the application requests one, the provider can reuse an existing connection from a pool.
Connection pooling improves performance and reduces the number of connections that need to be established. However, it can also become a source of problems when connections are not released correctly, database operations take too long, or the application receives more concurrent requests than the available connections can handle.
For example, an ASP.NET Core API may work correctly when only a few users are accessing it. As traffic increases, requests may start taking longer, database operations may time out, and the application may report errors indicating that the connection pool has been exhausted.
These problems are not always caused by a slow database. Sometimes, the application itself is holding connections for too long or requesting more connections than the configured pool can provide.
In this article, we will understand how connection pooling works in ASP.NET Core applications, identify common connection pool problems, and explore practical ways to diagnose and fix them. We will use SQL Server and Microsoft.Data.SqlClient for the main examples, while also discussing how the same concepts apply to other .NET database providers.
Understanding Database Connection Pooling
A database connection represents an active communication channel between an application and a database server.
When an application creates a connection using a database provider such as Microsoft.Data.SqlClient, the provider can use an existing physical connection from a pool instead of creating a new one.
A connection pool is a collection of reusable database connections maintained by the database provider. Connections are grouped according to their connection configuration, so connections with different connection strings or connection settings may belong to different pools.
Consider an ASP.NET Core API that receives 100 requests. Each request needs to retrieve information from SQL Server.
Without connection pooling, the application may need to establish a new physical database connection for every request. This creates unnecessary connection setup work and can put additional pressure on the database server.
With connection pooling enabled, the application can reuse connections.
The process generally works like this:
The application requests a database connection.
The database provider checks whether an available connection exists in the appropriate pool.
If an available connection exists, the provider returns it to the application.
The application executes its database operations.
When the application closes or disposes the connection, the provider normally returns the physical connection to the pool.
Another operation can reuse that connection.
The important detail is that closing a pooled connection does not normally mean that the underlying physical connection is destroyed. It means that the application has finished using it and the provider can make it available for another operation.
This is why properly disposing database connections is so important. If an application keeps a connection open after completing its database operation, that connection remains unavailable to other requests even when it is no longer needed.
How Connection Pool Exhaustion Happens
Every connection pool has a maximum number of connections that can be used simultaneously. When all available connections are busy, a new request must wait until another connection is returned to the pool.
If connections are returned quickly, this waiting may be temporary and barely noticeable.
However, if many requests hold connections for a long time, the pool can become exhausted. New requests then wait for an available connection. If the waiting period exceeds the connection timeout, the application receives a connection timeout exception.
For example, imagine an application with a maximum pool size of 100 connections.
If 100 concurrent operations are already holding connections, the next operation cannot immediately obtain another connection from that pool. It must wait until one of the existing operations releases its connection.
This situation becomes more serious when database operations are slow, transactions remain open, or connections are accidentally leaked.
A common misunderstanding is that increasing the maximum pool size always solves the problem. It may temporarily reduce waiting, but it does not fix the underlying issue if the application is holding connections unnecessarily or the database cannot handle the additional workload.
Before changing pool settings, developers should identify why connections are remaining occupied.
Step 1. Understand the Existing Connection Configuration
Let's create a simple ASP.NET Core Web API project that uses SQL Server.
Create the project:
dotnet new webapi -n ConnectionPoolDemo
Navigate to the project directory:
cd ConnectionPoolDemo
Install the SQL Server database provider:
dotnet add package Microsoft.Data.SqlClient
Add the database connection string to appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=CompanyDb;User Id=sa;Password=YourStrongPassword;TrustServerCertificate=True;Max Pool Size=100;Min Pool Size=0;Connect Timeout=15"
}
}
Let's understand the important connection string settings.
Max Pool Size defines the maximum number of connections that can be active in a connection pool at the same time. In this example, the pool can provide up to 100 connections.
Min Pool Size defines the minimum number of connections maintained in the pool. Setting it to zero allows the pool to start without maintaining a minimum number of connections.
Connect Timeout defines how long the application waits when trying to establish a new connection or obtain one from the pool before the operation fails. The default value for SqlClient is generally 15 seconds unless it is changed.
These settings control different aspects of connection management. Max Pool Size limits concurrent connections, while Connect Timeout controls how long an operation waits to obtain a connection.
The connection string also contains TrustServerCertificate=True for this local development example. This should not be copied blindly into production. Production applications should configure certificate validation and encryption according to their database security requirements.
Another important detail is that connection pooling is enabled by default in Microsoft.Data.SqlClient. You do not need to add a separate pooling configuration to activate it.
Step 2. Register the Database Connection Correctly
Open Program.cs and register the connection string.
For this example, we will create a small repository that uses SqlConnection directly.
using Microsoft.Data.SqlClient;
var builder = WebApplication.CreateBuilder(args);
var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException(
"Database connection string is missing.");
builder.Services.AddSingleton(connectionString);
builder.Services.AddScoped<ProductRepository>();
var app = builder.Build();
app.MapGet("/", () => "Connection Pool Demo API is running.");
app.Run();
The connection string is registered as a singleton because it is configuration data and does not need to be recreated for every request.
ProductRepository is registered as a scoped service because it will be used by application operations within a request scope.
Notice that we are not registering a single SqlConnection instance as a singleton. A database connection should not be shared across unrelated requests because it represents an active session with the database.
Instead, each database operation should request its own connection from the provider. The provider then manages physical connection reuse through its internal pool.
This separation is important. The application manages the lifetime of the connection it is using, while the database provider manages the pool of reusable physical connections.
Step 3. Use Connections With Proper Disposal
Create a file named ProductRepository.cs:
using Microsoft.Data.SqlClient;
public class ProductRepository
{
private readonly string _connectionString;
public ProductRepository(string connectionString)
{
_connectionString = connectionString;
}
public async Task<List<string>> GetProductsAsync(
CancellationToken cancellationToken)
{
var products = new List<string>();
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT ProductName FROM Products",
connection);
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
products.Add(reader.GetString(0));
}
return products;
}
}
This implementation demonstrates an important connection pooling practice.
The repository creates a SqlConnection when it needs to access the database. It then opens the connection, executes the query, reads the results, and disposes the connection when the operation is complete.
The await using statement is important because SqlConnection implements asynchronous disposal. It ensures that the connection is released even if an exception occurs while executing the query or reading the results.
When a pooled connection is disposed, Microsoft.Data.SqlClient normally returns the physical connection to its pool instead of immediately closing the underlying network connection.
This allows another request to reuse it.
Now expose an API endpoint:
app.MapGet("/api/products", async (
ProductRepository repository,
CancellationToken cancellationToken) =>
{
var products = await repository.GetProductsAsync(
cancellationToken);
return Results.Ok(products);
});
Every request can now execute the database operation without sharing an active SqlConnection instance with another request.
The repository itself does not need to manage a global collection of connections. The provider handles pooling automatically.
Step 4. Identify Connection Leaks
One of the most common reasons for connection pool exhaustion is a connection leak.
A connection leak happens when an application opens a database connection but does not release it after completing the operation.
Consider the following example:
public async Task GetProductsAsync()
{
var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync();
var command = new SqlCommand(
"SELECT ProductName FROM Products",
connection);
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine(reader.GetString(0));
}
}
At first glance, this code appears to work. It opens a connection, executes a query, and reads the returned records.
However, it does not dispose the SqlConnection, SqlCommand, or SqlDataReader.
The application may continue holding the connection after the method has finished. If this method is called repeatedly, connections can remain unavailable to the pool.
Eventually, the pool may run out of available connections.
The correct implementation should dispose these objects:
public async Task GetProductsAsync()
{
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync();
await using var command = new SqlCommand(
"SELECT ProductName FROM Products",
connection);
await using var reader =
await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine(reader.GetString(0));
}
}
The difference is not in the SQL query. The difference is in resource management.
Using await using ensures that the connection and related database objects are disposed even when the operation fails.
This is particularly important in APIs because the same repository methods may be called hundreds or thousands of times throughout the application's lifetime.
Step 5. Avoid Holding Connections During Unnecessary Operations
Another common problem occurs when an application keeps a database connection open while performing operations that do not require database access.
Consider the following example:
public async Task ProcessOrderAsync()
{
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync();
await UpdateOrderAsync(connection);
await SendEmailAsync();
await GenerateReportAsync();
await SaveOrderHistoryAsync(connection);
}
This method opens a database connection and keeps it open while sending an email and generating a report.
Sending an email may involve a remote SMTP server or an external email provider. Generating a report may involve file operations, calculations, or another external service.
None of these operations necessarily requires the database connection to remain open.
If the email provider responds slowly, the database connection remains occupied during that waiting period. When many requests execute this method concurrently, the application may use a large number of connections without performing database operations continuously.
A better approach is to open connections only around the operations that need them.
public async Task ProcessOrderAsync()
{
await UpdateOrderAsync();
await SendEmailAsync();
await GenerateReportAsync();
await SaveOrderHistoryAsync();
}
The database methods can manage their own connection lifetimes:
private async Task UpdateOrderAsync()
{
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync();
// Execute the required database operation.
}
This approach allows the connection to return to the pool as soon as the database operation finishes.
The goal is not to open and close a physical connection repeatedly. The provider handles physical connection reuse. The goal is to avoid keeping a connection checked out from the pool when the application is waiting for unrelated work.
There are situations where a connection must remain open across multiple operations, especially when a transaction is involved. In those cases, keep the connection open only for the duration required by the transaction.
Step 6. Understand Long-Running Database Transactions
Transactions can also contribute to connection pool problems.
A transaction allows multiple database operations to succeed or fail as one logical unit. This is important when an application needs to maintain data consistency.
However, a transaction usually holds database resources until it is committed or rolled back. If an application keeps a transaction open while performing unrelated operations, it can increase connection usage and database locking.
Consider this example:
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync();
await using var transaction =
await connection.BeginTransactionAsync();
await UpdateInventoryAsync(connection, transaction);
await SendEmailAsync();
await UpdateOrderAsync(connection, transaction);
await transaction.CommitAsync();
The transaction remains open while the application sends an email.
If the email service takes several seconds to respond, the database transaction remains active during that time. Depending on the SQL statements and isolation level, this can also cause locks to remain active longer than necessary.
A better design is to keep database operations within the transaction and move unrelated work outside it whenever the business requirements allow.
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync();
await using var transaction =
await connection.BeginTransactionAsync();
try
{
await UpdateInventoryAsync(connection, transaction);
await UpdateOrderAsync(connection, transaction);
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
await SendEmailAsync();
This example keeps the database transaction focused on the operations that must succeed together.
The email is sent after the transaction completes, so the database connection is no longer required for that operation.
For important business workflows, sending an email after a transaction introduces another consideration: what happens if the database transaction succeeds but the email operation fails?
A production application may use a transactional outbox pattern or a durable background queue to handle this reliably. The important point for connection pooling is that external work should not unnecessarily extend the lifetime of a database transaction.
Step 7. Understand Connection Pool Exhaustion Under Concurrent Requests
Connection pool problems often become visible when the application receives more concurrent requests.
Suppose the maximum pool size is 100.
If 100 requests are simultaneously executing database operations and holding their connections, another request must wait for a connection to become available.
The application may start reporting errors similar to:
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.
This may have occurred because all pooled connections were in use
and max pool size was reached.
This error indicates that the application could not obtain a connection from the pool within the allowed waiting period.
It does not automatically mean that SQL Server is down.
Several different conditions can cause this problem:
Connections are not being disposed.
Database queries are taking too long.
Transactions remain open for extended periods.
The application receives too many concurrent database operations.
The database server is overloaded.
A large number of different connection strings creates separate pools.
The configured pool size is too small for the actual workload.
When this happens, increasing Max Pool Size without investigating the cause can make the situation worse.
For example, increasing the pool size from 100 to 500 may allow more requests to obtain connections, but it also allows the application to create more simultaneous database sessions.
If SQL Server is already overloaded, adding more connections may increase resource pressure and make query response times even worse.
The correct approach is to measure connection usage, identify long-running operations, and understand whether the problem is caused by the application or the database.
Step 8. Monitor Connection Pool Metrics
Connection pool problems are easier to diagnose when the application provides useful metrics.
Microsoft.Data.SqlClient exposes connection-related performance counters and diagnostic information. Modern .NET applications can also use EventCounters and OpenTelemetry-compatible instrumentation to observe database activity.
The exact available metrics depend on the provider and runtime version, so verify the metrics supported by the version used by your application.
Useful measurements include:
Metric | What It Helps Identify |
|---|
Active connections | How many connections are currently being used |
Free connections | How many pooled connections are available |
Pooled connections | How many connections are maintained by the provider |
Connection open duration | How long the application waits to obtain a connection |
Query execution duration | Whether database operations are taking too long |
Connection timeout count | How often connection acquisition fails |
Database request concurrency | How many operations are accessing the database simultaneously |
These measurements help distinguish between different problems.
For example, if active connections remain close to the configured maximum while free connections remain near zero, the application may be holding connections for too long.
If connection usage is relatively low but individual queries take several seconds, the problem may be related to database performance rather than pool capacity.
If the application creates many separate pools, connection usage may be distributed across them. In that situation, checking only one pool may not provide a complete picture.
A useful diagnostic approach is to correlate application metrics with database monitoring. Check both the number of connections opened by the application and the query execution time on the database server.
Step 9. Use Application Logs to Identify Slow Operations
Metrics show what is happening, but application logs help explain why it is happening.
For example, suppose the application reports a high number of active database connections. You need to identify which operations are holding those connections.
You can log the duration of important database operations.
public async Task<List<string>> GetProductsAsync(
CancellationToken cancellationToken)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
try
{
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT ProductName FROM Products",
connection);
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
var products = new List<string>();
while (await reader.ReadAsync(cancellationToken))
{
products.Add(reader.GetString(0));
}
return products;
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
"GetProductsAsync completed in {Duration} ms",
stopwatch.ElapsedMilliseconds);
}
}
This example records the total time spent in the method, including connection acquisition, query execution, and reading the results.
That distinction matters because a slow database operation and a long wait for a pooled connection are not necessarily the same problem.
For deeper diagnostics, measure connection acquisition separately from query execution. This helps identify whether the application is waiting for a pool connection or whether the database itself is taking too long to respond.
Avoid logging passwords, complete connection strings, customer data, or other sensitive information while investigating connection problems.
Step 10. Review Connection String Consistency
Another less obvious cause of connection pool problems is inconsistent connection strings.
Connection pools are associated with connection configuration. If an application creates connections using different connection strings, the provider may maintain separate pools.
For example:
var connection1 =
"Server=localhost;Database=CompanyDb;User Id=appuser;Password=secret";
var connection2 =
"Server=localhost;Database=CompanyDb;User Id=appuser;Password=secret;Application Name=Reporting";
Although these connection strings point to the same database using the same credentials, they contain different settings.
Depending on the provider's pool matching rules, they may use separate pools.
This can make connection usage harder to understand. A developer may configure a maximum pool size of 100 and assume that the application has only one pool, while different parts of the application are creating connections with different configurations.
The best practice is to centralize connection string configuration and avoid creating unnecessary variations.
If the application needs separate connection configurations for different databases or workloads, configure them intentionally and monitor each pool separately.
Step 11. Configure Connection Pool Size Carefully
The Max Pool Size setting controls the maximum number of connections available in a pool.
For example:
Server=localhost;
Database=CompanyDb;
User Id=appuser;
Password=secret;
Max Pool Size=150;
Connect Timeout=20;
Increasing Max Pool Size may help when the application genuinely needs more concurrent database connections and the database server has enough capacity to handle them.
However, it should not be the first response to every connection timeout.
Before increasing the pool size, investigate whether connections are being released correctly, whether queries are slow, whether transactions are held open, and whether the database can handle additional concurrent work.
Also consider the total number of application instances.
For example, if an application has five instances and each instance has a pool configured with a maximum of 150 connections, the application could potentially use up to 750 connections across those pools, assuming they all use the same pool configuration within each instance.
The database server must be able to handle the combined connection demand from all application instances and other clients.
Pool size should therefore be planned using expected traffic, database capacity, application instance count, and the duration of database operations.
Step 12. Understand Connection Pooling With Entity Framework Core
Many ASP.NET Core applications use Entity Framework Core instead of writing SQL commands directly.
EF Core uses database providers that ultimately rely on the underlying ADO.NET connection management.
For example, when using SQL Server, EF Core typically uses Microsoft.Data.SqlClient.
A common registration looks like this:
builder.Services.AddDbContext<AppDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
By default, AddDbContext registers the DbContext as a scoped service. This generally means one DbContext instance is created for a request scope.
The DbContext manages database operations and uses the underlying provider to obtain connections when required.
However, developers should not assume that registering DbContext as scoped means that a physical database connection remains open for the entire HTTP request.
EF Core generally opens and closes connections around individual operations when it manages the connection itself. The underlying provider can return the physical connection to its pool when the operation finishes.
Problems can still occur when application code explicitly opens a connection and leaves it open, uses long-running transactions, or performs database operations that take too much time.
EF Core also supports DbContext pooling through AddDbContextPool.
For example:
builder.Services.AddDbContextPool<AppDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection")));
DbContext pooling and database connection pooling are two different concepts.
DbContext pooling reuses DbContext instances to reduce the cost of creating and initializing them.
Database connection pooling reuses physical database connections through the database provider.
Using DbContext pooling does not replace database connection pooling, and it does not automatically increase the maximum number of database connections.
When using pooled DbContext instances, be careful with state that belongs to a particular request or user. A DbContext instance may be reused, so request-specific state must not remain attached to it after the previous operation finishes.
Step 13. Avoid Blocking Database Operations
Using synchronous database operations inside ASP.NET Core request handlers can contribute to thread pool starvation under heavy load.
Consider this example:
public IActionResult GetProducts()
{
using var connection =
new SqlConnection(_connectionString);
connection.Open();
using var command = new SqlCommand(
"SELECT ProductName FROM Products",
connection);
using var reader = command.ExecuteReader();
// Read database records.
return Ok();
}
This code uses synchronous operations to open the connection, execute the query, and read results.
While waiting for database operations to complete, the request thread remains blocked.
Under high traffic, many blocked request threads can reduce the application's ability to process other incoming requests.
The asynchronous version allows the application to release the request thread while waiting for I/O operations to complete.
public async Task<IActionResult> GetProducts(
CancellationToken cancellationToken)
{
var products = new List<string>();
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT ProductName FROM Products",
connection);
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
products.Add(reader.GetString(0));
}
return Ok(products);
}
Asynchronous database operations improve how ASP.NET Core handles concurrent I/O workloads because request threads do not need to remain blocked while waiting for database responses.
However, async does not create more database connections or increase the capacity of the connection pool. If every request still holds a connection for several seconds, the pool can still become exhausted.
Async improves thread utilization, while proper connection lifetime management helps control database connection usage. Both are important, but they solve different problems.
Step 14. Use Cancellation Tokens for Database Operations
An API request may be cancelled because the client disconnects, a gateway timeout occurs, or the application is shutting down.
If database operations continue after the request is no longer needed, they may consume connections and database resources unnecessarily.
ASP.NET Core provides a CancellationToken that can be passed to asynchronous operations.
For example:
app.MapGet("/api/products", async (
ProductRepository repository,
CancellationToken cancellationToken) =>
{
var products = await repository.GetProductsAsync(
cancellationToken);
return Results.Ok(products);
});
The repository can pass the same token to connection and command operations:
await connection.OpenAsync(cancellationToken);
await command.ExecuteReaderAsync(cancellationToken);
This allows the database operation to respond to cancellation when supported by the provider and operation.
Cancellation is especially useful for long-running queries and large data retrieval operations.
However, cancellation is not a replacement for proper disposal. The application should still dispose connections and related database objects using using or await using.
It is also important to understand that cancelling an operation does not guarantee that every database operation is immediately stopped on the server. The provider must communicate the cancellation request, and the server must process it.
Common Connection Pool Problems and Their Solutions
Problem | Possible Cause | Recommended Solution |
|---|
Connection pool exhausted | Too many connections are being used simultaneously | Check connection disposal and query duration |
Connection timeout | No connection becomes available before the timeout | Investigate pool usage and long-running operations |
Database connections keep increasing | Connections are not being released correctly | Use using or await using |
API becomes slow under load | Database operations or connection acquisition are taking too long | Measure connection wait time and query execution time separately |
Database has too many sessions | Pool sizes are too large across multiple instances | Calculate total connection demand |
Multiple connection pools appear | Different connection string configurations are being used | Centralize and standardize connection strings |
Transactions remain active | Transactions are held open during unrelated operations | Keep transactions short and focused |
Requests continue after client disconnects | Cancellation tokens are not passed to database operations | Propagate CancellationToken through the application |
Increasing pool size does not help | The database itself is overloaded or queries are inefficient | Review database capacity and query performance |
Best Practices for Managing Connection Pools
Always Dispose Database Connections
Every database connection opened by application code should have a clearly defined lifetime.
Use using or await using so connections are released even when an operation throws an exception.
Do not keep connections in static variables or share the same active SqlConnection instance across multiple unrelated requests.
The provider can reuse physical connections through its pool, so there is normally no need to build a separate connection management mechanism inside the application.
Keep Database Operations Short
Open connections only when database access is required, execute the necessary operations, and release them as soon as possible.
Avoid holding a connection while calling external APIs, sending emails, generating files, or performing unrelated calculations.
Shorter connection lifetimes allow more requests to reuse the available pool.
Monitor Before Increasing Pool Size
A connection pool timeout is a symptom, not a complete diagnosis.
Measure active connections, connection acquisition time, query duration, transaction duration, and database server load before changing Max Pool Size.
Increasing the pool size without understanding the problem can move pressure from the application to the database server.
Use Asynchronous Database APIs
Prefer asynchronous connection, command, and reader methods in ASP.NET Core applications that handle concurrent requests.
This improves thread utilization while waiting for database I/O.
Remember that asynchronous operations do not remove the need to manage connection lifetimes or control database concurrency.
Avoid Long-Running Transactions
Keep transactions limited to operations that must succeed or fail together.
Do not keep a transaction open while waiting for an external service unless the business requirement genuinely demands it.
Long transactions can occupy connections and hold database locks, affecting other requests.
Standardize Connection Strings
Use a centralized configuration source for database connection strings.
Avoid creating unnecessary variations because different configurations can lead to separate connection pools.
When multiple pools are required, document why they exist and monitor their usage independently.
Consider Application Instance Count
Pool settings apply to each application process and its connection pools.
If the application runs across multiple containers or server instances, calculate the possible total number of connections across all instances.
This helps prevent a configuration that appears reasonable for one instance from overwhelming the database when the application scales horizontally.
Summary
Connection pooling is an important feature of database providers used by ASP.NET Core applications. It allows applications to reuse physical database connections instead of establishing a new connection for every database operation.
However, connection pool problems can occur when connections are not disposed, database operations take too long, transactions remain open, or the application receives more concurrent database requests than the pool can handle.
In this article, we explored how connection pooling works with Microsoft.Data.SqlClient, how to manage connection lifetimes using await using, and how long-running queries and transactions can contribute to pool exhaustion. We also covered connection string consistency, monitoring, Entity Framework Core, asynchronous database operations, and cancellation tokens.
The most important lesson is that increasing Max Pool Size is not always the correct solution. First, identify why connections are being held and how long database operations take. Once the actual cause is understood, you can make the right changes to application code, database queries, transaction management, or pool configuration.
Proper connection management helps ASP.NET Core applications handle concurrent requests more efficiently and reduces the risk of database connection failures under heavy workloads.
Join the conversation! Your thoughts help the community grow.