Boss lesson · Unit 04
One order, three services
Two-phase commit, sagas and the outbox
What you practise
- Two-phase commit and its blocking problem, sagas with compensating actions, the outbox pattern for "write to the database and publish an event", choosing between them
Try a question from this lesson
Pick one
An order charges a card in the Payments service, then reserves stock in Inventory. Each has its own database. The charge succeeds; Inventory says out of stock. Now what?
Correct answer
The customer is charged for nothing until the charge is undone
Why
There is no shared transaction to roll back: the charge already committed in another database. Something must notice the failure and undo the charge explicitly. This lesson is about doing that reliably.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Two-phase commit
Two-phase commit (2PC) makes several databases commit as one. A coordinator first asks every participant to prepare. A participant that votes yes promises it can commit, and holds its locks.
If all vote yes, the coordinator tells everyone to commit. If anyone votes no, everyone aborts.
coordinator A B
|--- prepare? --->| |
|--- prepare? ------------>|
|<-- yes ---------| |
|<-- yes ------------------|
|--- commit ----->| |
|--- commit -------------->|Concept
Sagas
A saga gives up the single big transaction. It is a chain of small local transactions, and each commits at once in its own service.
If a later step fails, the saga runs a compensating action for every step already done, newest first: refund the charge, release the stock.
Nothing is locked across services, but others can briefly see the half-finished state.
Concept
The outbox
The outbox pattern turns the two writes into one. In the same local transaction that saves the order, the service also inserts the event into an outbox table.
A separate relay reads the outbox, publishes each event to the queue and marks it sent. If the relay crashes midway it publishes again, so delivery is at-least-once.
BEGIN
insert order
insert event into outbox
COMMIT <- one local transaction
relay: outbox -> publish -> mark sent9 more exercises in the app
- 1× order the lines
- 1× true or false
- 5× multiple choice
- 1× fill the blanks
- 1× type the answer
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.