Distributed transactions: 2PC, sagas and the outbox
Two-phase commit and why it blocks, sagas with compensations, and the transactional outbox that fixes the dual-write problem between a database and a queue.
35 min8 steps
By the end you can
- Explain how two-phase commit reaches atomic agreement, what it costs, and why it blocks when the coordinator fails after prepare
- Design a saga with compensations in the right order and place irreversible steps last
- Explain the dual-write problem and how the transactional outbox and idempotent consumers solve it
- Choose between a local transaction, 2PC and a saga for a cross-service workflow
One business action, several databases
Atomic commit (2PC)
- Commit or abort together
- Locks held throughout
Saga
- Commit each step locally
- Undo with compensations
- No isolation
Naive sequence
- Flight booked, hotel call fails
- Left half done
Two-phase commit
Loading question…
Why 2PC blocks
Set Transaction protocol to Two-phase commit and select coordinator crash after prepare in Script.
Loading question…
The in-doubt participant
Already voted yes
- Keep locks and wait
- Cannot unilaterally abort or commit
Not voted yet
- May abort
- No commit was possible without its vote
Set Transaction protocol to Two-phase commit, select coordinator crash after prepare in Script.
Sagas: local commits and compensations
T1
Reserve flight
T2
Reserve hotel
T3
Reserve car
T4
Charge card fails
C3, C2, C1
Undo in reverse
Loading question…
Order the compensations, place the irreversible step last
Before the pivot
- Can fail
- Needs compensation
Pivot
- Cannot be undone
- Ship parcel, send wire
After the pivot
- Retry until success
- Cannot fail for good
Set Transaction protocol to Saga and select saga failure and reverse compensation in Script.
A trip saga reserved the flight, then the hotel, then the car. Charging the card fails. Put the recovery in order.
- 1The card charge fails and its local transaction rolls back
- 2Mark the saga as compensated and notify the customer
- 3Cancel the hotel reservation
- 4Cancel the car reservation
- 5Cancel the flight reservation
The dual-write problem and the outbox
Set Transaction protocol to Transactional outbox and select transactional outbox in Script.
Check your mastery, then redeliver
Kill consumer
redelivery
Dedup store, same seed
no duplicates
Score 80% or more. In the sandbox, publish from a service to a queue into a database, kill the consumer, then add dedup and rerun.
Mastery check
5 questions on fresh variants. One attempt each, no time limit. Score 80% or more to master the lesson.
Answer this step to continue.