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

📚 Interview question

Your API on Azure SQL throws intermittent SqlExceptions such as error 40613 during maintenance events. You turn on EnableRetryOnFailure, and now a checkout endpoint fails with an error saying the execution strategy does not support user-initiated transactions. How do you diagnose and fix it, and how do you keep retried work safe?

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.

Senior Debugging Advanced azure-sql ef-core execution-strategy idempotency resiliency transient-faults

🎯 Key points

  • Azure SQL drops connections during reconfigurations, failovers and throttling (e.g. 40613, 40197, 40501, 49918); clients must retry
  • EnableRetryOnFailure registers SqlServerRetryingExecutionStrategy, which retries only errors its transient detector recognises (plus errorNumbersToAdd): defaults 6 retries, up to 30 s delay, exponential backoff
  • EF can replay a query or a single SaveChanges because each is self-contained; inside a user-initiated BeginTransaction it would only know the failed last step, so it throws InvalidOperationException
  • Fix: wrap the whole unit, transaction included, in Database.CreateExecutionStrategy().ExecuteAsync
  • Retried delegates must be idempotent: a lost COMMIT acknowledgement means the work may already be done
  • ExecuteInTransactionAsync with a verifySucceeded callback, or a unique request id / idempotency key enforced by a unique index
  • Side effects (emails, payments, messages) don't belong inside the retried delegate: use an outbox
  • SqlClient idle connection resiliency (ConnectRetryCount) reconnects idle connections but doesn't replay commands; monitor retry events, failed dependencies and DTU/CPU so retries don't hide capacity problems

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.

EnableRetryOnFailure registers SqlServerRetryingExecutionStrategy. EF Core wraps every query and every SaveChanges in 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 with ExecuteUpdateAsync, 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 ExecuteInTransactionAsync with a verifySucceeded callback 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."


Diagnosis

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

What is safe to retry

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can diagnose transient Azure SQL failures and implement retries without introducing duplicate side effects.

Green flags

  • Identifies 40613 as reconfiguration and correlates with maintenance and health signals.
  • Explains why EF refuses user transactions and how to wrap them.
  • Raises commit-in-doubt and idempotency, with a concrete mechanism.
  • Moves external side effects to an outbox.

Red flags

  • Wraps the call in a generic Polly retry around the whole HTTP handler without idempotency.
  • Disables retries to make the error go away.
  • Thinks transactions guarantee exactly-once behaviour across a lost connection.

📚 Learn in depth

1. Why Azure SQL drops connections

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.

2. How the execution strategy works

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.

3. Why user transactions are refused

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.

4. The commit-in-doubt problem

COMMIT sent --> server commits --> ack lost (connection drops)
client sees an exception -> strategy retries -> work applied twice

Options:

  • Idempotency key: the client sends a key (or the server derives one); a unique index on it makes the second insert fail, or the delegate checks first.
  • 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.
  • Natural idempotency: UPDATE ... SET Status = 'Paid' WHERE Id = @id AND Status = 'Pending' is harmless to repeat.

5. State between attempts

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.

6. Side effects and the outbox

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.

Try it yourself

  1. Enable retries, call BeginTransactionAsync directly and read the exception text.
  2. Simulate transient errors with a DbCommandInterceptor that throws a fake SqlException with number 40613 on the first attempt (or a test helper), and watch the retry.
  3. Make the fake failure happen after commit and observe the duplicate; then add verifySucceeded.
  4. Run a load test and trigger a manual failover on a test Azure SQL failover group; record errors and latency.
  5. Log CoreEventId.ExecutionStrategyRetrying and build an Application Insights query over it.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Turning on 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.
  • Mistake: Starting the transaction outside the delegate. Why it is wrong: the retry reuses a transaction on a dead connection. Instead: begin, work and commit inside the delegate.
  • Mistake: Assuming a retried delegate runs exactly once. Why it is wrong: a lost commit acknowledgement leads to a second run and duplicates. Instead: idempotency keys with a unique index, or verifySucceeded.
  • Mistake: Sending emails, calling payment APIs or publishing messages inside the delegate. Why it is wrong: every retry repeats the side effect. Instead: write an outbox row and deliver after commit.
  • Mistake: Reusing a dirty change tracker between attempts. Why it is wrong: entities from the failed attempt are re-sent or conflict. Instead: ChangeTracker.Clear() at the start of each attempt or a new context.
  • Mistake: Treating every timeout as transient and retrying aggressively. Why it is wrong: timeouts from blocking or slow queries get worse under retry storms. Instead: fix the query or blocking; cap retries; watch for retry spikes.
  • Mistake: Hiding retries entirely. Why it is wrong: rising retry counts are an early warning of tier or platform problems. Instead: log execution strategy retry events and alert on them.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions BeginTransaction or savepoints. Why: Checks transaction fundamentals behind the retry rules.
    How to 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.

  2. When: Candidate mentions duplicates after a retry. Why: Checks handling of a commit whose acknowledgement was lost.
    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.

  3. When: Candidate mentions connection strings or Entra ID authentication. Why: Checks Azure SQL connection setup, which often appears alongside resiliency.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Duplicate orders after enabling retries on Azure SQL
Situation
An [online grocery] API on ASP.NET Core and Azure SQL Business Critical in Australia East, [~8k] orders a day. Planned maintenance caused bursts of 40613 errors and failed checkouts; the team enabled `EnableRetryOnFailure`.
Signals
First, checkout started failing every time with `InvalidOperationException` about user-initiated transactions. After a quick fix wrapping the code in the strategy, finance found [11] duplicate orders and double stock decrements after a failover; customers received two confirmation emails.
Investigation
Correlated the duplicates with Application Insights: each had a failed SQL dependency during COMMIT followed by a successful retry within seconds. Azure Resource Health showed a reconfiguration at that time. Read the code: the email was sent inside the delegate and there was no idempotency key, so a committed-but-unacknowledged attempt was replayed.
Resolution
Immediately: refunded and cancelled duplicates, and moved the email send out of the delegate. Then: added a client-generated idempotency key per checkout with a unique index and a check at the start of the delegate, cleared the change tracker per attempt, moved emails and payment capture to an outbox processor, and logged `ExecutionStrategyRetrying` events.
Prevention
Integration test with a command interceptor that fails after commit once and asserts one order; a design checklist item that every handler is idempotent; alerts on retry spikes; maintenance window set to [early morning AEST].

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.

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me