Connection Pooling Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Connection Pooling runs in O(1) time and O(n) space, in C# as in every other language.
- ✓ADO.NET pools automatically and invisibly: SqlConnection and NpgsqlConnection are lightweight handles over a pool keyed by the CONNECTION STRING, so new SqlConnection(cs) followed by Open() takes a pooled physical connection and Dispose() returns it rather than closing it.
- ✓Create a connection per operation, wrap it in a using declaration, and let the pool do its job, holding one open for the lifetime of a service is an anti-pattern in .NET precisely because the pool already solves that.
- ✓The C# trap: Pools are keyed by the EXACT connection string, so two strings differing only by whitespace, key order or casing create two separate pools, and an application that builds its string dynamically can silently multiply its connection count until the server rejects it.
- ✓Taking a pooled connection is on the order of a microsecond against tens of milliseconds to establish a new one.
What Connection Pooling actually is
Connection Pooling in C#: what you actually reach for
C# implementation
using System.Data;
using Microsoft.Data.SqlClient;
public sealed class UserRepository
{
// ONE canonical connection string: pools are keyed by its exact text,
// so a difference in whitespace or key order creates a SECOND pool.
private const string ConnectionString =
"Server=db.internal;Database=app;Max Pool Size=20;Min Pool Size=2;";
public async Task<string?> GetNameAsync(long id, CancellationToken ct)
{
// A connection per operation is CORRECT in .NET: the pool is
// underneath. Holding one open for the service lifetime is not.
await using var conn = new SqlConnection(ConnectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand(
"select name from users where id = @id", conn);
cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = id;
await using var reader = await cmd.ExecuteReaderAsync(ct);
return await reader.ReadAsync(ct) ? reader.GetString(0) : null;
}
}
// "Timeout expired. The timeout period elapsed prior to obtaining a
// connection from the pool" almost always means a LEAK: a connection or
// a DataReader not disposed on some exception path. It is rarely a
// reason to raise Max Pool Size.Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Connection Pooling?
ADO.NET pools automatically and invisibly: SqlConnection and NpgsqlConnection are lightweight handles over a pool keyed by the CONNECTION STRING, so new SqlConnection(cs) followed by Open() takes a pooled physical connection and Dispose() returns it rather than closing it. Pooling is controlled by connection-string keywords, Max Pool Size, Min Pool Size, Pooling and Connection Lifetime, not by an object you construct.
What is the most common C# mistake when implementing Connection Pooling?
Pools are keyed by the EXACT connection string, so two strings differing only by whitespace, key order or casing create two separate pools, and an application that builds its string dynamically can silently multiply its connection count until the server rejects it. The visible failure is the classic message that the timeout expired and the maximum pool size was reached, which almost always means a leak: a connection not disposed, usually because a DataReader or the connection itself was left open on an exception path. Async is part of the fix too, blocking on a connection with .Result starves the thread pool that would complete it.
How does Connection Pooling actually perform in C#?
Taking a pooled connection is on the order of a microsecond against tens of milliseconds to establish a new one. Default Max Pool Size is 100 per pool per process, which is generally too many for a database and is the number to lower rather than raise when tuning. Min Pool Size above zero keeps warm connections for latency-sensitive services at the cost of holding server resources while idle. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.