Transaction boundaries with EF Core 10 on Azure SQL: one SaveChanges per use case, scoped DbContext, explicit transactions with execution strategies, no transactions around remote calls, and the transactional outbox.
The boundary is the use case: one request or message handler loads what it needs, changes the aggregate, and calls SaveChanges once, which EF Core already runs in a transaction. The DbContext is scoped to that request or message. I add an explicit transaction only when several saves or ExecuteUpdate calls must commit together, wrapped in the execution strategy when retries are on.
I never keep a transaction open across a remote call: it holds locks for the other service's latency, and the other side cannot roll back anyway. When the use case must also publish an event, I write it to an outbox table in the same transaction and relay it afterwards.
The trade-off: short local transactions and eventual consistency between services, instead of the false comfort of distributed transactions.
"I start from the use case. A command handler like
PlaceOrderis one unit of work: load the customer and basket, apply the business rules on the aggregate, and callSaveChangesAsynconce. EF Core sends all the inserts and updates in one transaction, so either the whole order exists or none of it does. TheDbContextis scoped, so every repository or service in that request shares it and its change tracker, and it's disposed at the end. I only open an explicit transaction when I genuinely need two saves to be atomic, for example anExecuteUpdateon stock plus tracked changes on the order, and withEnableRetryOnFailurethat whole block goes insideCreateExecutionStrategy().ExecuteAsyncso a retry replays all of it.What I never do is put a remote call inside the transaction. For example, at [company] a checkout handler opened a transaction, reserved stock, then called the payment gateway, which sometimes took [8 seconds]. Those row locks blocked every other checkout for the same products, and when the gateway timed out after charging the card, our rollback couldn't un-charge it. We restructured it: a short transaction that saves the order as
PendingPaymenttogether with an outbox message, a payment step outside any transaction, and a second short transaction to record the result. Lock waits dropped by [over 90%].The mistake I see is the dual write:
SaveChangesand thenserviceBusSender.SendMessageAsync. If the process dies between them, the order exists and nobody hears about it; swap them and you announce orders that don't exist. The outbox fixes that by making the message part of the same local transaction, and idempotent consumers handle the at-least-once delivery. Transactions are for keeping one database consistent; between services you design for eventual consistency."
| Situation | Boundary |
|---|---|
| Single aggregate change | One SaveChanges, implicit transaction |
Several saves or ExecuteUpdate + tracked changes |
Explicit transaction inside the execution strategy |
| Database write + publish event | Outbox row in the same transaction; relay later |
| Database write + call another service | Separate steps; state machine or saga; no open transaction during the call |
| Long-running workflow (minutes, days) | Saga with persisted state and compensations |
| Batch job over millions of rows | Many short transactions (chunks), each idempotent |
| Anti-pattern | What goes wrong |
|---|---|
| Transaction around an HTTP call | Locks held for remote latency; remote side cannot roll back |
TransactionScope spanning two databases |
Distributed transaction promotion; limited support on Azure SQL and none for brokers |
Singleton or static DbContext |
Not thread-safe; tracker grows forever; stale data |
SaveChanges after every line |
Partial writes on failure; more round trips |
| Transaction-per-request middleware | Holds transactions during view rendering or remote calls |
After moving the payment call outside the transaction and adding an outbox in a [checkout service handling 150 orders per minute at peak], p95 checkout latency fell from [2.4 s to 450 ms], lock waits on Stock dropped by [over 90%], and the "order exists but no confirmation email" incidents, [roughly 3 a week], stopped.
Checks whether the candidate can design consistency boundaries for real services rather than reaching for bigger transactions.
Green flags
SaveChanges per use case and a scoped DbContextRed flags
TransactionScope across services as the answerSaveChangesAsync()
│ no ambient transaction?
├─ BEGIN TRAN
├─ INSERT / UPDATE / DELETE (batched)
└─ COMMIT (or ROLLBACK on any failure)
So a single SaveChanges is atomic with no extra code. ExecuteUpdate/ExecuteDelete run immediately as their own statement, outside that unit, unless you open a transaction.
With EnableRetryOnFailure, EF Core cannot retry a block it does not control, so a user-initiated transaction throws unless wrapped:
strategy.ExecuteAsync(async () =>
{
await using var tx = await db.Database.BeginTransactionAsync();
... SaveChanges / ExecuteUpdate ...
await tx.CommitAsync();
});
The whole lambda is replayed on a transient failure, so it must be safe to run twice (reload state inside it, and clear the change tracker before retrying if needed).
BEGIN TRAN ── UPDATE Stock (X lock) ── HTTP to payments (8 s) ── COMMIT
▲ every checkout for this SKU waits here
The fix is to model the in-between state explicitly (PendingPayment) and make each step a short local transaction.
Transaction:
INSERT Orders ...
INSERT OutboxMessages (Id, Type, Payload, OccurredAt)
COMMIT
Relay (BackgroundService or library):
SELECT TOP (100) ... WHERE ProcessedAt IS NULL ORDER BY OccurredAt
publish to Azure Service Bus (MessageId = outbox Id)
UPDATE OutboxMessages SET ProcessedAt = now
The relay can crash after publishing and before marking, so delivery is at least once. Setting the Service Bus MessageId to the outbox id lets duplicate detection drop repeats within its window, and consumers stay idempotent with an inbox table. Libraries such as MassTransit, NServiceBus and Wolverine provide EF Core outboxes.
AddDbContext registers the context as scoped: one per HTTP request, and one per message if your consumer creates a scope per message. A DbContext is not thread-safe; running two queries on it concurrently throws "A second operation was started on this context instance". Parallel work uses IDbContextFactory<T> with one context per task.
Azure SQL Database has READ COMMITTED SNAPSHOT on by default, so readers do not block writers. Writers still block writers, so short transactions remain the main lever. Use SERIALIZABLE or UPDLOCK hints only for specific invariants (such as unique allocation), and prefer optimistic concurrency with a rowversion for user edits.
SaveChanges twice and kill the process between them; observe the partial state. Then make it one save.EnableRetryOnFailure, open a transaction without the execution strategy, and read the exception.await Task.Delay(5000) after an update and watch blocking in sys.dm_exec_requests from a second session.Task.WhenAll and read the error.A use case with one transaction that saves the order and its outbox message together, and a payment step outside it:
namespace Checkout.Application;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public sealed record PlaceOrder(Guid CustomerId, IReadOnlyList<OrderLineDto> Lines);
public sealed record OrderLineDto(string Sku, int Quantity);
public sealed record OrderPlaced(Guid OrderId, Guid CustomerId, decimal Total);
public sealed class OutboxMessage
{
public Guid Id { get; init; } = Guid.CreateVersion7();
public required string Type { get; init; }
public required string Payload { get; init; }
public DateTimeOffset OccurredAt { get; init; }
public DateTimeOffset? ProcessedAt { get; set; }
}
public sealed class PlaceOrderHandler(CheckoutDbContext db, TimeProvider clock)
{
public async Task<Guid> HandleAsync(PlaceOrder command, CancellationToken ct)
{
var customer = await db.Customers.SingleAsync(c => c.Id == command.CustomerId, ct);
var order = customer.PlaceOrder(command.Lines); // business rules on the aggregate
db.Orders.Add(order);
db.Outbox.Add(new OutboxMessage
{
Type = nameof(OrderPlaced),
Payload = JsonSerializer.Serialize(new OrderPlaced(order.Id, customer.Id, order.Total)),
OccurredAt = clock.GetUtcNow()
});
// One SaveChanges: order, lines and outbox row commit atomically in EF Core's implicit transaction.
await db.SaveChangesAsync(ct);
return order.Id;
// Payment is triggered by the OrderPlaced message, outside any database transaction.
}
}
When two operations must commit together and retries are enabled:
namespace Checkout.Application;
using Microsoft.EntityFrameworkCore;
public sealed class ReserveStockHandler(CheckoutDbContext db)
{
public Task HandleAsync(Guid orderId, CancellationToken ct)
{
var strategy = db.Database.CreateExecutionStrategy();
return strategy.ExecuteAsync(async () =>
{
db.ChangeTracker.Clear(); // the lambda can be replayed; start clean each time
await using var tx = await db.Database.BeginTransactionAsync(ct);
var order = await db.Orders.Include(o => o.Lines).SingleAsync(o => o.Id == orderId, ct);
foreach (var line in order.Lines)
{
var updated = await db.Stock
.Where(s => s.Sku == line.Sku && s.Available >= line.Quantity)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.Available, x => x.Available - line.Quantity), ct);
if (updated == 0) throw new InvalidOperationException($"Out of stock: {line.Sku}");
}
order.MarkStockReserved();
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
});
}
}
-- What the first handler sends: one transaction
BEGIN TRANSACTION;
INSERT INTO [Orders] (...) VALUES (...);
INSERT INTO [OrderLines] (...) VALUES (...), (...);
INSERT INTO [OutboxMessages] ([Id], [OccurredAt], [Payload], [ProcessedAt], [Type]) VALUES (...);
COMMIT;
SaveChanges then publishing to Service Bus directly. Why it is wrong: A crash between the two loses the event; reversing the order announces data that may never commit. Instead: Use a transactional outbox.BeginTransaction with EnableRetryOnFailure and no execution strategy. Why it is wrong: EF Core throws because it cannot safely retry a user-initiated transaction. Instead: Wrap the block in CreateExecutionStrategy().ExecuteAsync.DbContext across threads or registering it as singleton. Why it is wrong: It is not thread-safe and its tracker grows without bound. Instead: Scoped per request or message; IDbContextFactory for parallel work.TransactionScope to span two databases or a database and a broker. Why it is wrong: It relies on distributed transactions, which brokers do not support and Azure SQL Database supports only in limited forms. Instead: Outbox and sagas.The question behind transaction boundaries is "what must be true together, and what can become true a moment later?" Inside one aggregate and one database, use a local transaction and make it short. Across services, accept eventual consistency and design the intermediate states, because users can see them ("payment pending") and support staff need to act on them.
I measure this with lock wait statistics and Query Store on Azure SQL, and with Application Insights dependency timings: any span where a SQL transaction is open while an HTTP dependency runs is a design smell worth an alert.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Single SaveChanges |
One aggregate, one database | None | Multiple independent writes |
| Explicit transaction + execution strategy | Several statements must be atomic | Retry-safe code | Remote calls inside |
| Transactional outbox | DB write + event publish | Relay, table growth, at-least-once | No messaging involved |
| Saga / process manager | Multi-service workflows | State, compensations, monitoring | Single-service operations |
| Distributed transaction (2PC) | Rarely: legacy, same-vendor resources | Availability, limited cloud support | Brokers, HTTP services |
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
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.
Unit of Work records every change made during one business operation and commits them together or not at all.
In EF Core, DbContext is the unit of work. The change tracker records added, modified and deleted entities. One SaveChangesAsync sends them all in a single implicit transaction. That's why every repository in a request must share the same scoped DbContext: separate contexts mean separate commits.
You need an explicit transaction (Database.BeginTransactionAsync) when one operation spans several SaveChanges calls, ExecuteUpdate/ExecuteDelete (which run immediately and skip the change tracker) or raw SQL. With EnableRetryOnFailure, wrap that transaction in CreateExecutionStrategy().ExecuteAsync, and make the block safe to re-run.
The trade-off: one context per request gives you atomic commits, but a long-lived context grows its change tracker and holds stale data.
How to tell it (STAR)
**S:** At [company] our checkout reserved stock and charged the card inside one database transaction. **T:** During a [sale], checkout latency hit [8 seconds] and some customers were charged for failed orders; I [led the fix]. **A:** Tracing showed the payment call running inside the open transaction, holding stock locks. I split the flow into short transactions with a `PendingPayment` state and an outbox message, moved payment into an idempotent consumer, and added a reconciliation job and an alert for transactions open across HTTP calls. **R:** p95 dropped to [450 ms], lock waits fell [over 90%], and orphaned charges went to [zero].
Last updated 23 Nov 2026.