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

📚 Interview question

How do transactions work in EF Core? Explain the implicit transaction around SaveChanges, when you would call BeginTransaction yourself, what savepoints do, why TransactionScope needs care, and how all of this interacts with a retrying execution strategy on Azure SQL.

Covers EF Core transactions: the implicit SaveChanges transaction and AutoTransactionBehavior, explicit BeginTransaction and UseTransaction, automatic and manual savepoints, TransactionScope pitfalls (Serializable default, async flow, no distributed transactions on Azure SQL) and wrapping explicit transactions in the execution strategy.

Intermediate Theory Intermediate azure-sql ef-core execution-strategy savepoints transactions transactionscope

🎯 Key points

  • SaveChanges is atomic: multi-statement saves run in an implicit transaction; with AutoTransactionBehavior.WhenNeeded (EF Core 7+ default) a single-statement save skips it, Always/Never override
  • Explicit Database.BeginTransactionAsync when several SaveChanges or raw SQL calls must commit together
  • Inside a user transaction EF Core creates a savepoint before each SaveChanges and rolls back to it on failure; CreateSavepointAsync / RollbackToSavepointAsync for your own
  • UseTransaction / GetDbConnection to share one transaction with Dapper or ADO.NET
  • TransactionScope defaults to Serializable and needs TransactionScopeAsyncFlowOption.Enabled for async; Azure SQL has no MSDTC
  • EnableRetryOnFailure refuses user-initiated transactions unless wrapped in CreateExecutionStrategy().ExecuteAsync
  • The whole retried unit must be idempotent and create its transaction inside the delegate
  • Keep transaction boundaries small: never span an HTTP call, a message publish or user think-time; an open transaction also pins a pooled connection

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I say is that most code doesn't need an explicit transaction at all. SaveChanges is already a unit of work: EF Core collects every pending change, opens a transaction on the connection, sends the commands in batches and commits. If any statement fails, the whole lot rolls back and the change tracker keeps the entities in their pending state. Since EF Core 7 it's even smarter: with AutoTransactionBehavior.WhenNeeded, the default, a single-statement save doesn't bother with a transaction because one statement is atomic anyway.

I reach for Database.BeginTransactionAsync when a use case genuinely spans more than one save or mixes EF with raw SQL: for example, an ExecuteUpdateAsync that closes old allocations plus a SaveChanges that inserts the new ones. Inside a user transaction, EF Core automatically creates a savepoint before each SaveChanges and rolls back to it if that save fails, so I can catch the error and carry on. I can also create named savepoints myself. If I need Dapper in the same transaction, I share the connection and call UseTransaction, or pass GetDbTransaction() to Dapper.

TransactionScope is where people get hurt. It defaults to Serializable, which on SQL Server means range locks and deadlocks under load; it doesn't flow across await unless you pass TransactionScopeAsyncFlowOption.Enabled; and if it touches two connections it wants to escalate to a distributed transaction, which Azure SQL doesn't support through MSDTC. The other trap is retries: once you turn on EnableRetryOnFailure, a hand-rolled BeginTransaction throws, because EF can't safely replay half a transaction. You wrap the whole thing in CreateExecutionStrategy().ExecuteAsync and start the transaction inside the delegate. The mistake I see is opening a transaction at the start of a request 'just in case'. A transaction is a lock budget; spend it on the smallest unit that must be atomic."


The options

Mechanism Scope Isolation Typical use
Implicit SaveChanges transaction One SaveChanges call Database default (Read Committed, or RCSI on Azure SQL) Almost everything
Database.BeginTransactionAsync() Several saves and raw SQL on one context Default, or pass IsolationLevel Multi-step use case
UseTransaction(dbTransaction) Shared with ADO.NET/Dapper or a second context on the same connection Whatever the owner set Mixing EF and Dapper
TransactionScope Ambient, across code that doesn't take a transaction parameter Serializable unless set Legacy code; avoid in new code
Savepoints Part of a user transaction Same as the transaction Partial rollback

AutoTransactionBehavior (EF Core 7+)

