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

Comparison of Two-Phase Commit (2PC) vs Saga pattern: in 2PC, a Coordinator sends PREPARE to lock rows across Order DB and Payment DB, then sends COMMIT only if all vote YES (blocking locks if the coordinator crashes); in the Saga pattern, Order Service and Payment Service each commit locally, and when Inventory fails with Out of Stock, compensating undo actions Refund Card and Cancel Order roll back prior steps without global locks Comparison of Two-Phase Commit (2PC) vs Saga pattern: in 2PC, a Coordinator sends PREPARE to lock rows across Order DB and Payment DB, then sends COMMIT only if all vote YES (blocking locks if the coordinator crashes); in the Saga pattern, Order Service and Payment Service each commit locally, and when Inventory fails with Out of Stock, compensating undo actions Refund Card and Cancel Order roll back prior steps without global locks
2PC holds distributed locks for atomic ACID commits (blocking on coordinator crash); Saga commits locally and runs compensating undo actions on failure · Made with Akriti

Two-Phase Commit (2PC) — Strong ACID, Blocking Locks

A central Coordinator runs two rounds across all participating databases:

  1. 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 replies YES (or NO).
  2. Phase 2 (Commit / Abort): If all participants voted YES, the coordinator logs COMMIT and tells everyone to commit and release locks. If any voted NO (or timed out), it tells everyone to ABORT.

Why microservices rarely use 2PC across service boundaries:

  • Blocking protocol: If the coordinator crashes after participants voted YES and 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 Stock fails (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

  1. Always pair with the Transactional Outbox: Never do db.commit() followed by kafka.publish() in two separate calls — a crash between them breaks the Saga. Write the outbound event into an outbox table inside the exact same local DB transaction and relay it reliably (see Temporal Coupling).
  2. Every step AND every compensation must be idempotent: Because brokers deliver messages at-least-once, ChargeCard(orderId=42) and RefundCard(orderId=42) must safely handle duplicate deliveries using idempotency keys.
  3. Design around missing Isolation (“Dirty Reads”): Because OrderCreated is 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 (like RefundCard 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.
What is a ‘pivot transaction’ in a Saga? A pivot transaction is the point of no return in a Saga (for example, actually charging a non-refundable wire transfer or shipping a package). Steps before the pivot must have compensating undo actions; once the pivot succeeds, all remaining steps are retryable until completion rather than rolled back.
When should I avoid distributed transactions altogether? Whenever two pieces of data always need strict ACID invariants together, ask whether they actually belong in the same service and database first! Over-splitting a monolith into tiny microservices creates unnecessary distributed transactions — keep tightly coupled transactional invariants inside one bounded context (see Domain Coupling).
Does Temporal or AWS Step Functions replace the Saga pattern? They implement orchestrated Sagas for you! Durable execution engines like Temporal persist workflow state, timers, retries, and compensation history automatically so you don’t have to hand-roll state tables and retry loops from scratch.