Skip to content

Distributed Transactions: 2PC, Sagas and Outbox

Advanced 40 min read Part 6 of 18

Keeping data consistent across services and shards: two-phase commit and its blocking problem, 3PC, sagas with compensations, TCC and the transactional outbox.

Summary#

A distributed transaction changes data in several databases or services as one unit. Inside one database, ACID makes this easy; across machines, any participant can fail or become unreachable mid-way. Two-phase commit (2PC) gives atomicity with a coordinator that asks everyone to prepare, then tells them to commit, but participants block if the coordinator dies at the wrong moment. Three-phase commit tries to avoid blocking but fails under network partitions. Most microservice systems use sagas instead: a sequence of local transactions, each with a compensating action to undo it, coordinated by choreography (events) or orchestration (a central workflow). TCC (try-confirm-cancel) reserves resources first. The transactional outbox makes "update the database and publish an event" reliable. Prefer designs that avoid cross-service transactions altogether.

Why It Exists#

Booking a trip touches a flight service, a hotel service and a payment service, each with its own database. Either all three succeed or the customer must not be charged for a half-booked trip. In one database you would wrap it in BEGIN ... COMMIT. Across services there is no shared log or lock manager, networks drop messages, and any service may crash between steps. The same problem appears inside one sharded database when a transaction spans shards, and whenever code writes to a database and a message broker. This page builds on Replication and ACID and Isolation Levels.

How It Works#

Why cross-service transactions are hard#

  • Partial failure: one participant commits, another crashes; nothing rolls both back automatically.
  • Uncertainty: a timeout does not tell you whether the other side committed. Retries need idempotency.
  • No global locks: holding locks across services for the duration of network calls kills throughput and availability.
  • Heterogeneous systems: a payment provider's API does not join your database's transaction.
  • Availability coupling: an atomic protocol needs every participant up; the more services, the lower combined availability.

Why it is hard, in depth#

The two generals. Two armies on opposite hills must attack at the same time to win, and they can communicate only by messengers who may be captured. General A sends "attack at dawn". A cannot know it arrived, so B sends an acknowledgement. B cannot know the acknowledgement arrived, so A acknowledges that, and so on forever. No finite exchange over an unreliable channel gives both sides certainty. Jim Gray used this "two generals paradox" in his 1978 "Notes on Data Base Operating Systems", the same notes that described two-phase commit. The lesson is that distributed commit cannot be made certain by more messages alone. Every practical protocol relies on durable logs, retries and, at some point, waiting.

FLP and its practical meaning. Fischer, Lynch and Paterson ("Impossibility of Distributed Consensus with One Faulty Process", JACM 1985) proved that in a fully asynchronous system, where messages can be delayed without bound, no deterministic protocol can guarantee that the nodes always reach agreement if even one node may crash. Real systems escape FLP by assuming timeouts eventually work, which is partial synchrony, so they stay safe always and make progress whenever the network behaves. Atomic commit is even stricter than consensus, because every participant has a veto: one "no" vote must abort everyone. That is why commit protocols block or time out rather than guess.

Availability multiplies. An atomic operation across k services succeeds only if all k are up. With five services each at 99.9% availability, the combined operation is at most 0.999^5 ≈ 99.5%, about 44 hours of failure a year instead of under 9. Latency stacks the same way: the transaction is as slow as its slowest participant on every round trip. A design that needs every service online at the same moment to make progress loses one of the main benefits of splitting into services.