Value Behaviour
WhenNeeded (default) Transaction only when more than one command is sent
Always Always wrap, even a single command
Never No transaction: only when you really accept partial writes

Retries and transactions

Situation What happens
EnableRetryOnFailure + plain SaveChanges The save is retried as a unit; fine
EnableRetryOnFailure + manual BeginTransaction InvalidOperationException: the execution strategy does not support user-initiated transactions
Wrapped in strategy.ExecuteAsync(...) The delegate (transaction included) is retried from the start; must be idempotent

Production example

A billing run on Azure SQL in Australia East used TransactionScope with default options around three saves. Under month-end load it hit [~40] deadlocks an hour because Serializable took key-range locks on the invoice table. Replacing it with BeginTransactionAsync(IsolationLevel.ReadCommitted) inside the execution strategy, and moving one save outside the transaction, cut deadlocks to [zero] and the run time from [52] to [31] minutes.

🔍 What the interviewer is checking

Checks whether the candidate knows SaveChanges is already transactional and can use explicit transactions correctly with retries on Azure SQL.

Green flags

  • States that each SaveChanges is atomic and that explicit transactions are for multi-step units.
  • Knows the execution strategy refuses user transactions and how to wrap them.
  • Mentions the TransactionScope Serializable default and async flow option.
  • Talks about idempotency of retried work and short transactions.

Red flags

  • Wraps every save in a transaction.
  • Thinks a transaction can include an HTTP call to keep systems consistent.
  • Has never heard of savepoints or the commit-in-doubt problem.

📚 Learn in depth

1. What SaveChanges does with transactions

SaveChanges()
  DetectChanges
  open connection (if closed)
  is there a current user transaction?
     no  -> more than one command? BEGIN TRAN (WhenNeeded)
     yes -> SAVE TRAN __EFSavePoint
  send command batches (MERGE/INSERT ... OUTPUT, UPDATE, DELETE)
  success -> COMMIT (own tran) / release savepoint
  failure -> ROLLBACK (own tran) / ROLLBACK TRAN __EFSavePoint
  AcceptAllChanges (entities become Unchanged)

If the commit fails, entities stay Added/Modified, so you can retry the same SaveChanges. That is what makes the retrying execution strategy safe for plain saves.

2. Explicit transactions

await using var tx = await db.Database.BeginTransactionAsync(ct);
// ExecuteUpdate / ExecuteSql / SaveChanges all enlist automatically
await tx.CommitAsync(ct);
// Dispose without commit = rollback

EF Core keeps the connection open for the transaction's lifetime. IDbContextTransaction.GetDbTransaction() gives you the ADO.NET DbTransaction for Dapper.

3. Savepoints

Since EF Core 5, when SaveChanges runs inside a user transaction it issues SAVE TRANSACTION __EFSavePoint first. If the save fails, it rolls back to that savepoint, leaving earlier work in the transaction intact. You can also call tx.CreateSavepointAsync("BeforeAllocations") and tx.RollbackToSavepointAsync(...). Savepoints are not compatible with MARS (Multiple Active Result Sets); EF Core skips them and logs a warning when MARS is on.

4. TransactionScope internals

TransactionScope sets Transaction.Current (ambient). SqlConnection.Open() enlists in it. Pitfalls:

  • new TransactionScope() uses Serializable and a 1-minute timeout. Always pass TransactionOptions { IsolationLevel = ReadCommitted }.
  • Without TransactionScopeAsyncFlowOption.Enabled, Transaction.Current lives in thread-local state and is lost after await.
  • Opening a second connection inside the scope promotes it to a distributed transaction. .NET 7+ supports that only on Windows with TransactionManager.ImplicitDistributedTransactions = true; Azure SQL Database doesn't support MSDTC (it has elastic database transactions for specific cross-database cases).

5. Execution strategies

SqlServerRetryingExecutionStrategy retries on transient error numbers (for example 40613 database unavailable, 40501 throttling, 49918, timeouts). A retry replays a delegate. EF Core can replay a SaveChanges because it knows its own state; it cannot replay arbitrary user code in an open transaction, so it refuses unless you hand it the whole unit:

