Skip to main content

Preview — Pro guide

You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.

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.

42 min read 2 sections 1 interview questions
Distributed TransactionsTwo-Phase Commit2PCSaga PatternCompensating TransactionsEventual ConsistencyChoreographyOrchestrationMicroservicesDistributed SystemsCAP TheoremIdempotency

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:

  1. Two-Phase Commit (2PC): strong consistency, synchronous, requires a coordinator
  2. Saga pattern: eventual consistency, asynchronous, uses compensating transactions
IMPORTANT

Premium content locked

This guide is premium content. Upgrade to Pro to unlock the full guide, quizzes, and interview Q&A.