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

📚 Interview question

Why do cloud systems avoid distributed transactions and two-phase commit? Explain how 2PC works, where it breaks (blocking, in-doubt transactions, availability, locks across the network), what .NET 10 and Azure still support, and what you use instead to keep data consistent across services.

Two-phase commit and distributed transactions: the prepare and commit protocol, its blocking and availability failure modes, current .NET and Azure support (MSDTC on Windows only, elastic transactions, no broker enlistment), and the replacements: one transaction by design, outbox with idempotent consumers, sagas, reservations and reconciliation.

Mid-Level Theory Intermediate data-consistency distributed-systems distributed-transactions outbox saga two-phase-commit

🎯 Key points

  • 2PC: coordinator sends prepare, every participant votes and holds locks, then coordinator sends commit or abort
  • Blocking: if the coordinator dies after prepare, participants stay in-doubt holding locks until it recovers
  • Availability multiplies: the transaction needs every participant up, so 3 × 99.9% is about 99.7%
  • Most cloud resources can't enlist: Service Bus, Kafka, Cosmos DB and HTTP APIs have no XA/DTC support
  • .NET 7+ supports MSDTC only on Windows (TransactionManager.ImplicitDistributedTransactions); Linux containers can't use it
  • Replacement 1: redraw boundaries so the invariant lives in one database transaction
  • Replacement 2: transactional outbox plus idempotent consumers gives at-least-once, eventually consistent propagation
  • Replacement 3: sagas with compensations or reservations, backed by reconciliation reports

⏱ 30-second answer

Two-phase commit (2PC) makes several resources commit atomically: a coordinator asks every participant to prepare (write, lock and vote yes), then tells all of them to commit. It is correct, but it is a blocking protocol: if the coordinator fails after prepare, participants sit in-doubt holding locks. It also needs every participant available, holds locks across network round trips, and most cloud resources (Service Bus, Kafka, Cosmos DB, third-party HTTP APIs) cannot enlist at all. In .NET 10, MSDTC-backed distributed transactions work only on Windows.

So instead we:

  • keep each invariant inside one service and one local transaction,
  • propagate changes with the transactional outbox and idempotent consumers,
  • coordinate longer flows with sagas and compensations.

The trade-off: you give up immediate atomicity across services and accept eventual consistency, which you must design and monitor for.

🗣 Full answer (senior)

How I would answer this in an interview

"Two-phase commit is the classic way to get one atomic commit across several resources. A coordinator sends prepare to every participant; each one writes its changes durably, takes its locks and votes yes or no. If everyone votes yes, the coordinator writes its decision and sends commit; otherwise abort. It's correct on paper, but it is a blocking protocol. Between voting yes and hearing the decision, a participant can't decide alone, so if the coordinator crashes the participant sits in-doubt with its locks held until someone recovers the coordinator or a DBA resolves it by hand.

In the cloud that cost gets worse. Every participant must be up for the transaction to succeed, so availability multiplies down. Locks are held across network round trips, which kills throughput under contention. And most of what we actually use can't take part: Azure Service Bus, Kafka, Cosmos DB and a payment provider's REST API don't speak XA or MSDTC. In .NET, System.Transactions can only escalate to MSDTC on Windows, from .NET 7 onwards, and only if you opt in with TransactionManager.ImplicitDistributedTransactions. Our services run in Linux containers, so that door is closed anyway.

What replaces it is design, not a different protocol. First I ask whether the invariant really spans services; often the boundary is wrong and the data belongs in one database, where a local transaction is cheap. If it does span services, I write the state change and an outbox row in one local transaction, publish at-least-once, and make consumers idempotent. For multi-step business flows I use a saga with compensating actions, and I run a reconciliation job that proves the services agree. The mistake I see is people reaching for TransactionScope around a database call and a message send and assuming it is atomic, when the broker was never enlisted. Distributed atomicity isn't free; you either pay for it in locks and availability, or you design for eventual consistency and monitor it."


How 2PC works and where it fails

