📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Which ADO.NET basics are still worth knowing when you mostly use EF Core? Explain SqlConnection, SqlCommand, SqlDataReader and parameters, how connection pooling really works, and the bugs you find in legacy ADO.NET code.

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.

Mid-Level Theory Intermediate ado-net connection-pooling legacy-migration sql-injection sqlclient

🎯 Key points

  • Microsoft.Data.SqlClient replaces System.Data.SqlClient on modern .NET
  • Open late, dispose early: using/await using returns the physical connection to the pool
  • One pool per exact connection string text and identity: any difference (keyword order, whitespace, user) creates a separate pool and fragments pooling
  • Max Pool Size defaults to 100 and is set in the connection string; when exhausted, Open waits Connect Timeout (15 s) then throws InvalidOperationException
  • Always use parameters (SqlParameter with explicit SqlDbType and size): prevents SQL injection and plan-cache bloat
  • SqlTransaction ties commands to one connection: pass it to every command, keep it short (locks), dispose to roll back if not committed
  • SqlDataReader is forward-only and streaming; DataSet/DataTable buffer everything in memory
  • Monitor pool usage with SqlClient event counters (dotnet-counters) and sys.dm_exec_sessions; EF Core and Dapper sit on the same rules

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Even if I use EF Core every day, ADO.NET is underneath it, so its rules still decide whether the app survives load. A SqlConnection represents a session with SQL Server. When you Open it, the pool hands you an existing physical connection if one is free, and when you Dispose it, 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 next Open waits for the connect timeout, 15 seconds by default, and then throws 'Timeout expired... max pool size was reached'.

SqlCommand runs 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 with SqlDbType, because AddWithValue guesses: a C# string becomes nvarchar sized to the value, which can cause implicit conversions against a varchar column and kill an index seek. SqlDataReader streams rows forward-only; DataSet and DataTable load 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.SqlClient and the async methods. The senior line: the pool is a shared, limited resource, so connection lifetime is an architecture concern, not a coding detail."


The core types

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

Pooling facts

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains pooling per connection string, Max Pool Size 100 and the timeout
  • Insists on parameters with explicit types and explains implicit conversions
  • Knows reader versus DataSet trade-offs
  • Mentions Microsoft.Data.SqlClient and its Encrypt default

Red flags

  • Thinks Close/Dispose closes the TCP connection every time
  • Uses string concatenation or only "sanitises" input
  • Fixes pool exhaustion by raising Max Pool Size

📚 Learn in depth

1. How pooling works

app 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.

2. Why parameters matter twice

  • Security: parameters are sent separately from the SQL text, so values can't change the query. This is the primary defence against SQL injection (OWASP A03).
  • Performance: 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.
  • Type accuracy: 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.

3. Readers versus DataSets

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.

4. Async and threads

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.

5. System.Data.SqlClient vs Microsoft.Data.SqlClient

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).

Try it yourself

  1. Write a loop that opens 150 connections without disposing them and watch the exception at 101; then add using and repeat.
  2. Query sys.dm_exec_sessions filtered by program_name to see your pooled sessions.
  3. Run the same query with concatenated values 1,000 times and check sys.dm_exec_cached_plans for single-use plans; repeat with parameters.
  4. Compare an nvarchar parameter against a varchar indexed column and look at the execution plan for CONVERT_IMPLICIT.
  5. Use dotnet-counters monitor --counters Microsoft.Data.SqlClient.EventSource to watch active and pooled connections.

💻 Code

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));
        }
    }
}

⚠ Common mistakes

  • Mistake: Not disposing 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.
  • Mistake: Concatenating user input into SQL. Why it is wrong: SQL injection, and a new plan per value. Instead: Use SqlParameter every time, including in dynamic SQL (sp_executesql).
  • Mistake: Using 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.
  • Mistake: Raising 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.
  • Mistake: Building connection strings per user or per request. Why it is wrong: Each unique string gets its own pool, defeating pooling. Instead: Use one connection string per database and pass identity another way.
  • Mistake: Loading large results into a DataSet. Why it is wrong: High memory use and LOH allocations. Instead: Stream with SqlDataReader and page in SQL.
  • Mistake: Upgrading to 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions connection pooling as an object pool Why: Checks they understand pooling trade-offs and reset bugs in general
    How to answer

    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.

  2. When: Candidate mentions pool exhaustion Why: Checks they can diagnose leaks versus slow queries versus too much concurrency
    How to answer

    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.

🛠 Real-world problems: how you handle them

Pool exhaustion at the Monday peak from an undisposed reader
Situation
A [customer billing portal] on ASP.NET Web API 2 and .NET Framework 4.8, using hand-written ADO.NET against Azure SQL, serving [about 3,000] users at the start of each week.
Signals
Every Monday around [9:00] the error rate jumped to [15%] with 'max pool size was reached' exceptions in the logs; response times went from [200 ms] to [15 s+]; Azure SQL CPU was low, which ruled out an overloaded database.
Investigation
Queried `sys.dm_exec_sessions` for the app's `program_name` during the incident: [100] sessions, most `sleeping`. Captured a memory dump with ProcDump and opened it in WinDbg with SOS (`!dumpheap -type SqlDataReader`), finding [90+] live readers rooted from an export method. Code search showed `GetStatementReader()` returning an open `SqlDataReader` that callers didn't dispose when an exception was thrown.
Resolution
Immediate: recycled the app pool to free connections and temporarily routed the export feature off peak. Real fix: changed the method to materialise results inside a `using` block (or return an `IAsyncEnumerable` that owns the connection), added `using` to [12] other call sites found by an analyser, and parameterised two concatenated queries found on the way.
Prevention
Enabled CA2000 (dispose objects before losing scope) and a custom code review checklist item for data access; added a pool usage metric and an alert at [80%] of Max Pool Size; added a load test of the Monday traffic pattern to the release pipeline.

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.

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me