strategy.ExecuteAsync(async () => {
    BEGIN TRAN
    work...
    COMMIT          <- if the connection drops here, did it commit?
})

The commit-in-doubt case is why the delegate must be idempotent, or use ExecuteInTransactionAsync with a verifySucceeded callback that checks the database.

6. Isolation on Azure SQL

Azure SQL Database has READ_COMMITTED_SNAPSHOT on by default, so readers don't block writers under Read Committed. Choosing Serializable or Repeatable Read gives that up. Snapshot isolation (IsolationLevel.Snapshot) gives a consistent view for multi-query reads but raises update conflicts (error 3960) on concurrent writes.

Try it yourself

  1. Turn on LogTo(Console.WriteLine, LogLevel.Information) and compare the SQL of a one-entity save and a three-entity save: spot the missing BEGIN TRANSACTION in the first (EF Core 7+).
  2. Inside a BeginTransactionAsync, make the second SaveChanges violate a unique index, catch it, and confirm the first save still commits (automatic savepoint).
  3. Enable EnableRetryOnFailure, call BeginTransactionAsync directly, and read the exception; then fix it with CreateExecutionStrategy().
  4. Run a new TransactionScope() and query sys.dm_tran_session_transactions / DBCC USEROPTIONS to see Serializable.
  5. Run two concurrent Serializable transactions that read then insert into the same range and produce a deadlock; then repeat under Read Committed.

💻 Code

A multi-step use case done safely with retries on Azure SQL.

namespace Billing.Allocations;

using System.Data;
using Microsoft.EntityFrameworkCore;

public sealed class ReallocateCredit(BillingDbContext db)
{
    public async Task ExecuteAsync(int accountId, decimal amount, Guid requestId, CancellationToken ct)
    {
        // The strategy owns the retry; the transaction must be created INSIDE the delegate.
        var strategy = db.Database.CreateExecutionStrategy();

        await strategy.ExecuteAsync(async () =>
        {
            // Idempotency: a retry after an in-doubt commit must not apply twice.
            if (await db.Allocations.AnyAsync(a => a.RequestId == requestId, ct)) return;

            await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);

            // Set-based close of old allocations (no tracking).
            await db.Allocations
                .Where(a => a.AccountId == accountId && a.ClosedAt == null)
                .ExecuteUpdateAsync(s => s.SetProperty(a => a.ClosedAt, DateTimeOffset.UtcNow), ct);

            db.Allocations.Add(new Allocation(accountId, amount, requestId));
            await db.SaveChangesAsync(ct);   // EF Core takes a savepoint here automatically

            await tx.CommitAsync(ct);
            db.ChangeTracker.Clear();        // a retry must not re-add the entity from the failed attempt
        });
    }
}
// Program.cs
builder.Services.AddDbContext<BillingDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Billing"),
        sql => sql.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null)));
// Sharing the transaction with Dapper on the same connection.
await using var tx = await db.Database.BeginTransactionAsync(ct);
var conn = db.Database.GetDbConnection();
await conn.ExecuteAsync("UPDATE Accounts SET Locked = 1 WHERE Id = @id", new { id }, tx.GetDbTransaction());
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);

⚠ Common mistakes

  • Mistake: Wrapping a single SaveChanges in BeginTransaction "to be safe". Why it is wrong: SaveChanges already commits or rolls back as a unit, so the explicit transaction adds a round trip, holds locks and a pooled connection for longer, and buys no extra safety. Instead: rely on the implicit transaction and add an explicit one only when two or more operations must commit together.
  • Mistake: new TransactionScope() with default options. Why it is wrong: it uses Serializable, causing range locks and deadlocks, and loses the ambient transaction after await. Instead: pass ReadCommitted and TransactionScopeAsyncFlowOption.Enabled, or use BeginTransactionAsync.
  • Mistake: Calling BeginTransaction with EnableRetryOnFailure on. Why it is wrong: EF Core throws because it cannot replay half a user transaction. Instead: wrap the unit in CreateExecutionStrategy().ExecuteAsync.
  • Mistake: Creating the transaction outside the retry delegate. Why it is wrong: the retry reuses a dead transaction. Instead: begin and commit inside the delegate.
  • Mistake: Making the retried delegate non-idempotent. Why it is wrong: a commit whose acknowledgement was lost is replayed, so money moves twice. Instead: use a request id check or ExecuteInTransactionAsync with verifySucceeded.
  • Mistake: Holding a transaction open across an HTTP call or message publish. Why it is wrong: locks are held for the remote call's latency and a failure leaves the two systems inconsistent anyway. Instead: commit first and use the outbox pattern.
  • Mistake: Opening a second connection inside TransactionScope on Azure SQL. Why it is wrong: it tries to promote to a distributed transaction, which Azure SQL Database doesn't support. Instead: share one connection or redesign the boundary.

