# Distributed Transactions & Sagas — System Design

Source: https://www.geekswithgeeks.com/en/system-design/sd-distributed-transactions

> Keeping data correct across services without one shared database.

## Why it's hard

A single-database transaction is atomic for free. Once data lives in separate services with separate databases, you need an explicit protocol to make a multi-step operation succeed or fail as a whole.

## Two-phase commit

**2PC** has a coordinator ask every participant to **prepare** (lock and promise to commit), then, only if all say yes, tell everyone to **commit**. It gives strong consistency but blocks if the coordinator dies mid-flight — poor fit for high-scale, high-availability systems.

## The saga pattern

A **saga** breaks the transaction into a sequence of local transactions, each with a **compensating action** to undo it. If step 4 of 5 fails, you run compensations for steps 3, 2, 1 — no locks held across services, but you design for eventual consistency.

## Prefer sagas at scale

Most large systems (e-commerce checkout, travel booking) use sagas orchestrated by a workflow engine or coordinated via events, reserving 2PC for narrow, low-latency scopes like a single database cluster.