Coordinator            Orders DB            Payments DB
    |---- prepare ------->|                      |
    |---- prepare ---------------------------->|
    |<--- yes (locks held)|                      |
    |<--- yes (locks held) ----------------------|
    |  [writes COMMIT decision to its log]       |
    X  coordinator crashes here                  |
                          |  in-doubt: can't commit or abort alone
                          |  rows stay locked until coordinator recovers
Failure mode What happens Impact
Coordinator crash after prepare Participants are in-doubt Locks held for minutes or hours; blocked readers and writers
Participant slow Everyone waits for the slowest vote Tail latency of the whole transaction = worst participant
Any participant down Transaction can't commit Availability = product of all participants
Network partition Votes or decision lost Timeouts, aborts, or in-doubt state
Resource can't enlist Not part of the transaction at all False sense of atomicity

What .NET 10 and Azure support today

Option Status Notes
TransactionScope across two SQL connections, MSDTC .NET 7+ on Windows only, opt-in Throws on Linux; not available in most container estates
Azure SQL Database elastic transactions Supported between Azure SQL databases Only SQL participants; adds coordination latency
Azure SQL Managed Instance distributed transactions Supported via server trust groups Only MI and SQL Server participants
Azure Service Bus transactions Local to one namespace (including send-via) Cannot enlist in DTC or with a database
Kafka transactions Atomic writes across Kafka partitions Not with your database
Cosmos DB transactional batch One logical partition key Not across containers or services

What replaces it

Approach Consistency When to use When not
One service, one local transaction Immediate The invariant (e.g. "balance never negative") lives in one aggregate When it forces unrelated teams into one database
Outbox + idempotent consumers Eventual, at-least-once A change must be announced reliably to others When the user must see all effects immediately
Saga (orchestrated or choreographed) Eventual, with compensations Multi-step business flows (order, pay, ship) Simple one-hop notifications
Reservation (try, confirm, cancel) Eventual, bounded Scarce resources: stock, seats, credit When holds can't expire safely
Reconciliation job Detects drift Always, as the safety net Never skip it for money

Production example

A team I'd describe in an interview had a TransactionScope wrapping an EF Core save and a Service Bus send; about 0.3% of orders had a message but no row after transient SQL failures. Replacing it with an outbox row in the same EF Core transaction and an idempotent consumer brought mismatches to zero over [three months], and a nightly reconciliation query confirmed it. Publish latency rose from about 20 ms to a p95 of 400 ms, which the business accepted.

🔍 What the interviewer is checking

Checks whether the candidate understands why 2PC is impractical in cloud systems and can name concrete, production-ready replacements with their consistency trade-offs.

Green flags

  • Explains prepare and commit, and why a YES vote makes the participant block
  • Knows brokers and HTTP APIs can't enlist, and that MSDTC in .NET is Windows-only
  • Starts with "can this live in one transaction?" before reaching for patterns
  • Pairs the outbox with idempotent consumers and mentions reconciliation

Red flags

  • Believes TransactionScope makes a database write and a message send atomic
  • Says "just use eventual consistency" with no plan for drift or user experience
  • Treats compensations as rollbacks

📚 Learn in depth

1. The protocol from first principles

Atomic commitment means all participants commit or all abort. With one database, the write-ahead log gives you this: a single commit record makes the transaction durable. With several resources there is no single log, so 2PC adds a coordinator with its own log.

Phase 1 (voting)                 Phase 2 (decision)
C -> P1, P2: PREPARE              C logs COMMIT (or ABORT)
P1, P2: force-write, lock, vote   C -> P1, P2: COMMIT
P1, P2 -> C: YES                  P1, P2: apply, release locks, ACK

The key property: once a participant votes YES it has given up the right to decide alone. That is what makes 2PC blocking. Three-phase commit tries to remove the block but assumes bounded network delays, which real networks don't give you, so it is rarely used. Consensus-based commit (Paxos Commit, or databases built on Raft such as Spanner and CockroachDB) replicates the coordinator so it can't be a single point of failure, but that lives inside one database product, not across your services.

2. How .NET implements it

