Skip to content

Sagas and two-phase commit

Two ways to make a change that spans several databases land as a unit: two-phase commit holds everyone's locks until a coordinator decides, while a saga commits step by step and undoes finished steps with compensating actions.

On this page

What it is

A local transaction gives you atomicity, consistency, isolation and durability inside one database. The moment a business operation (place an order, reserve credit, charge the card) touches databases owned by different services, no single database can commit or roll back the whole thing. Two-phase commit and sagas answer that in opposite ways: 2PC keeps the all-or-nothing promise by making participants wait for one decision; a saga drops that wait and accepts that other work can see steps that have committed but may yet be compensated.

Two-phase commit is a protocol between a coordinator and a set of participants. In the first phase (voting, or commit-request), the coordinator sends a prepare message; each participant does its part of the work, writes undo and redo records to durable storage, and votes yes if it could commit or no if it hit a problem. In the second phase the coordinator sends commit if everyone voted yes, and rollback if anyone voted no or the coordinator's timeout ran out. Participants then apply or undo, release their locks and acknowledge.

The cost is in the gap between the phases. A participant that has voted yes has promised to commit, so it keeps its locks and waits for the coordinator's decision; if the coordinator fails for good, that participant stays blocked. Should the coordinator and a participant both fail during the second phase, the survivors may be unable to tell whether the lost participant already committed, so a replacement coordinator has no safe way to finish. This is what people mean when they call 2PC a blocking protocol.

A saga is a sequence of local transactions, each of which commits in its own service and then triggers the next one with a message or event. If a step fails, the saga runs compensating transactions that reverse what the earlier steps did. The idea comes from a 1987 paper on long-lived transactions: a transaction that runs for hours, or pauses for user input, should not hold database resources the whole time, so it is split into smaller transactions that other work can interleave with, and the system promises that either all of them finish or compensations amend the partial run.

A compensation is semantic undo, not a restore. The paper's airline example: if one step reserved a seat, its compensation cancels that reservation, say by subtracting one from the count and running the usual checks. It can't write back the seat count from before the step, because other sagas have reserved and released seats in the meantime. The paper also separates backward recovery, compensating the steps already done, from forward recovery, retrying the missing steps from a save point, which works when each step will eventually succeed if retried.

Kind of stepWhat it meansWhat it needs

Compensable

Can be reversed by a later action with the opposite effect

A written compensation for each one

Pivot

The point of no return; once it succeeds, the saga must run to the end

Everything before it compensable, everything after it retryable

Retryable

Runs after the pivot and is repeated until it succeeds

Idempotence, so a repeat changes nothing

Sagas are coordinated in one of two ways. With choreography, each local transaction publishes an event and the next service reacts to it; there is no central controller. With orchestration, an orchestrator object holds the saga's state, sends each participant a command, reads the reply and decides what comes next, including which compensations to run on failure.

What a saga gives up is the I in ACID. Because each step commits before the next starts, another saga can read a reservation that will be canceled a second later, overwrite an update the first saga is about to compensate, or read different values in two of its own steps. The documented countermeasures are design work: a semantic lock (a status field such as PENDING that tells other sagas an update is in progress), commutative updates that give the same result in any order, reordering the saga so risky updates sit after the pivot, and rereading a value right before writing to confirm it hasn't changed. Two more things follow from the mechanism: a service must update its database and publish its event atomically, which a plain distributed transaction across the database and the broker can't be relied on for, and each retried step must be idempotent. Our suggestion for the second: an idempotency key on each command.

When to use it

Reach for a saga when the operation crosses services that each own their database, when a step can take a long time or wait for a person, and when you can write a sensible compensation for each step before the point of no return. It fits a workflow that has to finish one way or the other without coupling the services to one coordinator's locks. Pick which failure gets which recovery: a transient platform failure (a timeout, a crashed node) is retried and the saga moves forward; a business failure (the card is declined) triggers compensation backward.

Choose choreography for a short workflow with a few services where no coordination logic is needed; it adds no extra component and no single point of failure. Choose orchestration when the workflow is long, branches, or you expect to add services: the flow lives in one place, cyclic dependencies between participants go away, and the participants stay simple, at the price of one more component to run and keep available.

Reach for two-phase commit when all participants sit inside one system you operate, the transaction is short, and you want all participants to commit or none without writing compensations. Microsoft's guidance even suggests choosing by risk: sagas for low-risk updates and distributed transactions for the high-risk ones.

When not to

If the data can live in one database, use one local transaction and skip both patterns. In an interview the first move is to ask whether the service boundary can be drawn so the change is local, because a single ACID transaction is cheaper to build, to reason about and to debug than either protocol.

A saga is a poor fit when the steps are tightly coupled, when a compensation would have to land in a participant that ran earlier in a way that breaks the chain, or when participants depend on each other in a cycle. It is also a poor fit when a step can't be undone and can't be moved after the pivot: a payment to a third party that offers no refund, for example. Compensations can themselves fail, which can leave the system inconsistent, so a saga whose compensations are not well understood isn't safer than no saga.

Two-phase commit is the wrong tool for long-lived work: a participant that voted yes holds its locks until the decision arrives, so anything that pauses for a user or runs for hours keeps conflicting work on those rows waiting. It is also a poor fit across organizations or across services you don't operate, where you can't rely on the coordinator being recovered quickly after a crash.

Compared

QuestionTwo-phase commitSaga

Who decides the outcome

A coordinator, after collecting all the votes

Each step commits on its own; a failure triggers compensations

What is held in the meantime

Locks at each participant until commit or rollback

No database locks across steps; each step's commit is visible to others before the next step starts, and a semantic lock is usually an application-level marker such as a status flag, not a held row

Isolation from other work

The set commits or aborts as a unit; isolation comes from each participant's own locking while it waits

No; other sagas see partial results and may conflict

How a failed run is undone

Automatic rollback from undo logs

Hand-written compensations, one per compensable step

Worst failure

Coordinator lost after yes votes: participants block

A compensation fails: inconsistent until repaired

Weaker-looking option is right when

Participants are one system you run and the transaction is short: an all-or-nothing outcome without hand-written compensations

Steps are long or cross service boundaries: a saga avoids holding locks for a user's think time

In a picture

Create order:pending

Step 1 of 5

The first local transaction

An orchestrator creates the order in a pending state and commits that in the order service's own database. Pending is a semantic lock: other sagas can see this order exists and that it isn't final.

How to say it in an interview

The common mistake

Quiz

In two-phase commit, a participant voted yes and then the coordinator crashed before sending a decision. What does the participant do?
A saga step reserved one seat on a flight that had 40 free. Which compensation is correct?
One step of your saga sends the customer a confirmation email, which you can't take back. Where does it belong?
A checkout workflow has eight steps, branches on the payment method, and gains a new service each quarter. Which coordination fits?

Questions that use this

Related

Sources

  1. microservices.io: Pattern: Saga
  2. Azure Architecture Center: Saga design pattern
  3. Wikipedia: Two-phase commit protocol
  4. AWS Prescriptive Guidance: Saga patterns
  5. Garcia-Molina and Salem, Sagas (1987), full text on the Internet Archive
Sign in to report a mistake