Preview — Pro guide
You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.
Sections
Related Guides
Event Sourcing and CQRS: Audit Logs, Temporal Queries, and Read/Write Separation
High-Level Design
Consistency Models: Strong vs Eventual vs Causal, Linearizability, CRDTs & CAP Theorem
High-Level Design
Distributed Systems Patterns
High-Level Design
Message Queues & Streaming: Kafka, Delivery Semantics, and Consumer Groups
High-Level Design
Design a Payment System (Stripe-style Processor)
High-Level Design
Distributed Transactions: 2PC, Saga Pattern, and Compensating Transactions
Distributed transactions coordinate state changes across multiple services or databases. Two-Phase Commit (2PC) provides strong consistency but sacrifices availability. The Saga pattern achieves eventual consistency through compensating transactions — the approach used by Uber, Amazon, and Stripe for multi-step business workflows. This guide covers both models, their failure modes, and when each applies.
The Distributed Transaction Problem
A local transaction on a single database is ACID: either all changes commit or all roll back. This is guaranteed by the database's transaction log and lock manager.
The problem: in a microservices system, a business operation spans multiple services with separate databases. An e-commerce order requires:
- Inventory service: reserve 1 unit of SKU-123
- Payment service: charge $89.99
- Order service: create order record
- Notification service: send confirmation email
All four must succeed or none should. If payment succeeds but inventory reservation fails, the customer is charged for an item that can't be shipped. If all succeed but the order record fails to write, the customer has no order to track.
There is no "global database transaction" that wraps all four — each service owns its own datastore. This is the distributed transaction problem.
Two solutions dominate production systems:
- Two-Phase Commit (2PC): strong consistency, synchronous, requires a coordinator
- Saga pattern: eventual consistency, asynchronous, uses compensating transactions