System.Transactions starts a lightweight transaction for one durable resource. When a second durable resource (a second SqlConnection with a different connection string, or a second open connection on older SQL Server versions) enlists, the transaction escalates to a distributed transaction managed by MSDTC.

TransactionScope
   |-- SqlConnection A (enlists, lightweight)
   |-- SqlConnection B (second durable resource) -> escalate to MSDTC
                                                   (Windows only, .NET 7+, opt-in)

On .NET Core 1.0 to 6 escalation threw PlatformNotSupportedException everywhere. .NET 7 added Windows support behind TransactionManager.ImplicitDistributedTransactions = true. Linux and macOS still throw. EF Core itself only manages local transactions (Database.BeginTransactionAsync) and can share one DbTransaction across contexts on the same connection, which is a local transaction, not 2PC.

3. Why the cloud makes it worse

  • Availability: a transaction across three services each at 99.9% succeeds at most 99.7% of the time, before contention.
  • Latency and locks: locks are held for at least two network round trips plus the slowest participant's fsync. Under contention this shows up as blocking chains in sys.dm_exec_requests.
  • Enlistment: brokers and SaaS APIs don't implement XA. An HTTP call can't be rolled back; at best it can be compensated.
  • Operational burden: in-doubt transactions need manual resolution, which nobody on call wants at 3 am.

4. What you build instead

Orders service                     Broker               Payments service
BEGIN TRAN
  INSERT Order
  INSERT OutboxMessage
COMMIT  --- relay polls --->  OrderPlaced  --->  Inbox check (message id)
                                                  BEGIN TRAN
                                                    INSERT InboxMessage
                                                    INSERT Payment
                                                  COMMIT

Each arrow can fail and be retried, so delivery is at-least-once and the consumer deduplicates. The system is consistent once the messages are processed, and a reconciliation query proves it. For flows that need undo, a saga records state and issues compensations (refund, release stock).

5. Reservations (try, confirm, cancel)

For scarce resources, a reservation gives you most of the safety of 2PC without the locks: Try reserves with an expiry, Confirm makes it permanent, Cancel or expiry releases it. A seat held for 10 minutes is a lock with a timeout, owned by the business, not the database.

Try it yourself

  1. In a Linux container, open two SqlConnections with different databases inside a TransactionScope and observe the PlatformNotSupportedException.
  2. On Windows, set TransactionManager.ImplicitDistributedTransactions = true, repeat, and watch the transaction in Component Services. Kill the process between the two writes and inspect locks with sys.dm_tran_locks.
  3. Wrap an EF Core save and a ServiceBusSender.SendMessageAsync in a TransactionScope, throw after the send, and confirm the message was still sent.
  4. Rebuild the same flow with an outbox table and a relay BackgroundService; inject failures and confirm no lost or orphaned messages.
  5. Write a reconciliation query that compares orders with payments by order id and reports drift.

💻 Code

The mistake (a scope that looks atomic but isn't) and the replacement (one local transaction with an outbox row).

// Before: TransactionScope does NOT enlist Service Bus. If SaveChanges fails after the send,
// the message is already out; on Linux a second SQL database would throw instead of escalating.
namespace Orders.Before;

using System.Transactions;
using Azure.Messaging.ServiceBus;

public sealed class PlaceOrderHandler(OrdersDb db, ServiceBusSender sender)
{
    public async Task HandleAsync(Order order, CancellationToken ct)
    {
        using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
        db.Orders.Add(order);
        await sender.SendMessageAsync(new ServiceBusMessage(order.Id.ToString()), ct); // not enlisted
        await db.SaveChangesAsync(ct);                                                 // may fail
        scope.Complete();
    }
}
// After: the state change and the event are written in ONE local SQL transaction.
// A relay publishes OutboxMessages at-least-once; consumers deduplicate by MessageId.
namespace Orders.After;

using System.Text.Json;
using Microsoft.EntityFrameworkCore;

public sealed record OrderPlaced(Guid OrderId, decimal Total);

public sealed class OutboxMessage
{
    public Guid MessageId { get; init; } = Guid.CreateVersion7();
    public required string Type { get; init; }
    public required string Payload { get; init; }
    public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;
    public DateTimeOffset? PublishedAt { get; set; }
}

public sealed class PlaceOrderHandler(OrdersDb db)
{
    public async Task HandleAsync(Order order, CancellationToken ct)
    {
        db.Orders.Add(order);
        db.Outbox.Add(new OutboxMessage
        {
            Type = nameof(OrderPlaced),
            Payload = JsonSerializer.Serialize(new OrderPlaced(order.Id, order.Total))
        });
        await db.SaveChangesAsync(ct); // one implicit local transaction: both rows or neither
    }
}

public sealed class Order
{
    public Guid Id { get; init; } = Guid.CreateVersion7();
    public decimal Total { get; init; }
}

public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<OutboxMessage> Outbox => Set<OutboxMessage>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<OutboxMessage>().HasKey(m => m.MessageId);
}

