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

📚 Interview question

Where do you draw transaction boundaries in an ASP.NET Core service using EF Core? Explain one SaveChanges per use case, the DbContext-per-request lifetime, why you never hold a database transaction open across an HTTP call to another service, and how the outbox pattern keeps the database and a message broker consistent.

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.

Senior Architecture Advanced architecture dbcontext-lifetime distributed-systems ef-core outbox transactions

🎯 Key points

  • One use case = one unit of work = usually one SaveChanges, which EF Core already wraps in a transaction
  • DbContext is scoped per request or per message, never singleton and never shared across threads
  • Explicit transactions (BeginTransactionAsync) only when several SaveChanges or ExecuteUpdate calls must commit together; wrap them in the execution strategy when retries are on
  • Never hold a database transaction open across an HTTP call, a message publish or user think-time: locks are held for remote latency and the remote side cannot roll back
  • Dual writes (database + Service Bus) need the transactional outbox: write the message row in the same transaction, relay it afterwards, deliver at least once
  • Consumers must be idempotent (inbox table or natural keys) because outbox delivery is at least once
  • Cross-service consistency is a saga with compensations, not a distributed transaction
  • Keep transactions short: read outside, validate, then write; READ COMMITTED SNAPSHOT on Azure SQL reduces reader/writer blocking

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"I start from the use case. A command handler like PlaceOrder is one unit of work: load the customer and basket, apply the business rules on the aggregate, and call SaveChangesAsync once. EF Core sends all the inserts and updates in one transaction, so either the whole order exists or none of it does. The DbContext is 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 an ExecuteUpdate on stock plus tracked changes on the order, and with EnableRetryOnFailure that whole block goes inside CreateExecutionStrategy().ExecuteAsync so 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 PendingPayment together 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: SaveChanges and then serviceBusSender.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."


Rules of thumb

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-patterns

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can design consistency boundaries for real services rather than reaching for bigger transactions.

Green flags

  • One SaveChanges per use case and a scoped DbContext
  • Explains why remote calls must be outside the transaction
  • Describes the dual-write problem and the outbox, with idempotent consumers
  • Knows the execution strategy requirement with explicit transactions

Red flags

  • TransactionScope across services as the answer
  • Transaction-per-request middleware as the default
  • Publish-then-save or save-then-publish with no outbox

📚 Learn in depth

1. What EF Core does by default

SaveChangesAsync()
  │ 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.

2. Explicit transactions and retries

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

3. Why remote calls must stay outside

BEGIN TRAN ── UPDATE Stock (X lock) ── HTTP to payments (8 s) ── COMMIT
                        ▲ every checkout for this SKU waits here
  • Locks are held for the remote latency, and tail latencies multiply.
  • The remote side has its own state: a database rollback cannot un-send an email or un-charge a card.
  • A timeout leaves you not knowing whether the remote action happened.

The fix is to model the in-between state explicitly (PendingPayment) and make each step a short local transaction.

4. The transactional outbox

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.

5. DbContext lifetime and concurrency

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.

6. Isolation

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.

Try it yourself

  1. Write a handler that calls SaveChanges twice and kill the process between them; observe the partial state. Then make it one save.
  2. Enable EnableRetryOnFailure, open a transaction without the execution strategy, and read the exception.
  3. Hold a transaction open with await Task.Delay(5000) after an update and watch blocking in sys.dm_exec_requests from a second session.
  4. Implement a minimal outbox table and relay, kill the relay after publishing, and confirm the duplicate arrives.
  5. Run two queries in parallel on one context with Task.WhenAll and read the error.

💻 Code

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;

⚠ Common mistakes

  • Mistake: Calling an external API inside a database transaction. Why it is wrong: Locks are held for the remote latency, and a rollback cannot undo the remote side effect. Instead: Persist an intermediate state, call the service outside, record the result in a second short transaction.
  • Mistake: 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.
  • Mistake: Opening 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.
  • Mistake: Transaction-per-request middleware. Why it is wrong: Every request holds a transaction through remote calls and serialisation. Instead: Let each handler own its unit of work.
  • Mistake: Sharing one 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.
  • Mistake: Using 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.
  • Mistake: Non-idempotent consumers. Why it is wrong: The outbox delivers at least once, so duplicates cause double charges. Instead: Inbox table or idempotency keys.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the outbox Why: Checks outbox mechanics, relay and delivery guarantees
    How to answer

    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.

  2. When: Candidate mentions explicit transactions or savepoints Why: Checks EF Core transaction APIs and execution strategy interaction
    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.

  3. When: Candidate says the DbContext is the unit of work Why: Checks Unit of Work and sharing one context per request
    How to answer

    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.

🛠 Real-world problems: how you handle them

Checkout locks piled up behind a slow payment gateway
Situation
[E-commerce checkout service on Azure SQL, ~150 orders per minute at peak during a sale]. The handler opened a transaction, decremented stock, called the payment gateway over HTTP, then committed.
Signals
p95 checkout latency rose from 600 ms to over 8 s; Application Insights showed SQL dependencies waiting on locks while the payment HTTP dependency ran; Azure SQL reported high LCK_M_U waits; customers reported being charged for orders that showed as failed.
Investigation
End-to-end transaction views in Application Insights showed the payment call nested inside an open SQL transaction. Query Store and `sys.dm_os_wait_stats` confirmed lock waits on `Stock` rows for popular SKUs. Logs showed gateway timeouts after the charge succeeded, followed by a database rollback.
Resolution
Immediate: raised the gateway timeout alert, and a reconciliation job matched gateway charges to orders and refunded orphans. Real fix: split checkout into a short transaction saving the order as `PendingPayment` plus an outbox message, a payment consumer outside any transaction using an idempotency key with the gateway, and a second short transaction recording the result.
Prevention
An Application Insights alert on SQL transactions open during an outgoing HTTP dependency, an architecture rule in the ADR ("no remote calls inside transactions"), and integration tests that kill the process between steps.

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

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me