Distributed Transactions: 2PC vs. Saga Pattern
Inside a single relational database, an ACID transaction (BEGIN ... COMMIT / ROLLBACK) makes multi-row updates all-or-nothing effortlessly. The moment a business workflow spans multiple microservices (Order DB + Payment DB + Inventory DB) or multiple database shards, there is no single local lock manager anymore — if Step 2 succeeds and Step 3 crashes, your system is left half-updated.
A distributed transaction coordinates state changes across independent data stores so they either all succeed or cleanly roll back. In practice, engineers choose between two fundamentally different approaches: Two-Phase Commit (2PC) or the Saga Pattern.
Two-Phase Commit (2PC) vs. Saga Pattern
Two-Phase Commit (2PC) — Strong ACID, Blocking Locks
A central Coordinator runs two rounds across all participating databases:
- Phase 1 (Prepare / Vote): Coordinator asks every participant (
Order DB,Payment DB): “Can you guarantee this commit?” Each DB acquires row locks, writes to its WAL, and repliesYES(orNO). - Phase 2 (Commit / Abort): If all participants voted
YES, the coordinator logsCOMMITand tells everyone to commit and release locks. If any votedNO(or timed out), it tells everyone toABORT.
Why microservices rarely use 2PC across service boundaries:
- Blocking protocol: If the coordinator crashes after participants voted
YESand before Phase 2 arrives, every participant must hold row locks indefinitely until the coordinator recovers — freezing unrelated traffic! - Throughput & heterogeneity: Holding database locks across network round-trips kills throughput, creates severe temporal coupling, and doesn’t work across systems that don’t speak XA (like Stripe’s HTTP API or Redis).
(Note: 2PC IS widely used internally inside distributed SQL databases like Google Spanner and CockroachDB — where the coordinator is itself replicated via Raft consensus so it never permanently crashes!)
The Saga Pattern — Non-Blocking Local Transactions + Compensation
Instead of one giant locked transaction, a Saga breaks the workflow into a sequence of independent local transactions (T1 → T2 → T3), each committing immediately in its own database and triggering the next step via a message broker:
- Happy path:
Create Order ✓→Charge Card ✓→Reserve Stock ✓. - Failure path: If
Reserve Stockfails (Out of Stock ✗), the Saga runs compensating transactions in reverse order (Refund Card→Cancel Order) to semantically undo the prior committed steps!
| Dimension | Two-Phase Commit (2PC) | Saga Pattern |
|---|---|---|
| Consistency model | Strong ACID (atomic & isolated) | Eventual consistency (ACD — no isolation between steps) |
| Locking | Holds locks across nodes during network RTT | Local locks only (sub-millisecond) |
| Availability under failure | Blocks if coordinator dies mid-commit | Non-blocking — retries and compensates asynchronously |
| Works with external APIs? | No (requires XA-compliant stores) | Yes (works with Stripe, email, webhooks, NoSQL) |
| Best fit | Distributed SQL internals (Spanner, CockroachDB) | Multi-service workflows (checkout, booking, fulfillment) |
Choreography vs. Orchestration Sagas
There are two ways to wire the steps of a Saga:
- Choreography (Event-Driven): Each service publishes event messages (
OrderCreated,PaymentCharged,InventoryFailed) and listens for events it cares about. No central coordinator — great for simple 2–3 step flows, but hard to trace or change once 6+ services are chained together. - Orchestration (Central Workflow): A dedicated Saga Orchestrator (or workflow engine like Temporal, AWS Step Functions, or Camunda) sends explicit command messages (
ChargeCard,ReserveInventory) and drives retries and compensations from one readable state machine. Preferred for complex multi-step business workflows.
Three Rules for Bulletproof Production Sagas
- Always pair with the Transactional Outbox: Never do
db.commit()followed bykafka.publish()in two separate calls — a crash between them breaks the Saga. Write the outbound event into anoutboxtable inside the exact same local DB transaction and relay it reliably (see Temporal Coupling). - Every step AND every compensation must be idempotent: Because brokers deliver messages at-least-once,
ChargeCard(orderId=42)andRefundCard(orderId=42)must safely handle duplicate deliveries using idempotency keys. - Design around missing Isolation (“Dirty Reads”): Because
OrderCreatedis committed before inventory is checked, a user might briefly see their order before it cancels. Use explicit intermediate states (PENDING→CONFIRMED/CANCELLED) — called semantic locking — so other services never ship an unconfirmed order!
FAQs
Can a compensating transaction fail?
Compensating actions (likeRefundCard or ReleaseStock) must never give up — they are retried with exponential backoff until they succeed (often paired with a Dead-Letter Queue and ops alerting for truly exceptional cases). Always design compensations to be idempotent and commute safely with retries.