⚠ Common mistakes

  • Mistake: Wrapping a database save and a broker send in TransactionScope and calling it atomic. Why it is wrong: Service Bus and Kafka don't enlist, so the send happens whatever the database does. Instead: Write an outbox row in the same local transaction and publish it afterwards.
  • Mistake: Turning on ImplicitDistributedTransactions to fix a cross-database bug. Why it is wrong: It only works on Windows, adds MSDTC as an operational dependency and holds locks across the network. Instead: Redraw the boundary or use an outbox between the two databases.
  • Mistake: Treating a saga compensation as a rollback. Why it is wrong: Other services and users may already have seen the intermediate state; a refund is a new business action. Instead: Design compensations as visible, auditable business steps.
  • Mistake: Splitting data into separate services when one invariant needs both. Why it is wrong: You've created a distributed transaction problem the business didn't need. Instead: Keep data that must change atomically in one aggregate and one database.
  • Mistake: Assuming eventual consistency means "consistent soon, by itself". Why it is wrong: Bugs, poison messages and lost events leave permanent drift. Instead: Run reconciliation jobs and alert on mismatches and outbox age.
  • Mistake: Making consumers non-idempotent because "the outbox guarantees delivery". Why it is wrong: The outbox gives at-least-once; a relay crash after publish but before marking sends the message again. Instead: Deduplicate by message id in an inbox table or make the change naturally idempotent.
  • Mistake: Using Database.BeginTransaction across two DbContexts on different connection strings. Why it is wrong: Each context gets its own local transaction; there is no atomicity between them. Instead: Share one connection and transaction only for the same database, or use an outbox.

🏛 Senior insight: trade-offs

The senior move is to treat "we need a distributed transaction" as a smell about boundaries. Most real invariants (a balance can't go negative, stock can't be oversold) belong to one aggregate. If two services must change atomically every time, they are probably one service. Where flows genuinely span services, I make the business own the consistency model: what the user sees while the flow is in progress, how long "pending" can last, and who gets paged when it doesn't converge.

To test a boundary I use three questions. Which invariants must hold at every instant? (those stay inside one aggregate and one transaction). Which data changes together, and how often? (a change-coupling list from the backlog or git history shows services that always deploy together). Can the business tolerate a pending state, and for how long? (if "payment pending for 30 seconds" is fine, eventual consistency is fine). An event-storming session with domain experts usually answers all three, and I record the outcome in an ADR. If the answers say two services always change together and can't tolerate pending, I merge them rather than add 2PC.

I also measure consistency rather than hoping for it: outbox age (oldest unpublished row), consumer lag, dead-letter counts, and a reconciliation query with a mismatch count that should be zero. Those four numbers on a dashboard tell you whether eventual consistency is actually happening.

