Covers diagnosing transient Azure SQL failures with EF Core: transient error numbers and reconfiguration events, SqlServerRetryingExecutionStrategy and its defaults, the user-initiated transaction error and wrapping work in CreateExecutionStrategy().ExecuteAsync, idempotency and commit-in-doubt with ExecuteInTransactionAsync, connection resiliency in Microsoft.Data.SqlClient, and telemetry for retries.
Azure SQL drops connections during reconfigurations, failovers and throttling (errors such as 40613, 40197, 40501), so clients must retry. EnableRetryOnFailure turns on SqlServerRetryingExecutionStrategy (by default 6 retries, exponential backoff up to 30 s), which safely replays queries and plain SaveChanges. It refuses user-initiated transactions, because it can't replay half a transaction. The fix is to wrap the whole unit, transaction included, in Database.CreateExecutionStrategy().ExecuteAsync(...). Because a lost COMMIT acknowledgement means the work may already have happened, the delegate must be idempotent: use a request id with a unique index, or ExecuteInTransactionAsync with a verifySucceeded check. Keep emails and payment calls out of the delegate (use an outbox). The trade-off: resilience in exchange for designing every write path to be safely repeatable.
"First I'd confirm these are genuinely transient. Error 40613 is 'database not currently available', which Azure SQL raises during reconfigurations such as patching, scaling or failover; 40197 and 40501 are similar service-side conditions. I'd line the failures up against Azure Service Health and the database's Resource Health and maintenance window. If they cluster around those events and last seconds, retrying is the right answer. If they're constant, it's something else: DTU exhaustion, blocking or a bad connection string.
EnableRetryOnFailureregistersSqlServerRetryingExecutionStrategy. EF Core wraps every query and everySaveChangesin it, and on a transient error it waits with exponential backoff and replays the operation. That's safe because EF knows exactly what the operation was. The checkout endpoint broke because it opened its own transaction:BeginTransactionAsync, save the order, decrement stock withExecuteUpdateAsync, commit. If the connection drops halfway, EF can't replay 'the second half', so it throws the error saying the strategy doesn't support user-initiated transactions. The fix is to give the strategy the whole unit:CreateExecutionStrategy().ExecuteAsync(async () => { begin; work; commit; }).The senior part is idempotency. For example, at [company] we [wrapped our checkout in the strategy and then saw a handful of duplicate orders after a failover]. The commit had succeeded on the server, but the acknowledgement was lost, so the strategy retried. I [added a client-generated idempotency key with a unique index and a check at the start of the delegate], and [moved the confirmation email and payment capture to an outbox processed after commit]. [Duplicates went to zero.] EF Core also has
ExecuteInTransactionAsyncwith averifySucceededcallback for exactly this. The mistake I see is turning retries on and assuming the job is done. Retries make failures less visible; idempotency is what makes them harmless."
| Signal | Likely meaning |
|---|---|
| 40613/40197 clustered in seconds, matching a maintenance window | Reconfiguration: retry |
| 40501 / 10928 / 10929 | Throttling or resource limits: retry with backoff, and check the tier |
| Constant timeouts (-2) under load | Blocking, slow queries or pool exhaustion: retries will make it worse |
| 18456 login failed | Not transient: auth or firewall |
InvalidOperationException about user-initiated transactions |
Explicit transaction not wrapped in the strategy |
| Operation | Safe with the strategy? |
|---|---|
| LINQ query | Yes |
Single SaveChanges |
Yes (state kept until success) |
BeginTransaction + several operations, wrapped in ExecuteAsync |
Yes, if idempotent |
| Same, not wrapped | Throws |
| Delegate that sends an email or calls a payment API | No: side effect repeats |
After wrapping [3] transactional endpoints in the execution strategy and adding idempotency keys, a planned failover of the [Australia East] primary produced [0] user-facing errors (previously [~200] 500s per event) and [0] duplicate orders; retries showed as a [2-4 s] latency blip in Application Insights.
Checks that the candidate can diagnose transient Azure SQL failures and implement retries without introducing duplicate side effects.
Green flags
Red flags
client --TCP/TDS--> gateway --> primary replica
| patch / scale / failover
v
new primary (seconds later)
existing connections broken -> 40613 / 40197 / socket errors
new connections succeed after the reconfiguration completes
Microsoft's guidance is that clients must implement retry logic. Microsoft.Data.SqlClient also has idle connection resiliency (ConnectRetryCount, ConnectRetryInterval), which reconnects broken idle connections transparently, but it doesn't replay commands in flight.
ExecuteAsync(operation)
attempt 1 -> SqlException 40613 -> ShouldRetryOn? (SqlServerTransientExceptionDetector) yes
wait (exponential backoff + jitter, capped at maxRetryDelay)
attempt 2 -> ...
after maxRetryCount -> RetryLimitExceededException (inner = last SqlException)
Defaults: EnableRetryOnFailure() retries 6 times with a 30 s maximum delay. Timeouts are also treated as transient, which is a double-edged sword: retrying a query that timed out because of blocking adds more load.
BEGIN TRAN
INSERT Order ok
UPDATE Stock <- connection drops
The server rolls back the open transaction when the connection dies. EF only knows the last operation failed; replaying just the UPDATE would update stock without an order. So EF refuses unless you pass it a delegate that it can replay from the beginning.
COMMIT sent --> server commits --> ack lost (connection drops)
client sees an exception -> strategy retries -> work applied twice
Options:
ExecuteInTransactionAsync(operation, verifySucceeded): EF calls verifySucceeded after a failure during commit; return true if the work is already in the database, and EF stops retrying.UPDATE ... SET Status = 'Paid' WHERE Id = @id AND Status = 'Pending' is harmless to repeat.If the delegate adds entities and the first attempt fails after SaveChanges started, the change tracker may hold partially accepted state. Clear it (ChangeTracker.Clear()) or create a new context per attempt, and re-read inside the delegate.
Anything outside the database (emails, payment captures, Service Bus messages) must not be in the retried delegate. Write an outbox row in the same transaction and let a background processor deliver it after commit, idempotently.
BeginTransactionAsync directly and read the exception text.DbCommandInterceptor that throws a fake SqlException with number 40613 on the first attempt (or a test helper), and watch the retry.verifySucceeded.CoreEventId.ExecutionStrategyRetrying and build an Application Insights query over it.A checkout that survives transient failures without duplicating orders.
namespace Shop.Checkout;
using Microsoft.EntityFrameworkCore;
public sealed record CheckoutRequest(Guid IdempotencyKey, int CustomerId, IReadOnlyList<CartLine> Lines);
public sealed record CartLine(int ProductId, int Quantity);
public sealed class CheckoutHandler(ShopDbContext db)
{
public async Task<int> HandleAsync(CheckoutRequest req, CancellationToken ct)
{
var strategy = db.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(async () =>
{
db.ChangeTracker.Clear(); // each attempt starts from a clean tracker
// Idempotency: if a previous attempt committed but the ack was lost, return its result.
var existing = await db.Orders.AsNoTracking()
.Where(o => o.IdempotencyKey == req.IdempotencyKey)
.Select(o => (int?)o.Id).SingleOrDefaultAsync(ct);
if (existing is int id) return id;
await using var tx = await db.Database.BeginTransactionAsync(ct);
var order = Order.Create(req.CustomerId, req.IdempotencyKey, req.Lines);
db.Orders.Add(order);
// Outbox row instead of sending the email / capturing payment here.
db.OutboxMessages.Add(OutboxMessage.For(new OrderPlaced(order.Id, req.CustomerId)));
await db.SaveChangesAsync(ct);
foreach (var line in req.Lines)
{
var updated = await db.Products
.Where(p => p.Id == line.ProductId && p.Stock >= line.Quantity)
.ExecuteUpdateAsync(s => s.SetProperty(p => p.Stock, p => p.Stock - line.Quantity), ct);
if (updated == 0) throw new OutOfStockException(line.ProductId); // rolls back the transaction
}
await tx.CommitAsync(ct);
return order.Id;
});
}
}
// Program.cs: retries on, plus a unique index that makes duplicates impossible even if a check races.
builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(
builder.Configuration.GetConnectionString("Shop"),
sql => sql.EnableRetryOnFailure(maxRetryCount: 6, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null)));
// In OnModelCreating:
// b.Entity<Order>().HasIndex(o => o.IdempotencyKey).IsUnique();
// Alternative: let EF verify after a failure during commit.
await strategy.ExecuteInTransactionAsync(
operation: async ct2 => { db.Orders.Add(order); await db.SaveChangesAsync(acceptAllChangesOnSuccess: false, ct2); },
verifySucceeded: ct2 => db.Orders.AsNoTracking().AnyAsync(o => o.IdempotencyKey == key, ct2),
cancellationToken: ct);
db.ChangeTracker.AcceptAllChanges();
EnableRetryOnFailure and leaving explicit transactions as they are. Why it is wrong: EF throws for user-initiated transactions. Instead: wrap the whole unit in CreateExecutionStrategy().ExecuteAsync.verifySucceeded.ChangeTracker.Clear() at the start of each attempt or a new context.Retries are table stakes on Azure SQL; the real design work is making each write path safe to repeat. I treat every command handler as 'may run more than once': it has an idempotency key or a natural idempotent update, no external side effects inside the transaction, and a test that simulates a failure after commit. That discipline pays off again with message-driven consumers, which have the same at-least-once problem.
I also separate genuine transient faults from capacity problems. Every retry is extra work for a database that may already be struggling: during throttling (40501, 10928/10929) a fleet of instances retrying in step can create a retry storm that keeps the database saturated. So I keep backoff exponential with jitter, cap the retry count and total delay below the request timeout, and chart ExecutionStrategyRetrying events next to failed dependencies, CPU/DTU and log-rate metrics. If retries rise outside maintenance windows, that's a capacity or query problem to fix, not a policy to loosen. I also set the database's maintenance window to a low-traffic time in the Australian time zone.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
EnableRetryOnFailure only |
Reads and single SaveChanges |
Latency during retries | Explicit transactions not wrapped |
Strategy ExecuteAsync + idempotency key |
Multi-step writes | Key design, unique index | Never wrong on Azure SQL |
ExecuteInTransactionAsync + verifySucceeded |
Single-context writes with a cheap check | Verification query | Complex multi-resource units |
| Outbox for side effects | Emails, payments, messages | Background processor | Pure database work |
| Retry setting | Effect of raising it | Risk |
|---|---|---|
maxRetryCount |
Survives longer outages | Requests exceed client timeouts; more load during throttling |
maxRetryDelay |
Gentler on a struggling database | Slower recovery, held threads and connections |
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.
Use Microsoft Entra ID authentication with a managed identity. Steps: 1. set a Microsoft Entra admin on the Azure SQL logical server (optionally enable Microsoft Entra-only authentication to turn off SQL logins); 2. turn on a system- or user-assigned managed identity on the App Service, Container App or AKS workload; 3. connected as the Entra admin, create a contained user for it in the database, CREATE USER [my-api] FROM EXTERNAL PROVIDER;, and grant least privilege (db_datareader, db_datawriter, no DDL for the app); 4. use a connection string with Authentication=Active Directory Default (or Active Directory Managed Identity plus User Id=<client id> for a user-assigned identity). Microsoft.Data.SqlClient gets and refreshes tokens itself, so EF Core needs no code change, and locally the same string uses your Azure CLI or Visual Studio sign-in. No secret exists to leak or rotate.
How to tell it (STAR)
**S:** At [company], our [grocery] checkout on Azure SQL failed in bursts during platform maintenance, so we turned on EF Core's retry strategy. **T:** I owned making checkout resilient without breaking anything. **A:** First, every checkout failed because the strategy refuses hand-rolled transactions, so I wrapped the unit in `CreateExecutionStrategy().ExecuteAsync`. Then after a failover we saw [11] duplicate orders: commits had succeeded but the acknowledgement was lost, so the retry ran them again, emails included. I added an idempotency key with a unique index, a check at the start of each attempt, and moved emails and payment capture to an outbox, with a test that simulates a failure after commit. **R:** The next [three] maintenance events caused [zero] failed checkouts and [zero] duplicates, compared with [~200] errors per event before.
Last updated 23 Nov 2026.