← All Concepts
Distributed Systems

Distributed Transactions

Patterns for maintaining data consistency across multiple services or databases in a distributed system.

**The problem:** In microservices, a business operation may span multiple services, each with its own database. How do you ensure all-or-nothing consistency? **2-Phase Commit (2PC):** 1. Prepare phase: coordinator asks all participants if they can commit 2. Commit phase: if all say yes, coordinator tells all to commit - Problem: blocking, coordinator is SPOF, poor performance **Saga Pattern (preferred):** Break transaction into a sequence of local transactions with compensating actions. **Types:** - **Choreography**: Services emit events, other services react - Pros: loose coupling, simple - Cons: hard to track, can become complex - **Orchestration**: Central coordinator directs the flow - Pros: easier to understand, centralized logic - Cons: coordinator is a dependency **Example (Order Saga):** 1. Create Order → 2. Reserve Inventory → 3. Process Payment → 4. Ship If step 3 fails: Compensate step 2 (release inventory), Compensate step 1 (cancel order) **Key requirement:** Each step must be idempotent (safe to retry).

Common Use Cases

  • E-commerce order processing across services
  • Payment processing with multiple parties
  • Travel booking (flight + hotel + car)
  • Any cross-service business operation

Advantages

  • +Saga: no distributed locking, better performance than 2PC
  • +Saga: each service maintains its own consistency
  • +Orchestration: clear transaction flow and error handling
  • +Compensating actions provide eventual consistency

Disadvantages

  • -Eventually consistent (not immediately)
  • -Compensating actions can be complex to implement
  • -Debugging distributed transactions is hard
  • -Partial failures leave data in intermediate states