Option When it fits Cost When not to
Local transaction Invariant in one aggregate or one database Coupling of that data to one service Data owned by different teams with different lifecycles
2PC (MSDTC, elastic transactions) Legacy Windows estate, SQL-only participants, low volume Locks across network, in-doubt recovery, Windows dependency Containers on Linux, brokers, SaaS APIs
Outbox + idempotent consumer Reliable announcement of a change Relay process, outbox table growth, seconds of lag When callers need the remote effect synchronously
Saga Multi-step flows with compensations State storage, timeouts, compensation design Two-step flows a single service can own
Signal Healthy Investigate
Oldest unpublished outbox row < 5 s > 60 s
Reconciliation mismatches 0 Any, for money
Dead-letter queue count 0 or flat Rising

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the outbox or the dual-write problem Why: Checks the mechanics of the outbox that replaces the dual write
    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 sagas or compensating actions Why: Checks saga design, compensations and timeouts
    How to answer

    A saga replaces a distributed transaction with a sequence of local transactions, one per service, coordinated by messages. Each step has a compensating action that semantically undoes it: release the stock, refund the payment. Compensation isn't a rollback, because other parties may already have seen or acted on the intermediate state.

    • Choreography: services react to each other's events. It's simple for two or three steps, but the flow is implicit.
    • Orchestration: a state machine (such as a MassTransit saga) sends commands, persists its state per correlation id, and handles failures. The flow is explicit and observable.

    Design points: put the irreversible step last, make every step idempotent, add scheduled timeouts, and handle late replies (payment succeeds after a timeout cancelled the order, so refund it). The trade-off is availability and autonomy against eventual consistency and more complex failure handling.

  3. When: Candidate says the system becomes eventually consistent Why: Checks what eventual consistency means to readers and how to choose a model
    How to answer

    A consistency model is the contract that says which values a read may return when data is replicated. At one end, strong (linearisable) consistency makes every read see the latest committed write, as if there were one copy. At the other, eventual consistency only promises replicas converge once writes stop. In between are the session guarantees: read-your-writes (you see your own updates), monotonic reads (you never go back in time) and consistent prefix (you never see writes out of order). Cosmos DB exposes this as five levels: Strong, Bounded Staleness, Session (the default), Consistent Prefix and Eventual; stronger levels cost more latency and request units, and Strong can't be used with multi-region writes. I choose per feature: what does a stale or out-of-order read cost here? The trade-off is freshness against latency, cost and availability.

🛠 Real-world problems: how you handle them

Orders with no payment after a TransactionScope 'fix'
Situation
An order and payment platform on [Azure App Service, Australia East] handling [8,000 orders a day]. A developer wrapped the Orders SQL save and a Service Bus send in TransactionScope to stop lost events.
Signals
Finance's daily report showed [about 25] payments a day for orders that didn't exist in Orders, and support tickets about charges for failed checkouts. No exceptions in Payments; SQL deadlock and timeout errors in Orders logs at the same times.
Investigation
Correlated the orphaned payment message ids with Orders logs in Application Insights by operation_Id: each one had a SQL timeout after SendMessageAsync had already returned. Confirmed in a test that ServiceBusSender doesn't enlist in System.Transactions. Checked the deployment: Linux containers, so MSDTC escalation was never an option.
Resolution
Immediate: Payments started checking Orders for the order before charging and refunded the [orphaned] charges. Real fix: an outbox table written in the same EF Core SaveChanges, a relay BackgroundService publishing with the outbox MessageId as the Service Bus MessageId, duplicate detection on the queue, and an inbox table in Payments.
Prevention
An analyser rule and review checklist banning TransactionScope around broker or HTTP calls, an outbox-age alert at 60 s, a nightly reconciliation query between orders and payments with an alert on any mismatch, and an ADR recording why 2PC isn't used.

How to tell it (STAR)

**S:** At [company], finance found [around 25] payments a day for orders that didn't exist. **T:** I was asked to find the cause and make it impossible. **A:** I traced the orphaned message ids in Application Insights and saw each one had a SQL timeout after the Service Bus send had already succeeded. Someone had added TransactionScope believing it covered the broker; it didn't, and our Linux containers couldn't escalate to MSDTC anyway. I replaced it with an outbox row written in the same SaveChanges, a relay that publishes at-least-once, and an inbox in Payments, then added a nightly reconciliation. **R:** Orphaned payments went from [25 a day] to zero over [three months], and the reconciliation report has stayed at zero mismatches.

↩ Usually asked after

More in Data Consistency

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me