With EF Core 10 and EnableRetryOnFailure, why does code inside BeginTransactionAsync throw, and how do you make the whole bakery order retry safely?
answer
- each operation retried on its own
- does not support user-initiated transactions
- Database.CreateExecutionStrategy().ExecuteAsync
- every attempt rebuilds its state
- ExecuteInTransactionAsync with verifySucceeded
basics
~20 sA retrying execution strategy replays single operations, so it refuses a transaction you opened: the first query or save inside it throws InvalidOperationException. Wrap the transaction in Database.CreateExecutionStrategy().ExecuteAsync so the whole unit is replayed, rebuilding its state on every attempt.
solid answer
~50 s`EnableRetryOnFailure()` installs a retrying execution strategy - on Npgsql it retries when an `NpgsqlException` reports `IsTransient` or a `TimeoutException` occurs, by default up to 6 times with delays capped at 30 seconds. Each query and each `SaveChanges` becomes its own retriable unit. Inside a transaction you began, replaying one statement would be wrong, because the rollback also undid the statements before it - so the strategy throws: "The configured execution strategy 'NpgsqlRetryingExecutionStrategy' does not support user-initiated transactions...". The fix is `var strategy = db.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { await using var tx = ...; ...; await tx.CommitAsync(); });`. The delegate is replayed whole, so it must rebuild everything - clear the change tracker or create the contexts inside it. A failure during commit leaves the outcome unknown; `ExecuteInTransactionAsync` with a `verifySucceeded` check covers that.
code
csharp · 13 linesvar strategy = db.Database.CreateExecutionStrategy();
var order = BuildOrder(request); // client-generated Guid key
await strategy.ExecuteInTransactionAsync(
async ct =>
{
db.Orders.Add(order);
await db.SaveChangesAsync(acceptAllChangesOnSuccess: false, ct);
},
async ct => await db.Orders.AsNoTracking().AnyAsync(o => o.Id == order.Id, ct),
cancellationToken);
db.ChangeTracker.AcceptAllChanges();go deeper
Know that EnableRetryOnFailure retries transient database errors, and that a manual transaction needs extra wrapping when it is on.
Explain why the strategy refuses user transactions and how CreateExecutionStrategy().ExecuteAsync makes the transaction one retriable unit.
Write replayable delegates - clean tracker, no external side effects - and handle the unknown-commit case with client keys or ExecuteInTransactionAsync verification.
Set a policy for which writes may be retried automatically, how idempotency is guaranteed, and where retries belong between EF Core and the caller.
## What EnableRetryOnFailure does Cloud databases drop connections and fail over. **Connection resiliency** in EF Core is an **execution strategy** that catches transient failures and replays the operation. On Npgsql you turn it on with `options.UseNpgsql(cs, o => o.EnableRetryOnFailure())`. The defaults come from EF Core's `ExecutionStrategy` base class: **6 retries** and a **maximum delay of 30 seconds**; overloads take `maxRetryCount`, `maxRetryDelay` and extra PostgreSQL error codes. `NpgsqlRetryingExecutionStrategy` treats an exception as transient when it is an `NpgsqlException` whose `IsTransient` is true, or a `TimeoutException`. With the strategy on, **each query and each `SaveChanges` call is retried as a unit**. That works because one `SaveChanges` is atomic: a failed attempt left nothing behind, so replaying it is safe. (Retrying also makes EF Core buffer query results, which costs memory on large result sets.) ## Why a transaction you began breaks it A bakery's order placement saves the order, then runs an `ExecuteUpdateAsync` on the loyalty table, inside `BeginTransactionAsync`. Suppose the connection drops during the second step. The database rolls back the **whole** transaction, including the order insert. If the strategy simply replayed the second step, the order would be gone and the loyalty points would be added for an order that does not exist. EF Core therefore refuses: when a retrying strategy finds a transaction already active - begun by you, enlisted with `UseTransaction`, or an ambient `TransactionScope` - the first operation it would execute throws: - `InvalidOperationException`: "The configured execution strategy 'NpgsqlRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit." ## The fix: make the whole unit retriable ```csharp var strategy = db.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { db.ChangeTracker.Clear(); // start each attempt clean await using var tx = await db.Database.BeginTransactionAsync(ct); db.Orders.Add(BuildOrder(request)); // rebuild the work await db.SaveChangesAsync(ct); await db.LoyaltyAccounts.Where(a => a.CustomerId == request.CustomerId) .ExecuteUpdateAsync(s => s.SetProperty(a => a.Points, a => a.Points + 10), ct); await tx.CommitAsync(ct); }); ``` Rules for the delegate: 1. **Everything that must be atomic goes inside it** - the `BeginTransactionAsync`, every save and every bulk update, and the commit. 2. **It must be replayable.** The strategy calls it again from the top after a transient failure. Entities added in a failed attempt are still in the change tracker, so clear it (or create the contexts inside the delegate) and rebuild the work from the request data. 3. **No side effects outside the database** - sending an email or calling a payment API inside it repeats them on every attempt. 4. **Two contexts?** Run both inside one delegate, sharing the connection and transaction as usual; the strategy of one context drives the retry. ## The commit you cannot see If the connection drops **while the commit is in flight**, nobody knows whether it committed. By default the strategy retries as if it rolled back; for an insert with a store-generated key that can create a **duplicate order**. The documented options: | Option | How | |---|---| | accept rare failure | use client-generated keys (for example GUIDs) so a duplicate insert fails instead of silently duplicating | | rebuild state | discard the context, reload from the database, tell the user the outcome is uncertain | | verify | `strategy.ExecuteInTransactionAsync(operation, verifySucceeded)` - begins and commits for you and calls your check, such as "does an order with this id exist?", when the commit fails | | track the transaction | insert a marker row per transaction and look for it after a commit failure | With the verify option the docs call `SaveChangesAsync(acceptAllChangesOnSuccess: false)` inside the operation and `ChangeTracker.AcceptAllChanges()` after it, so a retried attempt still sees the entries as pending.
- Why does a plain SaveChangesAsync with no explicit transaction retry fine under EnableRetryOnFailure?One `SaveChanges` call is atomic: if an attempt fails transiently, its own transaction rolled back and nothing was written, so the strategy can replay it. EF Core runs `SaveChanges` through the execution strategy for exactly that reason. The trouble starts only when your own transaction groups several operations.
- Your strategy delegate adds an Order and the first attempt fails. Why could the second attempt insert two orders?The `Add` from the first attempt is still in the change tracker as `Added`, and the second attempt adds another instance. Clear the tracker (or create the context inside the delegate) at the start of each attempt, or build the entities once outside the delegate and add them only inside it after a clear.
- EnableRetryOnFailure retries the failed statement inside my open transaction.
- Catching the InvalidOperationException and retrying manually fixes the strategy error.
- The strategy delegate runs once, so state left in the change tracker does not matter.
- A failure during commit always means the transaction rolled back.
- An ambient TransactionScope is exempt from the user-initiated transaction check.