Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

Two-Phase Commit (2PC) vs.
the Saga Pattern.

Replace blocking XA/2PC distributed locks with an orchestrated Saga using semantic reservations, idempotent steps, transactional outbox messaging, and compensating actions for non-blocking fault tolerance.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, 2PC guarantees atomic isolation (ACD) by holding locks across network RTTs, making it vulnerable to coordinator crashes; Sagas trade strict isolation for high availability and throughput using eventual consistency and compensations.

TL;DR30-second simplified summary
▾

Core Mechanics: An e-commerce checkout at 2,500 checkouts/sec (p99 <= 400 ms) spans OrderService (PostgreSQL), InventoryService (PostgreSQL), and PaymentService (Stripe 150–300 ms HTTP).

Visual & Structural Flow: Depicts Reserve -> Charge Stripe -> Compensate on Failure (Non-Blocking) (Saga Orchestrator -> Inventory DB -> Stripe PSP); Forward Progress & Reverse Compensation Transitions (T1: RESERVED -> T2: PAID (PIVOT) -> C1: COMPENSATE).

Trade-Offs & Production: Both extremes fail if designed carelessly: 1. Orchestrated Sagas are the standard pattern for cross-domain workflows: E-Commerce Checkout & Fulfillment: Coordinates Order, Inventory, Payment, and Shipping.

Failure Modes & Application: Orchestrated Sagas are the standard pattern for cross-domain workflows: E-Commerce Checkout & Fulfillment: Coordinates Order, Inventory, Payment, and Shipping.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Two-Phase Commit (2PC)
Two-Phase Commit (2PC) coordinates an atomic all-or-nothing transaction across independent shards or services by splitting execution into a durable PREPARE voting round followed by a COMMIT or ABORT decision.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why 2PC cannot span microservices and external Stripe APIs at 2,500/sec.

Why this matters: The mechanism: understand how Why 2PC cannot span microservices and external Stripe APIs at 2,500/sec works from first principles.

Think of Why 2PC cannot span microservices and external Stripe APIs at 2,500/sec as the intuition layer for Two-Phase Commit (2PC) vs. the Saga Pattern: The mechanism: understand how Why 2PC cannot span microservices and external Stripe APIs at 2,500/sec works from first principles.

An e-commerce checkout at 2,500 checkouts/sec (p99 <= 400 ms) spans OrderService (PostgreSQL), InventoryService (PostgreSQL), and PaymentService (Stripe 150–300 ms HTTP). External APIs do not support XA prepare/commit, and holding database row locks across 300 ms network RTTs under 2PC destroys throughput and wedges if the coordinator crashes.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Coordinator wedging in 2PC vs. dirty reads in naive Sagas.

Why this matters: The problem: see what breaks without Coordinator wedging in 2PC vs. dirty reads in naive Sagas under real concurrency or scale.

Both extremes fail if designed carelessly:

  1. 2PC (XA) Lock Wedging: Holding Inventory locks during Phase 1/2 across 300 ms Stripe calls caps concurrency and leaves participants blocked indefinitely if the coordinator dies.
  2. Naive Saga Anomalies: Because Sagas lack ACID Isolation (I), concurrent checkouts can read uncommitted state or double-deduct inventory on Kafka redelivery.
Orchestrated Saga & Compensation

Reserve -> Charge Stripe -> Compensate on Failure (Non-Blocking)

Saga OrchestratorInventory DBStripe PSP1. T1: Semantic Lock (RESERVED)2. T2 (Pivot): Charge + IdemKey3. Card Declined (402)4. C1: Compensate -> release stock

Orchestrated Sagas use local ACID transactions, semantic RESERVED locks, and idempotent compensations without cross-service locks.

Engineering Decision Framework
Problem
How to implement Two-Phase Commit (2PC) vs. the Saga Pattern without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, 2PC guarantees atomic isolation (ACD) by holding locks across network RTTs, making it vulnerable to coordinator crashes; Sagas trade strict isolation for high availability and throughput using eventual consistency and compensations.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Two-Phase Commit (2PC) vs. the Saga Pattern experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Why choreography-only Sagas and non-idempotent steps break at scale.

Why this matters: The problem: see what breaks without Why choreography-only Sagas and non-idempotent steps break at scale under real concurrency or scale.

Think of Why choreography-only Sagas and non-idempotent steps break at scale as the intuition layer for Two-Phase Commit (2PC) vs. the Saga Pattern: The problem: see what breaks without Why choreography-only Sagas and non-idempotent steps break at scale under real concurrency or scale.

Pure event choreography across 3+ services obscures checkout state and creates cyclic dependencies. Worse, executing Saga steps or compensations without an idempotency_log primary key causes at-least-once Kafka retries to double-deduct or double-refund inventory.

Component Topology

Why choreography-only Sagas and non-idempotent steps break at scale

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Crash-Safe Orchestrated Saga + Semantic Locks.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Sustain 2,500 checkouts/sec (p99 <= 400 ms) with zero leaked stock or orphaned charges:

  • Durable Orchestrator + Transactional Outbox: Persist each Saga state transition (PENDING -> RESERVED -> PAID -> CONFIRMED) alongside an outbox row in one local ACID commit so a crashed orchestrator resumes cleanly.
  • Isolation Countermeasures: Use Semantic Locks (reserved = reserved + qty before CONFIRMED), Commutative Updates (+qty / -qty), and Pivot Transaction ordering (Stripe charge).
  • Idempotent Steps & Compensations: Guard every local handler with INSERT INTO idempotency_log (saga_id, step) PK and pass saga_id as Stripe's Idempotency-Key.
Crash-Safe Saga State Machine

Forward Progress & Reverse Compensation Transitions

PSP charge OKPSP declined / timeoutT1: RESERVEDSemantic lock + outboxT2: PAID (PIVOT)Stripe Idempotency-KeyC1: COMPENSATERelease stock on fail

Durable state + outbox + idempotency_log PKs allow the orchestrator to crash and resume at any step safely.

BEGIN;
INSERT INTO idempotency_log (saga_id, step) VALUES ($1, $2); -- PK prevents duplicates
UPDATE inventory
   SET available = available - $3, reserved = reserved + $3
 WHERE sku = $4 AND available >= $3;
INSERT INTO outbox (event_id, topic, payload) VALUES ($5, 'saga.events', $6);
COMMIT;
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Sagas replace 2PC in distributed architectures.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Orchestrated Sagas are the standard pattern for cross-domain workflows:

  • E-Commerce Checkout & Fulfillment: Coordinates Order, Inventory, Payment, and Shipping.
  • Travel & Flash-Sale Bookings: Combines flight/hotel/seat reservations with semantic TTL locks.
  • Cloud Provisioning Pipelines: Rolls back partial VPC/IAM/VM resources on step failure.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Since Sagas do not provide ACID Isolation (I) across services, how do you prevent another checkout from double-spending or seeing inconsistent state mid-Saga?

Recommended Learning Flow