Database connection pool exhaustion is one of those problems that usually appears when an application is already under pressure. The application may work normally during development and testing, but once traffic increases, requests start becoming slow, database operations begin timing out, and eventually the API can appear completely stuck.
A common mistake is to assume that the database server has run out of connections. In many cases, the actual problem is inside the application. Connections are being held for too long, database work is running concurrently without limits, transactions remain open, or a connection is not returned to the pool correctly.
ASP.NET Core applications commonly use connection pooling through ADO.NET providers such as SQL Server and PostgreSQL. Understanding how that pool works makes this class of production issue much easier to diagnose.
What Is Database Connection Pooling?
Opening a database connection is not always cheap. A connection may require network communication, authentication, session setup, and other initialization work.
Instead of creating a completely new physical connection for every request, the application maintains a pool of reusable connections.
The simplified flow looks like this:
ASP.NET Core Request
|
v
Application asks for DB connection
|
v
Connection Pool
| |
Available None available
| |
v v
Reuse Wait
connection |
v
Timeout if wait is too long
When application code finishes using a connection, the connection is normally returned to the pool rather than physically closed.
For example:
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
using var command = new SqlCommand(
"SELECT Id, Name FROM Products",
connection);
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine(reader["Name"]);
}
The important part is not simply opening the connection. The connection must be disposed correctly so that the provider can return it to the pool.
What Does Connection Pool Exhaustion Mean?
Suppose an application has a pool that can provide 100 connections.
If 100 requests acquire connections and keep them busy, request number 101 cannot immediately get another connection from that pool.
It must wait.
If those existing connections are eventually returned, the waiting request can continue. If they remain occupied for too long, the request can time out.
This creates a chain reaction:
More traffic
|
v
More concurrent DB operations
|
v
Connections remain busy
|
v
Pool becomes exhausted
|
v
New requests wait
|
v
Request timeouts
|
v
Retries create more DB pressure
The retry step is particularly dangerous. A database problem can become an application-wide availability problem when every failed request immediately retries the same operation.
How ASP.NET Core Applications Get Into This Situation
Several patterns can cause connection pools to become exhausted.
Connections Are Held While Unnecessary Work Runs
Consider code like this:
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
var customer = await GetCustomerAsync(connection);
await SendEmailAsync(customer);
await PublishEventAsync(customer);
await SaveAuditRecordAsync(connection);
The connection remains occupied while email and event operations are performed.
If those operations take several seconds, the database connection is also unavailable for several seconds.
A better approach is to keep the database operation focused:
Customer customer;
await using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
customer = await GetCustomerAsync(connection);
}
await SendEmailAsync(customer);
await PublishEventAsync(customer);
The database connection is released before unrelated work starts.
Long Transactions Can Consume the Pool
Transactions are another common source of long-lived connections.
For example:
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await using var transaction = await connection.BeginTransactionAsync();
await UpdateOrderAsync(connection, transaction);
await CallExternalServiceAsync();
await UpdateInventoryAsync(connection, transaction);
await transaction.CommitAsync();
Keeping a transaction open while calling an external service is risky.
The external service might take seconds to respond. During that entire period, the database connection and transaction remain active.
A better design is to keep transactions around database work only:
Begin transaction
|
v
Update database
|
v
Commit transaction
|
v
Release connection
|
v
Call external service
If the business workflow requires atomic coordination between the database and another system, an outbox pattern is often a better solution than holding a database transaction open across a network call.
Too Many Concurrent Requests Can Overwhelm the Pool
Increasing database pool size is not always the right solution.
Imagine an API receiving thousands of requests concurrently. If every request immediately starts a database operation, increasing the pool may simply move the bottleneck to the database server.
The application needs controlled concurrency.
For example, a bounded channel can be used for workloads that do not need to execute immediately:
var channel = Channel.CreateBounded<WorkItem>(
new BoundedChannelOptions(1000)
{
FullMode = BoundedChannelFullMode.Wait
});
This allows the application to apply backpressure instead of allowing unlimited database work to start simultaneously.
For normal HTTP requests, the better approach is usually to reduce unnecessary database work and avoid creating excessive parallel operations.
Avoid Opening Multiple Connections for One Request
This pattern can create unnecessary pressure:
var customer = await GetCustomerAsync();
var orders = await GetOrdersAsync();
var payments = await GetPaymentsAsync();
var preferences = await GetPreferencesAsync();
If each method creates its own connection and several operations execute concurrently, a single request can consume multiple pool connections.
This becomes worse when the request volume increases.
Before introducing parallel database operations, determine whether they are actually necessary.
For example:
var customer = await GetCustomerAsync();
var orders = await GetOrdersAsync(customer.Id);
Sequential database access may sometimes be slower for one request, but it can be much safer for the database under high concurrency.
The right choice depends on query duration, connection limits, database capacity, and application traffic.
Connection Pool Size Is Not a Performance Setting by Itself
Most database providers expose settings such as minimum and maximum pool size.
For a SQL Server connection string, you might see:
Server=localhost;
Database=Shop;
User Id=app;
Password=secret;
Max Pool Size=100;
Min Pool Size=10;
Increasing Max Pool Size from 100 to 500 does not automatically make the application faster.
It can actually make the database less stable if the database server cannot handle the additional concurrent work.
Think about the complete system:
ASP.NET Core
|
v
Connection Pool
|
v
Database Server
|
v
CPU / Memory / I/O / Locks
The pool should support the database capacity rather than hide a database bottleneck.
The Difference Between Pool Exhaustion and Database Slowness
These problems can look similar from the API side.
Problem | Typical symptom | Likely cause |
|---|
Pool exhaustion | Requests wait for connections | Connections are occupied |
Slow query | Connections stay busy | Poor query performance |
Lock contention | Queries wait | Blocking transactions |
Database CPU pressure | Queries become slow | Too much database work |
Network problem | Connection or command timeouts | Connectivity issues |
Connection leak | Pool gradually becomes unavailable | Connections not returned |
This distinction matters because increasing the connection pool does not fix a slow query.
If one query takes 10 seconds and holds a connection for the entire duration, increasing the pool may only allow more copies of that expensive query to run.
Use Async Database APIs Correctly
ASP.NET Core applications should normally use asynchronous database APIs for I/O-bound operations.
For example:
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT Id, Name FROM Products",
connection);
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
Passing the request cancellation token is also important.
If the client disconnects, the application should not necessarily continue expensive database work that nobody will consume.
public async Task<Product?> GetProductAsync(
int id,
CancellationToken cancellationToken)
{
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT Id, Name FROM Products WHERE Id = @id",
connection);
command.Parameters.AddWithValue("@id", id);
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
if (!await reader.ReadAsync(cancellationToken))
{
return null;
}
return new Product
{
Id = reader.GetInt32(0),
Name = reader.GetString(1)
};
}
Cancellation does not solve every database problem, but it prevents abandoned requests from unnecessarily consuming resources.
Watch for Accidental Connection Leaks
One of the most important rules is simple: every acquired connection must have a clear disposal path.
Prefer:
await using var connection = new SqlConnection(connectionString);
instead of manually managing connection lifetime.
For synchronous code:
using var connection = new SqlConnection(connectionString);
This pattern makes cleanup much harder to forget.
Be especially careful with exception paths.
Bad:
var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await DoSomethingAsync();
connection.Close();
If DoSomethingAsync() throws an exception, the Close() call may never execute.
Better:
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
await DoSomethingAsync();
The connection is disposed even when an exception occurs.
Be Careful With Streaming Queries
A connection can remain occupied while a result set is being consumed.
For example:
await using var reader =
await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
await ProcessRowAsync(reader);
}
If ProcessRowAsync() performs slow network operations, the database connection stays active throughout the processing.
A better pattern is often to read the required data first and then process it after releasing the connection.
For example:
var products = new List<Product>();
await using (var reader =
await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
products.Add(new Product
{
Id = reader.GetInt32(0),
Name = reader.GetString(1)
});
}
}
foreach (var product in products)
{
await ProcessProductAsync(product);
}
This should still be balanced against memory usage when result sets are large.
Monitor Connection Pool Behavior
When investigating pool exhaustion, application logs alone are usually not enough.
Monitor at least:
Request duration
Database command duration
Database connection acquisition time
Number of active database connections
Number of waiting requests
Database CPU
Database locks
Query execution time
Request timeout rate
Connection errors
Retry count
A useful diagnostic question is:
Is the application unable to get a connection?
or
Is it getting connections, but the database work is taking too long?
That distinction determines the next investigation step.
Add Timeouts Instead of Waiting Forever
Every database operation should have sensible timeout behavior.
For example:
command.CommandTimeout = 30;
Timeouts should be selected according to the operation rather than using an arbitrary large value.
A very long timeout can make pool exhaustion worse because connections remain occupied while requests continue waiting.
At the same time, an extremely short timeout can create unnecessary failures.
The goal is to fail predictably and allow the application to recover.
Be Careful With Retry Policies
Retries can help with transient database failures, but they can also amplify connection pressure.
Consider this situation:
100 requests
|
v
Database becomes slow
|
v
100 requests timeout
|
v
100 requests retry
|
v
200 database operations
|
v
More pressure
This is sometimes called a retry storm.
Retries should therefore have:
A limited number of attempts
Exponential backoff
Jitter where appropriate
Clear handling for non-transient errors
Reasonable command timeouts
Do not retry every SQL exception automatically.
Common Mistakes
Increasing Max Pool Size First
This treats the symptom rather than the cause.
Find out why connections remain occupied before increasing the pool.
Holding Connections During HTTP Calls
Database connections should not normally remain open while calling another API.
Release the connection first whenever the business operation allows it.
Keeping Transactions Open Too Long
Transactions should contain the smallest practical set of database operations.
Ignoring Cancellation
Disconnected clients can leave unnecessary database work running.
Running Unlimited Parallel Queries
Task.WhenAll() is useful, but using it against a large collection of database operations can create a connection and database overload.
For example, avoid blindly doing this:
await Task.WhenAll(
items.Select(item => SaveItemAsync(item)));
For large collections, use bounded concurrency.
Assuming Pool Exhaustion Means a Database Bug
The database may be healthy. The application could simply be holding connections too long.
A Practical Troubleshooting Process
When production starts reporting database connection timeout errors, investigate in this order.
Step 1: Check the Application Logs
Look for:
Step 2: Check Database Activity
Determine whether queries are:
Step 3: Review Connection Lifetime
Search the codebase for:
OpenAsync()
and:
Open()
Then inspect how each connection is disposed.
Step 4: Look for Long Transactions
Identify transactions that remain open while performing:
HTTP requests
Message publishing
File operations
External service calls
CPU-heavy processing
Step 5: Check Concurrency
Look for:
Task.WhenAll(...)
large parallel loops, background workers, and high request concurrency.
Step 6: Review Pool Configuration
Only after understanding application behavior should you consider changing pool limits.
Advantages of Proper Connection Pool Management
Proper connection management provides several practical benefits:
Better request throughput
More predictable response times
Fewer database timeout errors
Lower database connection overhead
Better database stability
Easier capacity planning
Improved application behavior under load
The biggest benefit is predictability. A system with controlled database concurrency is much easier to operate than one where every incoming request can create unlimited database pressure.
Disadvantages of Poor Pool Configuration
A poorly configured connection pool can cause:
Requests waiting unnecessarily
Database overload
Connection timeout errors
Increased memory usage
Retry storms
Cascading application failures
A larger pool is not automatically better. The pool is part of a larger resource-management system.
Best Practices Checklist
Before deploying an ASP.NET Core application to production, check the following:
Dispose every database connection correctly.
Keep connection lifetimes as short as practical.
Avoid external network calls while holding database connections.
Keep transactions short.
Use asynchronous database APIs.
Pass cancellation tokens to database operations.
Avoid unlimited parallel database operations.
Configure sensible command and connection timeouts.
Use retries only for appropriate transient failures.
Monitor database query duration.
Monitor connection utilization.
Investigate slow queries before increasing pool size.
Load-test the application with realistic database concurrency.
Make database capacity part of application capacity planning.
Summary
Database connection pool exhaustion is usually a resource-management problem rather than a simple configuration problem.
The connection pool exists to reuse database connections efficiently, but every connection still represents a limited resource. If application code holds connections during slow operations, keeps transactions open too long, launches unlimited concurrent queries, or fails to dispose connections correctly, the pool can become exhausted under load.
The most effective solution is to control connection lifetime and database concurrency first. Keep database operations focused, release connections before performing unrelated work, use cancellation and timeouts, and investigate slow queries and blocking before increasing pool limits.
A healthy ASP.NET Core application should not just be able to connect to its database. It should be able to manage database connections predictably when traffic, latency, and failures increase.
Join the conversation! Your thoughts help the community grow.