← Back to Distributed Systems

Distributed Transactions — 2PC, Saga

Distributed SystemsSeniordbsystem-design

The Question

What are 2PC and Saga patterns for distributed transactions?

What a Strong Answer Covers

  • 2PC blocking problem. Saga = compensating. Choreography vs orchestration.

Senior-Level Answer

Distributed transactions arise when a single business operation must update data across multiple services or database nodes atomically. Two-Phase Commit (2PC) and the Saga pattern are the two dominant approaches, with fundamentally different consistency guarantees and failure models.

**Two-Phase Commit (2PC)** uses a coordinator to achieve distributed atomicity. Phase 1 (Prepare): the coordinator sends a PREPARE to all participants, which each execute the transaction locally, write to a write-ahead log, and vote YES or NO. Phase 2 (Commit/Abort): if all vote YES, the coordinator sends COMMIT; if any vote NO, it sends ABORT. All participants apply or roll back accordingly.

The critical flaw: 2PC is a blocking protocol. If the coordinator crashes after sending PREPARE but before sending COMMIT, participants are in an uncertain state—they've locked resources and cannot proceed without the coordinator. This is the 'in-doubt' window, and it can block indefinitely. It also requires all participants to be available simultaneously, making it impractical across microservices with independent availability SLAs. 2PC is appropriate for coordinating nodes within a single database system (e.g., XA transactions across two PostgreSQL instances in the same data center) but is rarely used across services.

**Saga pattern** decomposes a long-running transaction into a sequence of local transactions, each publishing an event or message that triggers the next step. Consistency is achieved through compensating transactions—each step has an inverse that undoes its effect if a later step fails.

There are two coordination styles. **Choreography**: each service listens for events and decides what to do next—decentralized, lower coupling, but harder to trace the overall workflow. **Orchestration**: a central saga orchestrator (or state machine) explicitly calls each service in sequence and handles failures—easier to observe and debug, but introduces a coordination point.

Sagas provide eventual consistency, not atomicity. Compensations are not rollbacks—they issue new transactions that semantically undo prior work (e.g., issuing a refund vs. reversing a payment). This means the system can be in an inconsistent intermediate state during execution, which is acceptable for many business workflows but requires careful design of idempotency and compensation logic.

Use 2PC when you need strong ACID atomicity across a small number of co-located resources and can tolerate the blocking risk. Use Saga when you need to coordinate across microservices with independent deployments, high availability requirements, or long-running workflows where blocking is unacceptable.

Key Differences

Aspect2PCSaga
Consistency modelStrong (ACID atomicity)Eventual (compensatable)
Blocking on failureYes — blocks in-doubt until coordinator recoversNo — proceeds via compensations
Cross-service supportPoor (requires XA support)Excellent (message/event based)
Coordinator dependencySingle coordinator SPOFOrchestrator or decentralized choreography
Intermediate state visibleNo (locked until commit)Yes (steps visible before completion)
Implementation complexityLow protocol, high infra costHigher business logic (compensation design)
Best fitCo-located DB nodes, short txnsMicroservices, long-running workflows

What Separates a 2/3 from a 3/3

2/3 — Passing but Incomplete

Correctly describes both phases of 2PC, identifies the blocking/in-doubt problem, explains Saga compensation concept, distinguishes choreography from orchestration.

3/3 — Strong Answer

Explains why 2PC blocks (coordinator crash after PREPARE), articulates that Saga provides eventual not strong consistency, explains compensation as semantic undo not rollback, discusses idempotency requirements, and makes a concrete recommendation on when to use each.

Common Mistakes

  • Saying Saga 'rolls back' transactions — compensations are forward-moving new transactions, not rollbacks
  • Not mentioning 2PC's blocking problem — just describing the happy path misses the key trade-off
  • Conflating choreography and orchestration or omitting the distinction entirely
  • Forgetting that idempotency is critical in Saga — message redelivery can cause duplicate compensation

Follow-Up Questions

  • What happens in 2PC if the coordinator crashes between Phase 1 and Phase 2? — Participants are in-doubt: they've voted YES and locked resources but don't know the outcome. They block until the coordinator recovers or a timeout+heuristic decision is made.
  • How do you handle idempotency in a Saga? — Each step and compensation must be idempotent — messages may be redelivered. Use idempotency keys, deduplication tables, or check-then-act patterns.
  • When would you choose orchestration over choreography for a Saga? — Orchestration is easier to observe, debug, and reason about for complex workflows with many steps. Choreography is better for simpler, loosely coupled flows where a central orchestrator would be overengineering.
  • Can you achieve read-your-writes consistency with Sagas? — Not trivially — intermediate state is visible. You'd need to track saga state and filter incomplete sagas at read time, or use a 'pending' flag that read paths check.

Related Questions

  • Consistent Hashing
  • Rate Limiting
  • CDN
  • Load Balancer — L4 vs L7
  • Exactly-once Delivery

Can You Explain This Cold?

Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.

Get Graded — Free Assessment
GrindQuestionsAITechnical interview assessment
TermsPrivacyAbout