Covers raw ADO.NET with Microsoft.Data.SqlClient: connection lifetime and pooling (pool per connection string, Max Pool Size, pool exhaustion), commands and parameters versus string concatenation, readers versus DataSet/DataTable, async APIs, transactions, and the typical legacy bugs.
ADO.NET is the layer every .NET data tool sits on, EF Core and Dapper included. SqlConnection opens a session (from Microsoft.Data.SqlClient on modern .NET), SqlCommand runs SQL with SqlParameters, and SqlDataReader streams rows forward-only.
Connection pooling keeps physical connections open per exact connection string: Dispose returns the connection to the pool, it doesn't close the socket. The default Max Pool Size is 100; when all are in use, Open waits up to the connect timeout and throws. Legacy code bugs: connections not disposed (pool exhaustion), string-concatenated SQL (injection and plan-cache bloat), huge DataSets, and synchronous calls that block threads. The trade-off: raw ADO.NET gives full control and speed, but every safety habit is your job.
"Even if I use EF Core every day, ADO.NET is underneath it, so its rules still decide whether the app survives load. A
SqlConnectionrepresents a session with SQL Server. When youOpenit, the pool hands you an existing physical connection if one is free, and when youDisposeit, it goes back to the pool rather than closing the TCP connection. There's one pool per unique connection string, so building connection strings dynamically, say with the user's name in them, creates a pool per user. The default maximum is 100 connections, and when they're all busy, the nextOpenwaits for the connect timeout, 15 seconds by default, and then throws 'Timeout expired... max pool size was reached'.
SqlCommandruns the SQL, and it should always use parameters. Concatenating values is SQL injection, and it also gives every value its own query plan, which fills the plan cache. I set the type and length explicitly withSqlDbType, becauseAddWithValueguesses: a C#stringbecomesnvarcharsized to the value, which can cause implicit conversions against avarcharcolumn and kill an index seek.SqlDataReaderstreams rows forward-only;DataSetandDataTableload everything into memory, which is fine for 50 rows and terrible for 500,000.The mistake I see in legacy code is connections opened in one method and closed in another, or a reader returned up the stack and never disposed. Under low load it works; under peak load the pool runs dry and the whole site times out. On modern .NET I also switch to
Microsoft.Data.SqlClientand the async methods. The senior line: the pool is a shared, limited resource, so connection lifetime is an architecture concern, not a coding detail."
| Type | Role | Watch out for |
|---|---|---|
SqlConnection |
Session from the pool | Always using/await using; open late, close early |
SqlCommand |
SQL text or stored procedure | CommandTimeout default 30 s; parameters |
SqlParameter |
Typed value | Set SqlDbType and Size; avoid AddWithValue on varchar columns |
SqlDataReader |
Forward-only stream | Holds the connection busy until disposed |
SqlTransaction |
Local transaction | Pass to every command; using rolls back if not committed |
DataSet / DataTable / SqlDataAdapter |
In-memory buffered data | Memory and GC cost for large results |
SqlBulkCopy |
Fast bulk insert | Much faster than row-by-row inserts |
| Setting | Default | Note |
|---|---|---|
Pooling |
true |
Don't turn off |
Max Pool Size |
100 | Per pool, per process |
Min Pool Size |
0 | Raise to keep warm connections |
Connect Timeout |
15 s | How long Open waits for a free connection |
| Pool key | Exact connection string + identity | Different whitespace or user = different pool |
A classic outage pattern: an ASP.NET app's error log shows a burst of 'max pool size was reached' at the Monday 9 am peak. sys.dm_exec_sessions shows 100 sessions from the app, most sleeping with an open transaction or idle. The cause is usually a code path that returns a SqlDataReader without disposing it on an exception. Wrapping it in using and adding a pool-usage metric removes the outages completely.
Checks that the candidate understands the ADO.NET layer under every ORM, especially pooling and parameters, and can spot legacy data-access bugs.
Green flags
Red flags
Close/Dispose closes the TCP connection every timeapp code SqlClient pool (per connection string) SQL Server
new SqlConnection(cs)
conn.Open() ── free connection? ── yes ─▶ hand it out (sp_reset_connection on first use)
│ no ─▶ below Max Pool Size? ─▶ open new TCP + login
│ else wait (Connect Timeout) ─▶ throw
conn.Dispose() ──▶ return to pool (socket stays open)
idle connections are trimmed after ~4–8 minutes
When a pooled connection is reused, the client sends sp_reset_connection with the next command, which resets session state (temp tables, SET options, open transactions are rolled back). Some state survives, such as the isolation level in older versions, which is a classic subtle bug.
SELECT ... WHERE Id = @id is one plan reused for every value. Concatenated SQL creates one ad hoc plan per value, bloating the plan cache and burning CPU on compiles.AddWithValue("@code", "AB12") sends nvarchar(4). Against a varchar(10) indexed column, SQL Server converts the column side (implicit conversion), which can turn an index seek into a scan. Explicit SqlDbType.VarChar, 10 avoids it.SqlDataReader reads rows as they arrive over TDS; memory stays flat. SqlDataAdapter.Fill(DataSet) reads everything into DataRow objects (boxed values, change tracking), which can use 5–10 times the raw data size and push objects onto the LOH. Legacy apps often fill DataSets for reports and then hit OutOfMemoryException in 32-bit app pools.
ExecuteReaderAsync and ReadAsync release the thread while waiting for SQL Server. Legacy code calling .Result on async methods, or synchronous calls inside highly concurrent ASP.NET code, ties up thread-pool threads and causes thread starvation. Note that ReadAsync on very large varbinary(max) columns has had performance problems in SqlClient; use CommandBehavior.SequentialAccess and streams for big blobs.
System.Data.SqlClient is the old provider (in .NET Framework, and a deprecated package on modern .NET). Microsoft.Data.SqlClient is the actively developed one: Entra ID (Azure AD) authentication, Always Encrypted improvements, TDS 8 / strict encryption. Version 4.0+ defaults Encrypt=true, which breaks connections to servers without a trusted certificate until you fix the certificate (or, as a stop-gap, set TrustServerCertificate=true).
using and repeat.sys.dm_exec_sessions filtered by program_name to see your pooled sessions.sys.dm_exec_cached_plans for single-use plans; repeat with parameters.nvarchar parameter against a varchar indexed column and look at the execution plan for CONVERT_IMPLICIT.dotnet-counters monitor --counters Microsoft.Data.SqlClient.EventSource to watch active and pooled connections.Legacy ADO.NET with the classic bugs, then the modern version with Microsoft.Data.SqlClient.
// Before (.NET Framework, System.Data.SqlClient): leaks, injection, buffering
public DataTable GetInvoices(string customerCode)
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Billing"].ConnectionString);
conn.Open(); // never disposed on exception
var sql = "SELECT * FROM Invoices WHERE CustomerCode = '" + customerCode + "'"; // injection
var adapter = new SqlDataAdapter(sql, conn);
var table = new DataTable();
adapter.Fill(table); // buffers every row and column
conn.Close();
return table;
}
// After (.NET 10, Microsoft.Data.SqlClient): pooled, parameterised, streaming, async
namespace Billing.Data;
using System.Data;
using Microsoft.Data.SqlClient;
public sealed record InvoiceRow(int Id, string Number, decimal Total, DateTime IssuedUtc);
public sealed class InvoiceReader(string connectionString)
{
public async IAsyncEnumerable<InvoiceRow> GetInvoicesAsync(
string customerCode,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default)
{
await using var conn = new SqlConnection(connectionString); // returned to pool on dispose
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("""
SELECT Id, Number, Total, IssuedUtc
FROM dbo.Invoices
WHERE CustomerCode = @code
""", conn);
// explicit type and size match the varchar(10) column: no implicit conversion
cmd.Parameters.Add("@code", SqlDbType.VarChar, 10).Value = customerCode;
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
yield return new InvoiceRow(
reader.GetInt32(0), reader.GetString(1), reader.GetDecimal(2), reader.GetDateTime(3));
}
}
}
SqlConnection or SqlDataReader. Why it is wrong: Connections don't return to the pool, and under load Open times out with 'max pool size was reached'. Instead: Use using/await using in the same method that opens them.SqlParameter every time, including in dynamic SQL (sp_executesql).AddWithValue everywhere. Why it is wrong: It infers nvarchar and sizes from the value, causing implicit conversions and plan cache fragmentation. Instead: Specify SqlDbType and Size.Max Pool Size to 1,000 to fix pool timeouts. Why it is wrong: It hides a leak or slow queries and can overload SQL Server. Instead: Find the leak or long-held connections first.DataSet. Why it is wrong: High memory use and LOH allocations. Instead: Stream with SqlDataReader and page in SQL.Microsoft.Data.SqlClient 4+ without testing encryption. Why it is wrong: Encrypt=true is the default and untrusted certificates fail to connect. Instead: Install a trusted certificate; use TrustServerCertificate=true only as a short, documented stop-gap.In migrations, I treat legacy ADO.NET as valuable, tested behaviour: it often encodes years of tuned SQL. Moving it to EF Core for its own sake is rarely worth it. I'd switch the provider to Microsoft.Data.SqlClient, fix disposal and parameters, make it async, and maybe wrap it with Dapper to remove mapping boilerplate.
Transactions deserve a specific look. A SqlTransaction belongs to one connection, every command must be given it, and while it's open SQL Server holds locks, so a transaction that spans a slow HTTP call or user think time causes blocking for everyone else. TransactionScope is convenient but can escalate to a distributed transaction (MSDTC on .NET Framework) when a second connection opens; on .NET it throws instead unless distributed transactions are explicitly enabled on Windows. I keep transactions short and local. For monitoring I watch SqlClient's event counters (active-hard-connections, number-of-pooled-connections, number-of-free-connections) with dotnet-counters or exported to Application Insights, alert well before Max Pool Size, and keep one connection string per database in configuration so pools don't fragment.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Keep raw ADO.NET, modernised | Tuned SQL, hot paths, bulk work | Low | Lots of CRUD boilerplate |
| Dapper over ADO.NET | Hand-written SQL with less mapping code | Low | You need change tracking and migrations |
| EF Core | New CRUD-heavy features, rich domain model | Medium | Porting tuned reporting SQL just for consistency |
SqlBulkCopy / TVPs |
Inserting thousands of rows | Low | Small writes |
Object Pool keeps reusable objects so callers rent and return them instead of allocating. In .NET it helps when objects are expensive to create or are large (connections, big buffers, arrays over 85 KB that land on the LOH), or when churn is extreme.
ObjectPool<T> (Microsoft.Extensions.ObjectPool): a policy creates and resets objects, IResettable exists from .NET 8, and it retains ProcessorCount * 2 objects by default.ArrayPool<T>.Shared: Rent can return a bigger array than you asked for, and you must never touch it after Return.AddDbContextPool resets EF state but not your own fields. Connection pooling is automatic per connection string.Pooling can be slower: a gen0 allocation is a pointer bump, while a pool adds synchronisation, reset cost and long-lived objects. Bad resets leak data between users. Prove the benefit with BenchmarkDotNet and dotnet-counters before adopting a pool.
First tell leak from slow queries from too much concurrency. Check SqlClient event counters (active vs free connections) or sys.dm_exec_sessions for the app's program_name: many sleeping sessions means connections held but idle (leak, open readers, long transactions); many running/suspended means slow queries or blocking (check sys.dm_exec_requests, wait types, Query Store; in Azure SQL also Query Performance Insight and Application Insights dependency telemetry). Check the configuration too: connection strings that differ per request fragment the pool, and a request spike or retry storm can exceed 100 concurrent queries even without a leak. On .NET Framework, a memory dump showing many undisposed SqlConnection/SqlDataReader objects confirms a leak; in code, look for connections not in using or held across slow calls. Fix the leak, tune the slow query, or limit concurrency; only then reconsider Max Pool Size.
How to tell it (STAR)
**S:** Our [billing portal] went down every Monday morning with connection pool timeouts, while the database itself was idle. **T:** I was asked to find the cause and stop the weekly outage. **A:** I checked SQL Server sessions during the incident and saw the pool full of sleeping connections, which pointed at a leak rather than slow queries. I took a memory dump, found [90+] undisposed data readers from one export method, fixed it and the other call sites an analyser found, and added a pool-usage alert. **R:** The Monday error rate went from [15%] to [zero], and the alert has caught [one] new leak in testing since.
Last updated 23 Nov 2026.