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.
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:
The trade-off: you give up immediate atomicity across services and accept eventual consistency, which you must design and monitor for.
"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.Transactionscan only escalate to MSDTC on Windows, from .NET 7 onwards, and only if you opt in withTransactionManager.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
TransactionScopearound 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."
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 |
| 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 |
| 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 |
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.
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
Red flags
TransactionScope makes a database write and a message send atomicAtomic 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.
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.
sys.dm_exec_requests.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).
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.
SqlConnections with different databases inside a TransactionScope and observe the PlatformNotSupportedException.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.ServiceBusSender.SendMessageAsync in a TransactionScope, throw after the send, and confirm the message was still sent.BackgroundService; inject failures and confirm no lost or orphaned messages.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);
}
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.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.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.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 |
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.