Distributed transactions and sagas¶
What you'll be able to do¶
- Explain why an operation spanning several services cannot be one ACID transaction, and what "atomic" can mean there.
- Trace two-phase commit and a saga through a failure, and say what each guarantees and where each breaks.
- Design a saga that survives crashes: idempotent steps, durable state, an outbox, timeouts.
The problem: one operation, several owners¶
Placing an order touches an inventory database, a payment provider, and a shipping service. Inside one database, BEGIN ... COMMIT gives atomicity (see indexes and transactions). A transaction opened on one database does not cover another service or an external payment API. Cooperating resource managers can use a distributed commit protocol, but ordinary service calls do not join it automatically.
As a toy calculation, assume each call fails independently 1% of the time, a failed call has no side effect, and we stop at the first failure. All three succeed with probability 0.99 × 0.99 × 0.99 = 0.970299. A failure at the first call leaves nothing behind (0.01). Everything else is a half-finished order: 1 − 0.970299 − 0.01 = 0.019701, about 2 in 100 orders with stock reserved or a card charged but no shipment.
Two common approaches are to commit together (two-phase commit), or to commit locally and repair afterwards (sagas).
Two-phase commit (2PC)¶
A coordinator drives several participants, each with its own local transaction:
- Prepare. A participant that votes yes has durably recorded that it can commit and keeps its locks. It has promised not to change its mind. No means it aborted locally.
- Commit or abort. If every vote is yes, the coordinator writes "commit" to its own durable log, the commit point, then tells everyone. Before logging a commit decision, the coordinator may decide abort if any participant votes no or fails to respond during prepare. After a yes vote, a participant must wait for the logged decision.
The guarantee is atomic commit: all participants commit or none do, if crashed nodes recover from their logs. The costs:
- Blocking. If the coordinator dies after the votes but before the decision arrives, a prepared participant can neither commit (the decision may have been abort) nor abort (it may have been commit). It is in doubt, holding locks until the coordinator returns. The lab reproduces this.
- Locks and latency. Locks stay held across both phases, including network trips and durable writes, paced by the slowest participant.
- Availability coupling. Commit needs every participant up. Three services at 99.9% each, failing independently, give 0.999³ ≈ 0.997: roughly 26 hours of unavailability a year instead of about 9.
2PC is real inside a boundary you control, such as a database coordinating its own shards, or systems that replicate coordinator state with consensus. XA is the standard interface for a transaction manager to coordinate separate resource managers; know the name, but avoid it between independent services; an external payment API will not take part.
Sagas: local transactions plus compensations¶
A saga is a sequence of local transactions, each committed immediately. Each undoable step has a compensating action. If step n fails, run the compensations of steps n−1 … 1 in reverse.
A compensation semantically undoes the earlier action; it is not a rollback. The charge happened; a refund follows it. Step 3 gets no compensation because it was definitely rejected, so it had no effect.
A lost reply or a timeout is different: the outcome is unknown, and the effect may have happened. Do not record it as failed. Retry or query with the same idempotency key until you know; if it happened and the saga aborts, compensate it too. A compensation must treat "nothing to undo" as success.
Some effects have no inverse: a sent email, shipped goods. Steps before the pivot (the step that commits the saga to going forward) must be compensable. Steps after it are retryable: retry transient failures until they succeed, and give permanent failures an explicit repair or manual intervention path. Here shipment is the pivot and the email follows it. Put hard-to-undo work late.
| Orchestration | Choreography | |
|---|---|---|
| Who knows the flow | One orchestrator holds steps and state | Each service reacts to events and emits the next |
| Visibility | Progress in one place | Flow spread across services |
| Coupling | Services take commands | Services depend on each other's events; cycles creep in |
| Fits | Longer flows, branches, timeouts | Two or three simple steps |
What a saga does not give you¶
A saga aims for a completed workflow or a business-level compensated outcome. Compensation can fail, and it cannot erase effects others already observed. Nor does a saga provide isolation: another customer may see stock reserved by an order that is later canceled. This is an intermediate committed state, not a database dirty read. Concurrent sagas can also overwrite each other. Countermeasures:
- Semantic lock: a flag such as
status = PENDINGmarking a row as tentative. - Commutative updates: where order truly does not matter (an unbounded counter), write deltas, not absolute values. Stock is bounded: use atomic, conditional updates, tie each release to an existing reservation, and do not assume reordering preserves capacity.
- Reordering: put steps with visible or irreversible effects last.
Making a saga survive reality¶
Reliability is the real work, resting on delivery and idempotency and timeouts and retries.
- Idempotent steps and compensations. The orchestrator can crash after a service did the work but before recording it, then re-send the step on resume. Derive a stable key such as
order-17:charge(andorder-17:charge:undo). A compensation may run many times and must succeed when there is nothing left to undo. - Durable saga state. Keep rows, not memory; the lab uses a log.
CREATE TABLE saga (id text PRIMARY KEY, status text, deadline timestamptz);
CREATE TABLE saga_step (saga_id text, step text, status text,
PRIMARY KEY (saga_id, step)); -- pending/done/failed/unknown/compensated
- Outbox. Saving state and sending the next command are two writes. Commit the state change and the outgoing message in one local transaction and let a relay publish it. Delivery is at least once; receivers deduplicate.
- Timeouts and stuck sagas. Give each saga a deadline and run a sweeper. A timeout means you did not hear back, not that the step failed, so retry with the same key before compensating. If compensation keeps failing, alert a person.
- Observability. Put the saga id on every log line. Track counts by status and the oldest unfinished saga's age. See observability.
Alternatives, and picking a consistency level¶
First, avoid the problem. If data must always change together, ask whether it belongs in one service and one database; see microservices. Otherwise:
- Reconciliation. A job compares systems (your orders against the payment provider's settlement report) and flags differences. A safety net under any design.
- TCC (try, confirm, cancel). Try places a tentative hold, confirm makes it final, cancel releases it. Give the hold an expiry or a recovery path so abandoned tries do not remain forever. A card authorization followed by a capture has this shape. Participants must be built for it.
- Event sourcing. Storing changes as events can drive saga steps, but brings event versioning and rebuilding of derived views. Adopt it for audit and replay, not just transactions. (CQRS, separate write and read models, is a different idea and does not require it.)
Pick a consistency model per operation:
| Model | Promise | Example fit |
|---|---|---|
| Strong | Reads see the latest committed write | Reading a newly committed value |
| Causal | If B was caused by A, everyone sees A first | A reply never appears before its comment |
| Read-your-writes | You see your own updates | Editing a profile, then reloading |
| Eventual | Replicas converge if writes stop | View counts, search index, feeds |
A fresh read does not make a later write safe: two clients can read the same balance and both debit. A balance check and debit require one atomic conditional update or transaction.
For AI engineers
An agent run with side effects (create a ticket, send an email, charge a card) can be designed as a saga, and can die halfway. Persist each known result, but assume a crash can occur before that write. Retry the same tool operation with a stable idempotency key (run id plus step) that the tool or service honors, or reconcile its outcome before proceeding. Put irreversible actions last, behind a human approval, and write compensations where they exist (close the ticket). Add per-tool timeouts and a sweeper for stuck runs.
Pipelines need atomic publish too: write data files to a staging location, then atomically publish a manifest or version pointer in a way the storage system supports; readers use only published versions. See agent reliability.
Common mistakes¶
- 2PC across independent services. One slow participant stalls everyone.
- Non-idempotent compensations. A retried refund that refunds twice is a new bug.
- No persisted saga state. A restarted orchestrator forgets what to undo.
- Assuming compensation always succeeds. Retry, then alert a human.
- Ignoring isolation. Readers see pending state; use semantic locks.
- A saga where one database would do. Keep co-owned data in one transaction.
Check yourself¶
The coordinator crashes after all participants voted yes but before it logged or sent a decision. What state are participants in, and what should a recovery coordinator do?
They are prepared (in doubt) and hold locks; they cannot abort alone, since the decision might have been commit. The recovery coordinator finds no logged decision, so the commit point was never reached: it logs abort and tells everyone. Had "commit" been logged, it would re-deliver commit.
An order saga runs reserve stock, charge card, create shipment, send email. Shipment fails. Which compensations run, in what order? What if the email fails after shipment succeeded?
Refund the card, then release the stock; shipment gets none, assuming it definitely failed (if unknown, resolve that first). An email failure comes after the pivot, so the order is not rolled back: retry transient failures, and send a permanent one (an invalid address) to repair or manual handling.
The orchestrator calls the payment service, which charges the card, then crashes before saving "charge done". On restart it re-sends the charge. What prevents a double charge?
An idempotency key derived from saga and step (order-17:charge): the payment service remembers it and returns the earlier result. The orchestrator cannot know the first attempt happened, so safety must come from the receiver.
Lab¶
You will build a toy two-phase commit coordinator, a saga orchestrator with compensations, and idempotent calls, over in-memory fakes with injectable failures. The tests count real side effects, so a double charge fails. They also separate a definite rejection from a lost reply, which must never be reported as compensated. The code is in code/distributed-transactions/. Run: cd code/distributed-transactions && PYTHONPATH=starter python -m pytest tests -q Done means all tests pass, including a resumed saga that charges once.
Go deeper¶
- Interactive: Designed to Scale – sagas, transactions
- Your handbook: Software Engineering Handbook, ch. 7 "CSDL quan hệ (index, query, transaction)"; in your Atlas, the case combining CQRS with sagas.
- Atomic commit and consensus: Kleppmann's Cambridge course and MIT 6.824.
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.