🏛 Senior insight: trade-offs

A senior answer starts from 'do I need this at all?'. One SaveChanges per use case, with the aggregate loaded and changed in memory, gives atomicity for free and works naturally with the retrying strategy. When I see explicit transactions in a code review, I ask what crosses the boundary: two saves can usually be one, and a transaction that includes an HTTP call or a bus publish is a design bug, not a transaction problem. Consistency with other systems comes from the outbox and idempotent consumers, not from stretching a database transaction.

The boundary also has a resource cost people forget: while a transaction is open, its connection is pinned and can't go back to the pool, so long transactions under load show up as pool exhaustion ('Timeout expired... max pool size was reached') as well as blocking. The second senior signal is knowing the Azure SQL defaults: RCSI is on, so Read Committed readers don't block writers, and choosing Serializable or TransactionScope defaults throws that away. I measure with sys.dm_tran_locks, deadlock graphs from the system_health session, and transaction duration in Application Insights dependencies.

Option When it fits Cost When not to
Implicit SaveChanges One aggregate per use case None Never wrong
BeginTransactionAsync in execution strategy Several saves or EF + raw SQL that must be atomic Longer locks, pinned connection, idempotency work Spanning remote calls
Savepoints Recover from one failed step and continue Extra round trip With MARS enabled
TransactionScope Legacy code without a transaction parameter Serializable default, async flow, promotion New code on Azure SQL

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions that SaveChanges is atomic or batches commands. Why: Checks the mechanics of what SaveChanges does inside its transaction.
    How to answer

    SaveChanges runs a pipeline:

    1. DetectChanges: compares every tracked entity with its original-values snapshot and marks changed properties Modified (skipped if AutoDetectChangesEnabled is false, so you must call it yourself).
    2. Ordering: builds commands per entity and sorts them by the foreign-key graph, so principals are inserted before dependants and dependants deleted before principals.
    3. Batching: groups commands into as few round trips as possible (SQL Server's default MaxBatchSize is 42).
    4. Transaction: wraps them in an implicit transaction when more than one statement is needed, or joins your explicit one.
    5. Fix-up: on SQL Server, INSERT ... OUTPUT INSERTED.[Id] returns identity keys and UPDATE ... OUTPUT INSERTED.[RowVersion] returns new row versions; EF Core replaces temporary keys, propagates them to foreign keys, then marks everything Unchanged.

    The trade-off: one call gives atomicity and few round trips, but its cost grows with every tracked entity.

  2. When: Candidate mentions isolation levels, RCSI or Serializable. Why: Checks isolation level choices on Azure SQL with EF Core.
    How to answer

    New Azure SQL Database databases have READ_COMMITTED_SNAPSHOT (RCSI) on by default (on-premises SQL Server doesn't; check is_read_committed_snapshot_on in sys.databases for your database). With RCSI each statement reads a consistent committed version without blocking writers. For several statements to see the same version, use IsolationLevel.Snapshot (needs ALLOW_SNAPSHOT_ISOLATION ON). The cost is the row-version store (tempdb, or the persistent version store when accelerated database recovery is on, as it always is in Azure SQL Database), a 14-byte versioning tag added to modified rows, and update conflicts (error 3960) under snapshot that you must retry.

  3. When: Candidate mentions EnableRetryOnFailure with explicit transactions. Why: Checks understanding of idempotency and verifySucceeded in retried transactions.
    How to answer

    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.

↩ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me