Tiếng Việt · English
Why saga instead of 2PC
A booking at dine has to get three things done: hold a table, take ingredients from the kitchen stock and collect the money. These three jobs live in three different services, each with its own database. The requirement sounds simple: either all three happen, or none of them counts. The first question everyone asks: why not wrap all three in one transaction and be done with it?
If there were only one database
When everything lives in one database, the answer is built in:
BEGIN → hold the table → take the stock → record the payment → COMMIT
If any step fails, ROLLBACK, and the database wipes everything clean as if nothing happened.
While the transaction runs, nobody else sees the half-done state either (the I, isolation, in ACID).
But dine is split into several services, and each service owns its data (database-per-service): the table service may not write straight into the kitchen's database. A single transaction cannot span three different databases. If you want "all or nothing", you need a coordination protocol on top.
What two-phase commit does
Two-phase commit (2PC) is the classic way to stretch one transaction across several databases. A coordinator runs two phases:
- Prepare. The coordinator asks each participant: "Are you sure you can do this?". Each one does its work but does not commit; it writes enough to survive a restart, keeps its locks on the affected rows, and answers "yes" or "no".
- Commit. If everyone says "yes", the coordinator orders a commit. A single "no" and everyone rolls back.
On paper this is exactly what we want: truly atomic, no in-between state.
MySQL even supports it out of the box with XA PREPARE / XA COMMIT.
The trouble is what happens between the two phases.
Why 2PC does not fit dine
1. Locks are held for as long as the slowest participant
From prepare until commit, every participant holds its locks. Table 7 is locked and nobody else can book it, just because the payment gateway takes 3 seconds to answer. The lock time of every participant equals the time of the slowest one, plus a network round trip. At peak hours, with many orders competing for a few free tables, these locks queue up behind each other.
2. A coordinator that dies between the phases leaves everyone stuck
This is the most famous weakness of 2PC: it is a blocking protocol. Once a participant has answered "yes" in the prepare phase, it may no longer decide on its own. It does not know what the others answered, so it dares neither commit nor roll back. If the coordinator dies at that moment, the participant sits in doubt, holding its locks, waiting for the coordinator to come back. That may take a few seconds, or it may last until someone steps in by hand.
3. Everyone must be up at the same time
2PC only succeeds when all three services and the coordinator are working at the same moment. If each service is available 99.9% of the time, all three together are available only about 99.7%. Every service you add pushes that number down. One service restarting for a deploy is enough to make every new order fail.
4. Not everything can take part in 2PC
To join 2PC, a participant must support "prepare, then wait for orders". Databases can. But dine's services talk to each other through Kafka, and Kafka does not join an XA transaction together with MySQL. Real life is harder still: no payment gateway or bank API will ever let you "charge tentatively, hold it, and I'll tell you later whether to commit". Once the API says "success", the money has gone.
In short: 2PC trades availability and speed for immediate consistency. For a few databases sitting side by side with short transactions, that can be a fair trade. For independent services talking through messages, with outside parties involved, the price is too high.
What a saga uses instead
A saga drops the idea of "one big transaction". Instead it splits the work into a chain of local transactions; each step is committed right away by one service in its own database. In return, every step needs a matching compensating step (compensation): a business action that cancels out the effect of that step.
| Step | Service | Compensation |
|---|---|---|
| Hold the table | reservation | Release the table |
| Take the ingredients | kitchen | Return the ingredients to stock |
| Collect the money | payment | Refund |
Compensation is not a rollback. A rollback means "as if it never happened". Compensation means "it happened, and now we do one more thing to balance it out". Money that was taken cannot have its history line deleted; it can only be refunded, and the customer will see both transactions on the statement. This is the most important difference when moving from transactions to sagas (the article Compensation is not rollback covers this in depth).
How dine runs an order
dine uses orchestration: the order service acts as the coordinator
and holds the whole saga state. The other three services only take commands, do their part
and report back; they don't need to know the big picture.
- Create the order.
orderwrites the order, the saga state and an "order created" message into the outbox table, in the same transaction of its own. There is never an order without a saga tracking it, and never a message for an order that does not exist. - Send the commands. A background process reads the outbox table and pushes the message to Kafka.
- The three services work in parallel. Table, kitchen and payment don't wait for each other. Each one commits its own work and replies "done" or "failed".
- All three "done": the order is confirmed.
- One "failed", or one silent for more than 5 seconds:
ordercancels the order and sends compensation commands to the services that already finished.
At no point does one service hold a lock while waiting for another. If the payment service dies, the message waits in Kafka. When it comes back, the work picks up where it left off.
The price you pay
A saga is not free. It only moves the complexity from the database into your code.
No isolation: others see the in-between state
The table is held as soon as reservation commits, even though the payment is not done yet.
If the payment then fails, the table is released. For those few hundred milliseconds,
anyone looking at the seat map sees the table as taken. That is why orders at dine have a
"processing" state rather than just "done" or "failed", and why on the Seats page you sometimes see a table taken and then free again.
The system is eventually consistent, not immediately consistent.
You write the compensations yourself, and they can fail too
Every step you add is one more compensation to write and test. Worse, a compensation is also a call over the network, so it can fail as well. What if the bank refuses the refund? You cannot keep "compensating the compensation" forever. dine chooses to stop and wait for staff to handle it by hand, because this is money, and retrying blindly is more dangerous.
Messages arrive late, or twice
Kafka delivers messages at least once: a message may arrive twice, or after
order has already made up its mind. Example: payment reports a failure first, the order is cancelled at once,
and only then does the kitchen report "done". The kitchen really did take the stock, so order has to recognise
this as a "late success" and send a separate command to return the stock. Every service must also be
idempotent: receiving the same command twice gives the same result as receiving it once.
Harder to follow
An order is now a chain of events spread over four services. Without a tracing tool you can hardly tell where an order is stuck. That is exactly why the diagram on dine's order detail page was built.
| 2PC | Saga | |
|---|---|---|
| Consistency | Immediate | Eventual |
| In-between state visible | No | Yes |
| Locks held across the network | Yes, until the slowest participant answers | No |
| One participant dies | Every order fails or gets stuck | Orders wait and continue when it comes back |
| Undo | The database rolls back | You write the compensations |
| Works with Kafka, external APIs | No | Yes |
When 2PC is still the right choice
A saga is not always better. If everything lives in one database, just use a normal transaction; don't split it up and make life complicated. If you have a few databases of the same kind side by side, short transactions, and a business that cannot accept anyone seeing an in-between state (for example an internal transfer between two accounts), 2PC is still worth considering. A saga fits when the steps live in independent services, outside parties are involved, and the business accepts "undoing with a new action".
See it for yourself
Each sample order below takes exactly one of the branches described in this article, with a diagram of when each service replied.
- Failure after others finished Table and kitchen have committed, payment refuses: the 2 finished services are compensated.
- Early failure, others finish late The order is already cancelled when a service reports "done": the late success is compensated on its own.
- One service goes silent The kitchen never replies: after 5 seconds the order is cancelled and undone, nobody waits forever.
- Refund fails The compensating step fails too: everything stops and waits for a person.
To cause trouble yourself, log in, press Book a table and turn on “Incident test”: choose the order in which the services reply, make one service go silent, or have the payment declined.
Spotted a mistake, or have a question? Write to [email protected].
dine is a personal project about distributed systems, written in Go: orchestrated sagas, transactional outbox, Kafka. More articles.