Uncertainty is the real enemy. The hardest failure is not "service B said no", which is easy to undo. It is "the call to B timed out". B may have committed, may have rolled back, or may still be working. Retrying might double-charge a card, and giving up might leave stock reserved forever. Every technique on this page is a way to turn that uncertainty into something manageable: durable decisions (2PC's log), idempotent retries (sagas) or explicit holds with timeouts (TCC).

Isolation disappears at the boundary. Inside one database, other transactions never see your half-finished work. Across services, every intermediate state is visible to anyone who reads it. Between "payment taken" and "order confirmed", a support agent, a report or another saga may act on inconsistent data. Designs must make those states explicit, for example as a PENDING status, rather than pretending they do not exist.

The best distributed transaction is none. Before choosing a protocol, ask whether the data that must change atomically can live together. A dating app shows the trick well. When user A swipes right on B, the system must atomically record the swipe and check whether B already swiped right on A, to detect a match. With 20 million daily users making 100 swipes a day, that is about 2 billion swipes a day, far beyond one partition. A naive layout puts A's swipes in A's partition and B's in B's partition, so the check spans partitions, and Cassandra's lightweight transactions (Paxos-based compare-and-set) work only within one partition. The fix is to key swipes by the pair: the partition key is the two user IDs sorted, such as "1234:5678", so A's swipe on B and B's swipe on A land in the same partition. Recording the swipe and checking for a reciprocal one is then a single-partition operation that the database can make atomic. The remaining costs are operational: partitions for very active pairs grow over time, and the system needs cleanup or archiving of old swipes. The general rule from sharding applies: choose keys so that data which must change together lives on one shard, and most cross-shard transactions disappear. See Partitioning and Sharding.

Two-phase commit (2PC)#

A coordinator (transaction manager) drives the participants:

  1. Phase 1, prepare: the coordinator asks each participant to prepare. Each one does the work, writes it durably to its log, holds its locks, and votes yes (promising it can commit no matter what) or no.
  2. Phase 2, commit or abort: if all voted yes, the coordinator logs the decision and sends commit; otherwise abort. Participants apply it and release locks.

The blocking problem. Once a participant votes yes, it may no longer decide alone; it must wait for the coordinator. If the coordinator crashes after collecting votes but before sending the decision, prepared participants are in doubt: they cannot commit (another may have voted no) or abort (the coordinator may have decided commit). They hold their locks until the coordinator recovers, which can block other transactions for minutes. Other costs: at least two round trips plus forced log writes per participant, and every participant must be available.

2PC is implemented by the XA standard (supported by many relational databases and Java transaction managers), Postgres PREPARE TRANSACTION, and internally by distributed databases. Modern systems such as Spanner and CockroachDB make the coordinator itself fault-tolerant by replicating its state with consensus (Paxos or Raft), which removes the single point of blocking. 2PC across your own microservices over HTTP is rarely used.

Two-phase commit in depth#

Participant states. Each participant moves through a small state machine, and the rules about which transitions it may make on its own are what make 2PC correct:

Before voting, a participant may abort unilaterally, for instance on a timeout, a constraint violation or a deadlock. After voting yes, it is in the prepared (in-doubt) state. It has promised to commit if asked, so it must keep its locks and its prepared data across crashes. Only the coordinator's decision can move it on. The coordinator in turn must force its decision record to disk before sending it, so that after a crash it can tell participants what was decided.

Recovery. When a participant restarts, it scans its log. Transactions with no prepare record are aborted. Committed and aborted ones are finished. Prepared ones are in doubt, so it asks the coordinator. If the coordinator is down, participants can try a cooperative termination: ask the other participants. If any of them has committed or aborted, or never voted, the outcome is known or can safely be abort. But if every reachable participant is prepared, nobody knows the decision, and they must wait. That residual case is the blocking problem, and no amount of cleverness among the participants removes it while the coordinator's log is unreachable.

Cost, in round trips and fsyncs. For n participants, 2PC needs two message round trips, n forced log writes for prepare records, one forced write for the coordinator's decision, and n commit records, which can be lazy. With participants in one availability zone, at about 0.5 ms per round trip and 1-2 ms per fsync on good SSDs, a 2PC commit adds roughly 3-6 ms. Across regions at 70 ms round trip it adds 150 ms or more, and locks are held that whole time, so throughput on contended rows collapses. Classic optimisations reduce the cost. Presumed abort (from the R* distributed database work by Mohan, Lindsay and Obermarck, ACM TODS 1986) lets the coordinator skip logging aborts, because a missing record means abort. Read-only participants vote "read-only" and drop out of phase two. Running the coordinator on one of the participants saves a hop.

2PC in practice.

  • PostgreSQL exposes PREPARE TRANSACTION 'tx77' and COMMIT PREPARED 'tx77' for an external coordinator. It is disabled by default (max_prepared_transactions = 0) for good reason. A forgotten prepared transaction survives restarts, holds its locks, and stops vacuum from removing old row versions, so the database bloats until someone commits or rolls it back. Monitor pg_prepared_xacts.
  • MySQL supports XA START, XA END, XA PREPARE and XA COMMIT. Java EE and Spring transaction managers (Narayana, Atomikos) drive XA across databases and JMS brokers.
  • Heuristic outcomes: XA lets an operator or resource force a commit or rollback of an in-doubt transaction to release locks. If it guesses differently from the coordinator, the result is a "heuristic mixed" outcome that someone must repair by hand. This is why DBAs dread XA in production.
  • Kafka transactions use a 2PC-style protocol. A transaction coordinator broker records the transaction's state in an internal log, and commit or abort markers are written to every partition involved, so consumers in read_committed mode see all of a transaction's messages or none.

When 2PC is the right tool. Inside a distributed database (Spanner, CockroachDB, YugabyteDB, Vitess with its atomic distributed transactions mode), where the coordinator and participants are replicated and close together, 2PC is routine and invisible. Across a few resources you control in one data centre at low volume, XA can be acceptable. Across independently deployed services owned by different teams, especially over HTTP, it couples their availability and lock lifetimes too tightly. Use sagas or TCC there.

Three-phase commit (briefly)#

3PC adds a pre-commit phase between voting and committing, so participants learn the outcome is "commit" before anyone actually commits. If the coordinator fails, participants can time out and decide among themselves. It avoids blocking only if the network is synchronous (bounded delays) and nodes fail by crashing. Under a network partition, two sides can decide differently, so it is not used in practice. Consensus-based commit is the real fix.

Non-blocking commit in depth#

Three-phase commit, step by step. Dale Skeen's "Nonblocking Commit Protocols" (SIGMOD 1981) added a third phase to remove the in-doubt window:

  1. Can-commit: the coordinator asks for votes, as in 2PC phase 1.
  2. Pre-commit: if all voted yes, the coordinator sends "pre-commit" and waits for acknowledgements. Now every participant knows that everyone voted yes.
  3. Do-commit: the coordinator sends "commit".

The key rule is that no participant can be in a state where some participant may have committed while it has not even reached pre-commit. If the coordinator dies, the survivors elect a new coordinator and inspect states. If anyone is pre-committed, it is safe to commit. If nobody is, it is safe to abort. Under crash failures with bounded message delays, this never blocks.

Why it fails in real networks. The argument relies on timeouts meaning a node has crashed. In a real network, timeouts also fire when a node is merely partitioned. Suppose the participants split into two groups. One group contains a pre-committed node and decides to commit. The other group has no pre-committed node and decides to abort. Both groups follow the protocol correctly, and the transaction is now half committed. 3PC also costs an extra round trip. For both reasons it is essentially unused in production. It is still worth knowing as the classic illustration that blocking can be traded only for a dependence on synchrony.

The real fix: replicate the coordinator. The blocking problem exists because one coordinator's log holds the decision. Make that log itself highly available with consensus, and the "coordinator is down" case becomes "a majority of the coordinator's replicas is down", which consensus systems are designed to survive. Jim Gray and Leslie Lamport formalised this in "Consensus on Transaction Commit" (ACM TODS, 2006). Paxos Commit runs a Paxos instance for each participant's vote, so with 2F + 1 acceptors the protocol tolerates F failures without blocking. When F = 0 it reduces exactly to 2PC.

How Spanner does it. In Google Spanner (Corbett et al., OSDI 2012), every shard is a Paxos group with a leader. A transaction touching several groups picks one group's leader as coordinator. Prepare and commit records are written through Paxos in each group, so they survive the failure of any minority of replicas. Spanner adds TrueTime, a clock API that returns an interval guaranteed to contain the true time. The coordinator assigns a commit timestamp and then waits until that timestamp is certainly in the past (commit wait, typically a few milliseconds) before making the result visible. This gives externally consistent (strictly serializable) transactions across the globe, at the cost of cross-group round trips and commit wait on every multi-shard write. CockroachDB and YugabyteDB use the same "2PC over Raft groups" structure with hybrid logical clocks instead of TrueTime, and CockroachDB's parallel commits cut the common case to one round of consensus.

What this means for you. If you need true multi-shard ACID transactions, use a database that implements consensus-replicated 2PC, and design keys so most transactions still touch one shard. Do not build your own commit protocol across services. The engineering effort that went into Spanner's commit path is a good measure of how hard it is.

Sagas#

A saga splits a business transaction into a sequence of local transactions, each committed in one service's database. If step k fails, the saga runs compensating actions for steps k-1 back to 1, semantic "undos" such as refunding a payment or releasing a reservation.

  • Compensations are business operations, not rollbacks: a sent email cannot be unsent, so you send a correction.
  • Steps and compensations must be idempotent and retryable, because messages are delivered at least once.
  • Sagas give ACD without I (no isolation): other requests can see the intermediate state ("seat held, not yet paid"). Countermeasures: semantic locks (status PENDING), ordering steps so the riskiest or most likely to fail comes first, and making the final step a pivot after which only retries (not compensations) are needed.

Choreography vs orchestration

ChoreographyOrchestration
HowEach service reacts to events and emits its own ("OrderCreated" leads Payment to charge, then "PaymentCompleted"...)A central orchestrator sends commands to each service and tracks state
CouplingLoose; no central componentServices coupled to the orchestrator's API
VisibilityFlow is implicit, spread across services; hard to traceFlow is explicit in one place
Good for2-4 simple stepsMany steps, branching, timeouts, compensations
ToolsKafka, SNS/SQS, event busesTemporal, AWS Step Functions, Camunda, Netflix Conductor

An orchestrated saga with compensations (trip booking):

saga BookTrip(trip):
  flight = call Flight.reserve(trip)            # compensation: Flight.cancel(flight)
  try:
    hotel = call Hotel.reserve(trip)            # compensation: Hotel.cancel(hotel)
  except Failed: Flight.cancel(flight); return FAILED
  try:
    call Payment.charge(trip, idem_key=trip.id) # pivot step
  except Declined:
    Hotel.cancel(hotel); Flight.cancel(flight); return FAILED
  retry_until_success(Flight.confirm(flight), Hotel.confirm(hotel))
  return BOOKED

A workflow engine persists the orchestrator's state after every step, so a crash resumes the saga instead of losing it. See Temporal and Workflow Engines and Pattern: Multi-Step Processes.

Sagas in depth#

Origin. Hector Garcia-Molina and Kenneth Salem introduced sagas in a 1987 SIGMOD paper, "Sagas", to deal with long-lived transactions inside one database. A transaction that runs for hours would hold locks for hours. They proposed splitting it into a sequence of short transactions T1 ... Tn, each with a compensating transaction C1 ... Cn, and guaranteeing that either all of T1 ... Tn run, or T1 ... Tk run followed by Ck ... C1. Microservices rediscovered the idea because a cross-service process has exactly the same problem: it cannot hold locks across services for its whole duration.

Three kinds of steps. Designing a saga becomes much easier once each step is classified:

  • Compensatable steps can be undone semantically: reserve stock (release it), create an order in PENDING (mark it CANCELLED), place a card authorisation (void it).
  • The pivot is the point of no return, typically the step that is hardest to undo or that has external effects: capturing payment, or sending the order to a third-party warehouse. If the pivot succeeds, the saga will complete. If it fails, the saga compensates.
  • Retryable steps come after the pivot. They must eventually succeed, so they are retried until they do: send the confirmation email, update the loyalty points, create the shipment label.

Ordering steps as compensatable, then pivot, then retryable means compensation is only ever needed before the pivot, where every step can be undone. Put the step most likely to fail (payment authorisation, scarce inventory) as early as possible, so failures cause little compensation work.

Isolation anomalies and countermeasures. Because every local commit is visible immediately, sagas suffer the anomalies isolation normally prevents. One saga can overwrite another's change (lost update). A reader can see data that a saga will later compensate away (dirty read). Two reads within one saga can see different values (fuzzy read). The standard countermeasures are:

  • Semantic lock: mark records touched by an unfinished saga, as with order.status = 'PENDING_PAYMENT', and make other operations respect the mark, by refusing, waiting or treating it specially.
  • Commutative updates: design operations so their order does not matter. Debits and credits applied as increments commute, while setting a balance to a value does not.
  • Pessimistic view: reorder steps to reduce the damage of a dirty read. For example, raise a credit limit only in the final, retryable step.
  • Reread value: before updating, check that the record has not changed since the saga read it (optimistic concurrency), and abort or restart if it has.
  • Version file: record operations as they arrive so that out-of-order steps, such as a cancel arriving before its create, can be reordered.
  • By value: choose the mechanism per request by risk. Large transfers use a distributed transaction or manual review, small ones use a saga.

Choreography in practice. In a choreographed checkout, Order Service writes an order in PENDING and emits OrderCreated. Payment Service consumes it, charges the card, and emits PaymentSucceeded or PaymentFailed. Inventory Service consumes PaymentSucceeded, reserves stock, and emits StockReserved or StockUnavailable. Order Service listens for the terminal events and marks the order confirmed or cancelled, and Payment Service listens for StockUnavailable and refunds.

The flow is spread across services, so give every event a correlation ID (the order ID) and trace it end to end. Avoid cycles, where service A's event triggers B, whose event triggers A, and keep choreography for short chains. Every event must be published through an outbox, or the chain breaks on the first crash.

Orchestration and durable execution. An orchestrator holds the saga's state machine and issues commands. The hard part is surviving crashes. If the process running the saga dies after step 2, a restart must know that steps 1 and 2 are done and step 3 is next. Writing your own state table works for simple flows. Durable execution engines generalise it. In Temporal (and Cadence, its predecessor from Uber), the workflow is ordinary code. Every step's result is recorded in an event history held by the Temporal service. When a worker crashes, another worker replays the history through the same code. Completed steps return their recorded results instead of running again, and execution continues from the first unfinished step. That requires workflow code to be deterministic, with no direct clock reads, random numbers or network calls, while all side effects live in activities that the engine retries with configured policies. AWS Step Functions and Azure Durable Functions offer the same guarantees with a state-machine definition or a managed runtime.

Operational questions every saga must answer.

  • Crash midway? With durable execution, the saga resumes from its recorded history. With a hand-rolled orchestrator, the saga row's state and a periodic sweeper resume stuck instances.
  • Changing the workflow while instances are in flight? Running instances were started with the old logic. Either version the code paths (Temporal's patching or versioning APIs branch on a recorded marker), or let old instances finish on old workers while new ones start on the new definition.
  • Unbounded state? A long-running saga, such as a subscription that renews monthly for years, accumulates history. Periodically restart it as a fresh instance carrying only its current state (Temporal's "continue-as-new").
  • External events? A saga that waits for a human approval or a webhook from a payment provider receives it as a signal or message, with a timer that triggers a timeout path if it never arrives.
  • Exactly-once steps? The engine guarantees at-least-once execution of activities. Make each activity idempotent with a key derived from the saga ID and step name, and pass that key to downstream APIs such as a payment provider's idempotency key.

TCC (try-confirm-cancel)#

TCC is a reservation-based variant. Each participant exposes three operations:

  • Try: check and reserve resources (hold 2 seats, put a hold of $300 on a card); nothing final happens.
  • Confirm: make the reservation final; it must succeed if Try succeeded.
  • Cancel: release the reservation.

The coordinator calls Try on everyone, then Confirm on all if every Try succeeded, otherwise Cancel. Unlike a saga, no participant applies a visible final change before everyone has agreed, so isolation is better (others see "reserved", never "sold then refunded"). Reservations need timeouts so that a lost coordinator does not hold resources forever. It fits domains with natural holds: inventory, seats, card authorisations (authorise, then capture or void). Its cost is three APIs per service, and handling Cancel arriving before Try (an "empty rollback") and duplicate calls.

TCC in depth#

Where it comes from. Pat Helland's essay "Life beyond Distributed Transactions: an Apostate's Opinion" (CIDR 2007) argued that large systems must give up distributed transactions and instead coordinate independent entities through tentative operations, confirmations and cancellations, with every message idempotent. Try-confirm-cancel is a concrete form of that idea. It was popularised in Java transaction managers such as Atomikos and is offered by Alibaba's Seata framework, alongside its XA, saga and "AT" modes.

A worked example: booking concert seats. A user buys two seats and a parking pass in one checkout. The flow runs in three steps.

  1. Try. The seat service marks seats A12 and A13 as HELD by reservation r-881, with an expiry 10 minutes ahead. The parking service decrements available passes and records a hold. The payment service places an authorisation hold of $240 on the card. Nothing is sold yet. Other buyers see the seats as unavailable, but nobody sees them as sold.
  2. Confirm. Every Try succeeded, so the coordinator calls Confirm on each. Seats become SOLD, the parking hold becomes a pass, and the payment authorisation is captured.
  3. Cancel. If any Try fails, say parking is sold out, the coordinator calls Cancel on the services whose Try succeeded. Seats return to AVAILABLE and the authorisation is voided.

Compared with a saga, nobody ever observed a "sold, then refunded" seat. The worst visible state is "held", which the business already understands.

The three classic edge cases. TCC frameworks document the same hazards, and any hand-built TCC must handle them:

  • Idempotency: Confirm and Cancel can be delivered more than once after retries, so each must check the reservation's state and do nothing if it has already been applied.
  • Empty rollback: the coordinator times out waiting for Try and sends Cancel, but the Try request never arrived. Cancel must succeed and record that reservation r-881 was cancelled, even though there was nothing to release.
  • Suspension (late Try): the delayed Try then arrives after that Cancel. It must be rejected because the reservation was already cancelled, otherwise it would hold seats forever with no coordinator to confirm or cancel them.

All three come down to a per-reservation state record, checked and updated atomically in the participant's own database.

Timeouts and holds. Every Try must carry an expiry, and the participant must release holds on its own when the expiry passes. A coordinator can disappear for good, and resources must not stay locked. Choosing the expiry is a business decision. It must be long enough to finish checkout, including a slow 3-D Secure card challenge, and short enough that popular inventory is not tied up by abandoned carts. Card authorisations have their own natural expiry set by the card networks and issuers, typically several days, after which an uncaptured hold drops off automatically.

When TCC fits. TCC suits resources with natural, short-lived holds: seats, rooms, inventory units, rate-limited quotas and card authorisations. It is a poor fit when a participant cannot offer a reservation, such as a third-party API that only has "do it" and "undo it". In that case a saga with compensation is the only option. TCC also triples the API surface of each participant, so reserve it for flows where the isolation benefit matters.

Transactional outbox#

A very common sub-problem: a service must update its database and publish an event. Doing both separately is a dual write: if the process crashes between them, the database and the event stream disagree.

The outbox pattern writes the event into an outbox table in the same local transaction as the business change. A separate relay publishes outbox rows to the broker and marks them sent.

BEGIN;
UPDATE orders SET status = 'PAID' WHERE id = 991;
INSERT INTO outbox (id, aggregate_id, type, payload, created_at)
VALUES (gen_random_uuid(), 991, 'OrderPaid', '{"order_id":991,"amount":4999}', now());
COMMIT;
-- Relay: poll "WHERE published_at IS NULL ORDER BY created_at", publish, then set published_at
-- or tail the WAL with CDC (Debezium outbox router)

The relay may publish an event twice (crash after publishing, before marking), so consumers must be idempotent, typically by recording processed event IDs. The outbox is the reliable glue for choreographed sagas and event-driven systems. See Change Data Capture and Delivery Semantics.

Outbox and inbox in depth#

Two ways to relay. The relay that moves outbox rows to the broker comes in two forms.

  • Polling publisher: a job runs SELECT ... WHERE published_at IS NULL ORDER BY id LIMIT 500 every 100 ms or so, publishes the rows, and marks them published. It is simple and works on any database, but it adds query load, and its latency is the polling interval. With several relay instances, use FOR UPDATE SKIP LOCKED or a leader so rows are not published twice concurrently.
  • Log tailing (CDC): Debezium, or a similar tool, reads the database's write-ahead log or binlog and turns inserts into the outbox table into broker messages. Debezium ships an "outbox event router" transformation that routes each row to a topic based on its aggregate type and uses the aggregate ID as the message key. Latency drops to tens of milliseconds, and there is no polling load. PostgreSQL also lets you write an event straight into the WAL with pg_logical_emit_message, so no outbox table rows need to be stored or cleaned up at all.

Ordering. Consumers usually need events for one entity in order: OrderCreated before OrderPaid before OrderCancelled. Publish with the aggregate ID as the partition key so all of one order's events go to one Kafka partition, which preserves their order. Global ordering across entities is rarely needed and very expensive.

Cleanup. Outbox tables grow by one row per event. Delete or partition-drop published rows after a retention period, for example 7 days, or use log-only messages as above. An outbox table that grows forever slows the poller and bloats backups.

The inbox: exactly-once effects. The relay guarantees at-least-once delivery. It can publish a row and crash before marking it, so the event is published again on restart. Consumers make the effect happen exactly once by recording each processed event ID in an inbox (or processed_events) table in the same local transaction as the effect. A duplicate then hits the unique key and is skipped. At-least-once delivery plus an idempotent consumer gives exactly-once effects, which is what businesses actually need. Within Kafka itself, a consume-transform-produce pipeline can use Kafka transactions to commit its output messages and its consumer offsets atomically, giving exactly-once processing between topics. Side effects outside Kafka still need idempotency.

Listen to yourself. A variation avoids the outbox table: the service publishes the event first, then updates its own database by consuming its own event, like any other consumer. The event log becomes the source of truth. This is close to event sourcing, and it suits services that are already event-driven. The cost is that the service's own reads may lag behind its writes. See Event Sourcing and CQRS.

A multi-step pipeline example. A personal-finance app refreshes a linked bank account. The accounts API puts a job on a queue, because extraction from the bank can take seconds to minutes. A worker pulls the job, fetches transactions, stores the raw response in object storage, categorises each transaction, and then, in one SQL transaction, inserts the categorised rows into transactions, updates monthly_spending aggregates for the affected categories, and inserts an outbox row BudgetRecalculated. A notification service consumes that event and alerts the user if a budget is exceeded. Keeping the two tables in one database turns what could be a distributed transaction into a local one. The outbox makes the notification reliable. The queue job is safe to retry because the insert is keyed by the bank's transaction ID, so re-running it changes nothing.

Choosing an approach#

SituationApproach
Data can live in one databaseA local ACID transaction; redraw service boundaries if needed
One database, many shardsThe database's own distributed transactions (Spanner, CockroachDB, Vitess 2PC)
Update the DB and publish an eventTransactional outbox (or CDC)
Multi-step business process across servicesOrchestrated saga on a workflow engine
2-3 loosely coupled stepsChoreographed saga with outbox events
Resources with natural holds (seats, stock, card auth)TCC or a saga with reservations
Heterogeneous databases needing strict atomicity, low volumeXA 2PC, accepting blocking risk

The first question is always: can I avoid it? Most "distributed transactions" disappear by keeping data that must change atomically within one service and one database.

Choosing an approach in depth#

A decision path. Most real decisions follow the same few questions, in this order:

Worked case 1: money transfer between users on different shards. Alice (shard 3) sends Bob (shard 41) $50. A cross-shard 2PC would work, but it ties the transfer to both shards being up. A common alternative treats the transfer as its own entity, a saga:

  1. On Alice's shard, in one local transaction, check her balance, debit $50, and insert a transfer row (id = t-19, PENDING) plus an outbox event TransferDebited.
  2. A consumer on Bob's shard receives the event and, in one local transaction, credits $50 and records t-19 in its inbox, so a duplicate does nothing. It emits TransferCredited.
  3. Alice's shard marks t-19 COMPLETED. If Bob's account is closed and the credit is permanently rejected, the compensation credits Alice back and marks the transfer REVERSED.

At any moment, the sum of balances plus in-flight transfers is constant, so the books balance. That is the standard double-entry ledger view. Users see the debit immediately and the credit within a second, which banks have always done. Many payment systems are built this way, because a pending state is honest and auditable.

Worked case 2: e-commerce checkout. The steps are reserve stock (compensatable, with a 15-minute hold), authorise payment (compensatable by voiding), create the order in CONFIRMED (the pivot), then capture payment, notify the warehouse and send email (retryable). This is an orchestrated saga with TCC-style holds for stock and payment. If authorisation fails, the stock hold is released. Once the order is confirmed, the remaining steps are retried until they succeed, with alerts if they keep failing.

Worked case 3: high-contention flash sale. For 1,000 units of a product and 200,000 buyers, any approach that holds locks across services collapses. Keep the contended counter in one place, such as a single row with an atomic conditional decrement or a Redis counter, then run the slow, multi-service part of checkout as a saga only for buyers who got a unit. Holds expire, so abandoned checkouts return stock. See Pattern: Dealing with Contention.

Weighing the options. The deciding factors are usually:

  • Isolation needs: if intermediate states must never be visible, use 2PC inside one database, or TCC with holds. If visible pending states are acceptable, a saga will do.
  • Duration: milliseconds suit database transactions. Seconds to days need sagas on a durable engine.
  • Ownership: services owned by different teams or companies cannot share a transaction manager, but they can expose idempotent APIs and holds.
  • Failure cost: money and inventory demand an auditable trail (ledger rows, transfer records) whatever protocol is used.

Reconciliation, observability and testing#

Reconciliation is the safety net under every protocol. No matter how carefully you write a saga or a 2PC coordinator, bugs, manual database edits, vendor outages and lost webhooks will leave a few records out of step. Mature systems therefore run a reconciliation job: a periodic process that compares two sources that should agree and reports or repairs the differences. A payments team compares its internal ledger against the payment provider's settlement file every night. An order service compares orders in CONFIRMED against the warehouse's shipment records. An inventory service compares holds against active checkouts and releases orphans. The job is simple to write. Its value is that it turns silent drift into a visible, countable queue of exceptions. A typical target is to count mismatches per million transactions and alert when the rate rises above its usual baseline.

Design records so they can be reconciled. Reconciliation needs a shared key. If the saga ID travels into every downstream system (as an idempotency key, a metadata field on the charge, a column on the shipment), matching is a join. Without it you are left fuzzy-matching amounts and timestamps. Keep every state transition with a timestamp, the actor, and the reason. "Order 8812 moved PENDING to CANCELLED at 10:02:17 by the saga timeout" is what an on-call engineer needs at 3 a.m.

Metrics worth watching.

  • Sagas by state and age. A histogram of how long sagas have been in each non-terminal state. A growing tail in PAYMENT_PENDING is the earliest sign of a stuck downstream service.
  • Compensation rate. The fraction of sagas that compensate. A sudden jump usually means a dependency is failing, not that customers changed behaviour.
  • Outbox lag. Age of the oldest unpublished outbox row. Seconds is normal. Minutes means the relay is down or the broker is rejecting writes.
  • Prepared transaction age for any XA or 2PC use. In PostgreSQL, query pg_prepared_xacts. Anything older than a minute or so is likely orphaned and holding locks.
  • Dead-letter queue depth for failed steps and compensations, with an owner and a runbook for each type.

Distributed tracing. Propagate one trace context (W3C traceparent) through every step, including asynchronous hops via message headers. Then one trace shows the whole saga across services, and a slow or failing step is obvious. Tag spans with the saga ID so traces and business records can be joined.

Testing. Unit tests cannot find most distributed-transaction bugs, because the bugs live in timing and failure. Useful techniques:

  • Fault injection per step. For each step, test a crash before it runs, after it commits but before it replies, and during its compensation. The "after commit, before reply" case is the one that exposes missing idempotency.
  • Duplicate and reordered delivery. Deliver every message twice and in swapped order in tests. Consumers that break under this will break in production.
  • Workflow replay tests. Durable engines such as Temporal can replay recorded histories against new code to catch non-deterministic changes before deployment.
  • Model checking and Jepsen-style tests. Specifying the protocol in TLA+ (as Amazon engineers described doing for DynamoDB and S3 in a 2015 Communications of the ACM article) finds design-level bugs that tests miss. Jepsen-style tests run a real cluster under partitions and check the recorded history for anomalies.

Transactions that cross company boundaries#

Many "distributed transactions" involve a system you do not control: a card network, a payment provider, a shipping carrier, a bank. You cannot enlist them in 2PC, and they will not run your compensations. Three techniques carry most of the load.

Idempotency keys on every mutating call. Providers such as Stripe accept an Idempotency-Key header. A retry with the same key returns the original result instead of charging twice. Derive the key from the saga ID and step name, such as order-8812:charge, so that retries after a crash reuse it. Store the key before you call, not after, so a crash between the call and the save cannot produce a second, different key. See Idempotency.

The unknown outcome. A request that times out may or may not have succeeded. This is the same uncertainty as a prepared 2PC participant, but with no coordinator log to consult. The rule: never treat a timeout as failure and compensate immediately. First, retry with the same idempotency key, or query the provider for the operation's status by your reference. Only compensate once you know the original attempt failed or has been cancelled. Mark the step UNKNOWN in your own state so that the reconciliation job and humans can see it.

Webhooks as the second channel. Providers report asynchronous results (a payment settled, a dispute opened, a refund failed) by calling your webhook. Treat webhooks like any other at-least-once event stream. Verify the signature, record the event ID in an inbox table to drop duplicates, and process it idempotently. Do not rely on webhook ordering. Fetch the current state of the object from the provider when order matters. Because webhooks can be lost during your own outages, pair them with periodic polling or the provider's event list API as a backstop.

Two-step money movement. Card payments are naturally a TCC protocol. An authorisation reserves funds on the cardholder's account (the Try). A capture takes them (the Confirm). A void releases them (the Cancel). Authorisations expire after a network-defined period, typically about 7 days for many card types, which is the built-in timeout. Capturing only when goods ship, and voiding when an order is cancelled before shipping, keeps the customer's money untouched until you are sure. That is exactly the "reserve, then commit" shape this page recommends for internal systems.

Contracts in place of protocols. Across organisations, the agreement about what happens on failure is written into an API contract and a service-level agreement, not a commit protocol. Examples are refund windows, settlement schedules and dispute processes. When designing, read the external party's guarantees carefully. What is idempotent? How long are results retained? What states can an operation be in? Your saga's states should mirror theirs.

When to Use It#

  • Business processes that span services: checkout, trip booking, money transfers between ledgers.
  • Writing to a database and a message broker reliably (outbox).
  • Transactions across shards of one database (use the database's built-in support).

When NOT to Use It#

  • When the data can be co-located; a local transaction is simpler and faster.
  • 2PC across independently deployed microservices over HTTP: it couples availability and blocks.
  • Sagas for steps that cannot be compensated and cannot be ordered after a pivot; redesign the flow.
  • High-contention hot paths where holding locks during network calls would collapse throughput.

How to Implement It#

  1. Draw the steps and mark each step's compensation; put irreversible steps last (pivot), after reservations.
  2. Make every step idempotent with request or event IDs; retries are certain.
  3. Use an orchestrator with durable state (Temporal, Step Functions) for anything beyond a few steps.
  4. Publish events through an outbox or CDC, never with dual writes.
  5. Add semantic states (PENDING, RESERVED) and timeouts so partial states are visible and expire.
  6. Monitor stuck sagas and provide manual repair tools; some failures need humans.
TechnologyFits when
Temporal, CadenceCode-first durable workflows for orchestrated sagas
AWS Step FunctionsManaged state machines on AWS
Debezium (outbox router), KafkaReliable event publishing from the outbox
Spanner, CockroachDB, YugabyteDBDistributed SQL with built-in cross-shard transactions
XA transaction managers (Atomikos, Narayana)Classic 2PC across XA-capable resources

Trade-offs#

ChoiceGainCostPick when
2PCAtomic, isolatedBlocking, latency, all participants must be upInside a database or tightly controlled resources
Saga (choreography)Loose coupling, no central serviceHard to trace and change, no isolationFew simple steps
Saga (orchestration)Explicit flow, timeouts, compensationOrchestrator to run; coupling to itComplex business processes
TCCBetter isolation via reservationsThree APIs per service, timeoutsNatural holds
OutboxReliable DB + eventRelay to run; duplicate eventsEvery event-publishing service
Consensus-replicated 2PCAtomic, isolated, no single blocking pointCross-shard latency, commit waitDistributed SQL with multi-shard invariants
Inbox deduplicationExactly-once effects from at-least-once deliveryExtra table and write per eventEvery event consumer with side effects
Ledger with transfer recordsAuditable, balances always reconcilePending states visible to usersMoney movement between accounts or shards

Common Pitfalls#

  • Dual writes (DB then broker) without an outbox, losing events on crashes.
  • Compensations that are not idempotent or that can themselves fail without retry.
  • Forgetting the lack of isolation: other requests act on half-finished sagas.
  • Choreography spread across ten services that nobody can trace.
  • Holding database locks while waiting for remote calls.
  • Leaving PostgreSQL prepared transactions orphaned, holding locks and blocking vacuum.
  • Placing an irreversible step, such as shipping or an external email, before the pivot.
  • Not handling empty rollback and late Try in TCC, so holds leak or reappear.
  • Non-deterministic code in durable workflows (clock reads, random IDs) breaking replay after a crash.

Real-World Examples#

Google's Spanner paper (2012) describes 2PC across Paxos-replicated groups, so the coordinator and participants are each fault-tolerant and in-doubt blocking is avoided in practice.

Uber built Cadence, the predecessor of Temporal, to run long-lived workflows durably; Temporal is now used by many companies to orchestrate sagas.

Garcia-Molina and Salem's 1987 sagas paper anticipated today's microservice patterns by decades. Chris Richardson's Microservices Patterns (2018) catalogued the saga isolation countermeasures (semantic lock, commutative updates, pessimistic view, reread value, version file, by value) used in many production designs. Debezium's outbox event router is widely used to publish outbox rows to Kafka from the database log.

In the Interview#

Handling distributed transactions in an interview#

Spot the trigger. Any time a single user action changes data owned by two services or two shards, such as "place an order and charge the card" or "move money between accounts", the interviewer is checking whether you notice. Say it out loud: "These two writes are in different services, so there is no single ACID transaction. Here's how I keep them consistent."

Lead with avoidance. First, ask whether the data can be co-located. "I'll shard swipes by the sorted user pair, so recording a swipe and checking for a match is one partition." Or: "The order and its line items share a service and a database, so that's a local transaction." Interviewers reward designs that make the hard problem disappear.

Then pick a pattern and state its guarantees. "Checkout is an orchestrated saga on Temporal. Reserve stock with a 15-minute hold, authorise the card, mark the order confirmed as the pivot, then capture and ship as retryable steps. Each step is idempotent with a key made of the order ID and step name. Events go out through an outbox, and consumers dedupe with an inbox table." Then name the isolation trade-off: "Users can see 'payment pending' for a second or two, and other flows respect the pending status."

Answer the follow-ups crisply.

  • "Why not 2PC?" A participant that has voted yes blocks while the coordinator is down, every service must be up at once, and locks are held across network calls.
  • "What if a compensation fails?" It is idempotent and retried with backoff. After a limit it goes to a dead-letter queue with an alert and a runbook for manual repair.
  • "What if the orchestrator crashes?" Its state is durable, so another worker resumes from the recorded history.
  • "How do you avoid double charges?" Use the payment provider's idempotency key, derived from the saga ID.

Red flags to avoid: wrapping calls to several services in one "transaction", writing to the database and Kafka separately, and compensations that assume they run exactly once.

Deep Dive: Commit protocols in distributed databasesShow

Parallel commits. CockroachDB writes a transaction record in a "staging" state alongside intents (provisional writes) in parallel; the transaction is committed as soon as all writes are durably replicated, letting it reply after one round of consensus instead of two.

Deterministic databases. Calvin-style systems (FaunaDB, inspired by the Calvin paper, 2012) agree on the order of transactions first, then execute them deterministically on every replica, removing the need for 2PC for most transactions.

Percolator. Google's Percolator (2010) built cross-row transactions on top of Bigtable with a timestamp oracle and a primary lock per transaction; TiDB uses a similar model. Locks left by crashed clients are resolved by checking the primary lock's status.

Sagas and the outbox in event sourcing. If the service is event-sourced, the event log itself is the source of truth and publishing is natural; see Event Sourcing and CQRS.

Deep Dive: Atomic commitment theory and what sagas really guaranteeShow

The atomic commitment properties. Bernstein, Hadzilacos and Goodman (Concurrency Control and Recovery in Database Systems, 1987) state the requirements precisely:

  • AC1: all processes that decide reach the same decision.
  • AC2: a process cannot reverse its decision.
  • AC3: commit can be decided only if all processes voted yes.
  • AC4: if there are no failures and all voted yes, the decision is commit.
  • AC5: after failures are repaired and stay repaired long enough, all processes eventually decide.

2PC satisfies all five, but AC5 only eventually: while the coordinator is down, prepared processes cannot decide. That is the blocking problem in formal terms. Skeen showed that no protocol can be non-blocking if communication failures (partitions) are possible and the protocol must never let two sides decide differently. You can pick at most two of non-blocking, safe under partitions, and every-participant veto. Consensus-based commit keeps safety and vetoes and makes blocking require a majority failure, which is the practical optimum.

Paxos Commit's cost. With N participants and 2F + 1 acceptors, Gray and Lamport's Paxos Commit uses about (N + 1)(F + 3) - 4 messages in the normal case. It has the same message delay as 2PC when the participants' Paxos acceptors are co-located. With F = 1 it tolerates any single failure, including the coordinator's, without blocking. The Spanner design is a practical instance: each participant's vote is a Paxos-replicated log entry.

What a saga guarantees, formally. A saga guarantees atomicity in the eventual sense: in the end, either all T steps took effect, or the completed ones were compensated. It guarantees consistency only if each Ti and each Ci preserves invariants on its own and the invariants tolerate intermediate states. It guarantees durability from the local databases. It gives no isolation. Other transactions can observe and act on any prefix of the saga. A useful way to reason about safety is to treat each intermediate state as a legitimate business state, such as "reserved" or "pending payment", with its own rules. If you cannot name and handle a state, the saga needs reordering, a semantic lock or a TCC hold.

Compensations are not inverses. In general Ci(Ti(x)) is not equal to x. Refunding a charge leaves both a charge and a refund on the statement. Cancelling a hotel booking may incur a fee. Releasing a seat after another buyer already saw it as taken has changed what they did. Compensation restores business consistency, not data identity, and its semantics belong in the product specification, not just the code. When an action has no acceptable compensation, such as sending a physical shipment, it must come after the pivot, or be protected by a hold.

Deterministic and timestamp-ordered alternatives. Calvin (Thomson et al., SIGMOD 2012) sequences transactions in a replicated log before execution, so every replica runs them in the same order and multi-partition transactions need no 2PC. The cost is that transactions must declare their read and write sets in advance. Percolator (Peng and Dabek, OSDI 2010) layers snapshot-isolated transactions on Bigtable with a timestamp oracle and a primary lock. Its commit is effectively 2PC, with the primary lock's state as the coordinator's durable decision, so any client can resolve an abandoned transaction by checking that one cell. TiDB's transaction model descends from it.

Key Takeaways#

  • Cross-service transactions are hard because of partial failures, uncertain outcomes and no shared locks.
  • 2PC is atomic but blocks when the coordinator fails; 3PC does not survive partitions; consensus-replicated coordinators fix blocking inside databases.
  • Sagas chain local transactions with compensations, via choreography or orchestration, and give up isolation.
  • TCC reserves first and then confirms or cancels; the outbox makes database-plus-event writes reliable.
  • Choose by first avoiding distributed transactions, then outbox for events, orchestrated sagas for processes, and built-in database transactions across shards.
  • Atomic commit gives every participant a veto, which is why 2PC must block when the coordinator's decision is unreachable. Replicating the coordinator with consensus is the practical fix.
  • Order saga steps as compensatable, then pivot, then retryable, and make every step idempotent with a key derived from the saga ID.
  • TCC needs per-reservation state to handle duplicates, empty rollbacks and late Try requests, and every hold needs an expiry.
  • Outbox plus inbox gives exactly-once effects. At-least-once delivery is unavoidable, but duplicate effects are not.