Transactions from .NET against SQL Server: SqlTransaction vs TransactionScope (default serializable, TransactionScopeAsyncFlowOption, escalation to distributed transactions), connection pooling and leaked transactions, isolation level reset, timeouts, and XACT_ABORT.
SqlTransaction is explicit: one connection, BeginTransaction, pass the transaction to every command, Commit, and disposing without commit rolls back. TransactionScope is ambient: connections opened inside enlist automatically. Its traps: it defaults to Serializable with a 1-minute timeout, needs TransactionScopeAsyncFlowOption.Enabled to survive await, and if a second connection is opened it promotes to a distributed transaction, which needs MSDTC on Windows and isn't supported against Azure SQL Database except through elastic transactions.
Also: a client timeout cancels the command but the server-side transaction can stay open unless SET XACT_ABORT ON, and pooled connections can carry state between requests. Prefer one connection and an explicit transaction, kept short.
"My default is an explicit transaction on one connection:
BeginTransactionAsync, every command gets that transaction,CommitAsyncat the end, andawait usingso any exception disposes it and rolls back. EF Core does the same thing under the hood:SaveChangesis already one transaction, andDatabase.BeginTransactionAsyncgives me an explicit one when I need severalSaveChangescalls or raw SQL to be atomic.
TransactionScopeis convenient because it's ambient, but it has three traps. First, it defaults to serializable isolation and a one-minute timeout, so I always passTransactionOptions. Second, withoutTransactionScopeAsyncFlowOption.Enabledthe ambient transaction doesn't flow acrossawait, and you get errors or work outside the transaction. Third, opening a second connection inside it, even to the same database if the first one is still open, promotes it to a distributed transaction. On .NET 7 and later that works only on Windows with MSDTC, and Azure SQL Database doesn't take part in MSDTC at all; you need elastic database transactions, which is a different set-up. For example, at [company] a refactor added a repository that opened its own connection inside an existing scope; it worked on developers' Windows machines and failed in Linux containers with a 'distributed transactions are not supported' error. We fixed it by sharing one connection.The subtle production issue is timeouts and pooling. When a command times out, the client sends an attention signal and the statement stops, but by default the transaction stays open on the server, holding locks, until the connection is closed or reused. With
SET XACT_ABORT ON, the timeout rolls back the whole transaction on the server. So I putXACT_ABORT ONin every transactional procedure, and I keep transactions short: read and call external services outside, write inside. A transaction's cost is how long it holds locks, so it should be milliseconds, not seconds."
SqlTransaction |
TransactionScope |
|
|---|---|---|
| Style | Explicit, per connection | Ambient, implicit enlistment |
| Default isolation | Read committed | Serializable |
| Async | Works naturally | Needs TransactionScopeAsyncFlowOption.Enabled |
| Multiple connections | Not possible | Promotes to distributed (MSDTC) |
| Timeout | Command timeouts only | Scope timeout (default 1 min, max 10 min machine default) |
| Use when | Almost always | Coordinating code you don't control on one connection |
| Problem | Cause | Fix |
|---|---|---|
| Open transaction after timeout | XACT_ABORT OFF, attention doesn't roll back |
SET XACT_ABORT ON |
| Isolation level on next request | Session-level SET TRANSACTION ISOLATION LEVEL stays on the pooled connection |
Set per transaction; recent SqlClient resets on reuse, don't rely on it |
| Connection pool exhaustion | Connections not disposed | await using; check Max Pool Size (default 100) |
| Long locks | External calls inside the transaction | Outbox or move calls out |
A service that timed out under load left transactions open on pooled connections; locks lingered until the connection was reused, causing blocking chains of [30+] sessions. Adding SET XACT_ABORT ON to the procedures and fixing an undisposed connection in a background job ended the chains, and the 'sleeping session with open transaction' alert went quiet.
Checks practical knowledge of transaction APIs in .NET and the production traps around isolation defaults, promotion, timeouts and pooling.
Green flags
TransactionScope defaults to serializable and needs async flowXACT_ABORTRed flags
TransactionScope everywhereA SQL Server transaction belongs to a session (SPID), which is a physical connection. SqlTransaction sends BEGIN TRAN through TDS; all commands on that connection must carry the transaction object, or SqlClient throws 'ExecuteReader requires the command to have a transaction'.
SqlConnection.Close()/Dispose() returns the physical connection to the pool. On reuse, SqlClient calls sp_reset_connection, which resets most session state (temp tables, SET options) and rolls back an open transaction. Two caveats:
sp_reset_connection; newer SQL Server and SqlClient versions reset it, but code shouldn't rely on that.CommandTimeout (default 30 s) or a cancelled CancellationToken sends an attention to the server. The current statement is cancelled; the transaction is not rolled back unless XACT_ABORT is ON. Locks remain until something rolls back.
client: timeout -> ATTENTION -> server stops statement
XACT_ABORT OFF: transaction still open, locks held
XACT_ABORT ON : transaction rolled back, locks released
TransactionScope sets Transaction.Current (stored in thread or async-local storage). SqlConnection.Open checks it and enlists. One connection = lightweight local transaction. A second durable resource, or a second connection open at the same time, triggers promotion to a distributed transaction coordinated by MSDTC. Since .NET 7, distributed transactions are supported on Windows only and must be enabled with TransactionManager.ImplicitDistributedTransactions = true; otherwise promotion throws. Azure SQL Database supports elastic transactions between Azure SQL databases only, not MSDTC.
SaveChanges wraps its batch in a transaction.Database.BeginTransactionAsync(isolation) for multi-step work; UseTransactionAsync to share an ADO.NET transaction with Dapper on the same connection.EnableRetryOnFailure, user-initiated transactions must run inside CreateExecutionStrategy().ExecuteAsync(...) so the whole block is retried.T-SQL has no real nested transactions: BEGIN TRAN inside a transaction just increments @@TRANCOUNT, and an inner ROLLBACK rolls back everything. Savepoints (SAVE TRAN name; SqlTransaction.Save) allow partial rollback. EF Core uses savepoints automatically when SaveChanges runs inside a user transaction.
XACT_ABORT; query sys.dm_exec_sessions.open_transaction_count from SSMS.SET XACT_ABORT ON and compare.TransactionScope and open two connections at once on Linux; read the exception. Then share one connection.transaction_isolation_level for the session inside a default TransactionScope.Microsoft.Data.SqlClient.EventSource pool counters while leaking undisposed connections.An explicit transaction shared by Dapper and EF Core on one connection, plus a safe TransactionScope helper.
namespace Orders.Data;
using System.Data;
using System.Transactions;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using IsolationLevel = System.Data.IsolationLevel;
public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
}
public sealed class Order
{
public int Id { get; set; }
public required string Status { get; set; }
}
public sealed class OrderCompletion(OrdersDb db)
{
public async Task CompleteAsync(int orderId, CancellationToken ct)
{
// Retrying execution strategy must wrap the WHOLE transaction.
var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
var order = await db.Orders.SingleAsync(o => o.Id == orderId, ct);
order.Status = "Completed";
await db.SaveChangesAsync(ct);
// Dapper on the SAME connection and transaction: no promotion, one atomic unit.
var conn = db.Database.GetDbConnection();
await conn.ExecuteAsync(new CommandDefinition(
"INSERT dbo.OrderEvents (OrderId, Kind) VALUES (@orderId, 'Completed');",
new { orderId }, transaction: tx.GetDbTransaction(), cancellationToken: ct));
await tx.CommitAsync(ct);
});
}
}
public static class Transactions
{
// If you must use TransactionScope: read committed, async flow, explicit timeout.
public static TransactionScope Create(TimeSpan? timeout = null) => new(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
Timeout = timeout ?? TimeSpan.FromSeconds(30)
},
TransactionScopeAsyncFlowOption.Enabled);
}
-- Every transactional procedure: a client timeout or error rolls back on the server.
CREATE OR ALTER PROCEDURE dbo.CompleteOrder @OrderId int
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRAN;
UPDATE dbo.Orders SET Status = 'Completed' WHERE Id = @OrderId AND Status = 'Paid';
IF @@ROWCOUNT = 0 THROW 50001, 'Order is not in Paid state.', 1;
INSERT dbo.OrderEvents (OrderId, Kind) VALUES (@OrderId, 'Completed');
COMMIT;
END
new TransactionScope() with defaults. Why it is wrong: Serializable isolation and range locks cause deadlocks. Instead: Pass TransactionOptions with read committed.TransactionScope with await but without async flow. Why it is wrong: The ambient transaction doesn't flow, causing exceptions or work outside it. Instead: TransactionScopeAsyncFlowOption.Enabled.XACT_ABORT, the transaction stays open and holds locks. Instead: SET XACT_ABORT ON and dispose the transaction.await using everywhere.BEGIN TRAN as nested transactions. Why it is wrong: An inner ROLLBACK rolls back everything. Instead: Use savepoints for partial rollback.BeginTransaction with EF Core retries enabled outside an execution strategy. Why it is wrong: EF Core throws, or retries only part of the work. Instead: CreateExecutionStrategy().ExecuteAsync.The senior message is: transactions are about lock duration and boundaries, and the .NET APIs make it easy to get both wrong silently. One connection, explicit transaction, read committed, XACT_ABORT ON, milliseconds long. Every extra second a transaction stays open is a second its X locks block other sessions, so under load transaction duration translates directly into blocking chains, timeouts and deadlocks; measure it (Application Insights dependency durations, sys.dm_tran_active_transactions) rather than guess. Anything that spans services is not a database transaction: use an outbox or a saga.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SqlTransaction / EF Core BeginTransaction |
Default for multi-statement work | Must pass the transaction around | Never a bad default |
TransactionScope (configured) |
Legacy code or libraries that open their own commands on one connection | Ambient magic, promotion risk | Linux containers with multiple connections; Azure SQL DB distributed work |
| Elastic transactions | Atomic work across Azure SQL databases | Azure-specific, latency | On-premises or mixed resources |
| Outbox / saga | Database plus message broker or other services | Eventual consistency | Single-database work |
By default every SaveChanges is atomic: EF Core opens a transaction, sends all the INSERT/UPDATE/DELETE batches and commits, or rolls back on any failure (since EF Core 7 it skips the transaction when there is only one statement). You call Database.BeginTransactionAsync yourself only when several SaveChanges calls or raw SQL must commit together; inside that, EF Core takes a savepoint before each SaveChanges so one failed save can be undone without losing the rest. TransactionScope works but defaults to Serializable isolation, needs TransactionScopeAsyncFlowOption.Enabled for async, and cannot escalate to a distributed transaction on Azure SQL. With EnableRetryOnFailure, an explicit transaction must run inside CreateExecutionStrategy().ExecuteAsync, so the whole unit is retried. The trade-off: explicit transactions give you multi-step atomicity at the cost of longer-held locks and retry complexity, so prefer one SaveChanges per use case.
If the connection drops during COMMIT, the client can't know whether the transaction committed, and a blind retry may apply the work twice. Make the unit idempotent (a unique request id checked at the start and enforced by a unique index), or use ExecuteInTransactionAsync with a verifySucceeded delegate that queries the database to see if the work landed before retrying. Clear the change tracker between attempts so stale Added entities aren't re-sent. Only transient errors should be retried: let permanent failures (constraint violations, login failures) surface immediately. Log each retry and its outcome so an in-doubt commit can be traced and reconciled later.
Blocking is sessions waiting for locks another session holds. I find the head blocker by following blocking_session_id in sys.dm_exec_requests to the session that isn't blocked itself, or with sp_WhoIsActive @find_block_leaders = 1. Then I check what it is: a running query, or a sleeping session with open_transaction_count > 0, which means the app opened a transaction and never finished it.
Typical .NET causes: transactions left open around slow work or HTTP calls, scans caused by missing indexes locking far more rows than needed, lock escalation from big batches, and leaked connections. Mitigation may be KILL, but the fix is indexing, shorter transactions and RCSI so readers don't wait on writers.
How to tell it (STAR)
**S:** After moving our order service to Linux containers, order completion failed on every request with a 'distributed transactions not supported' error. **T:** I needed to restore the service and fix the cause. **A:** We rolled back first. The stack trace showed the error when a second connection opened inside a TransactionScope; a recent refactor had a repository opening its own connection, which promoted the transaction to MSDTC. That worked on Windows but isn't supported on Linux or Azure SQL Database. I replaced the scope with an explicit EF Core transaction shared with the Dapper repository on one connection, and moved our integration tests to Linux containers. **R:** The redeploy had [0] transaction errors, and the Linux-based tests have caught [one] similar issue before release since.
Last updated 23 Nov 2026.