One order, many services
An order touches payments, stock and delivery, and each has its own database. The card was charged, then the stock step failed, and now a customer has paid for nothing.
Play this levelPart of Bugpit Pro. It runs in your browser: build the design, press Run, and watch what breaks.
The lesson
A single database gives you a transaction: everything happens, or nothing does. Once data lives in separate services, no single transaction covers them all.
Two phase commit makes every service vote, then commit together. It's correct, but everyone waits on everyone, so one slow service holds up the rest.
A saga is a chain of small local steps. If a step fails, earlier steps are undone by compensating actions, such as refunding a card.
Sagas are eventually consistent: for a moment the order is half done. Show that honestly with a status like "processing". Messages can also repeat, so every step must be safe to run twice.
The outbox pattern stops messages going missing: save the change and the message in one local transaction, and let a worker send the message afterwards.
What you have to achieve
4,000 requests a second at the busiest hour, 10% of them writes.
- No broken or illegal connections
- Use a Queue
- Use a Worker
- No component is overloaded
- Workers clear the queue within the day
- Fewer than 0.1% of requests fail
- p99 response time under 250 ms
What you learn
The order now moves through a queue, step by step, and a failure can be undone. You traded instant, all at once correctness for a system where one slow service can't hold everything up.
Check yourself
The card was charged, but reserving stock failed. What does a saga do next?
- Retry forever
- Run a compensating action and refund the card
- Ignore it
Show the answer
Run a compensating action and refund the card. There's no shared transaction to roll back, so each finished step has its own undo.
Why might you avoid two phase commit across services?
- It can lose data
- It holds everyone up while they wait for each other
- It only works on Mondays
Show the answer
It holds everyone up while they wait for each other. All the services hold their locks until everyone has voted, so one slow service slows the rest.
A queue may deliver the same message twice. What must each saga step be?
- Idempotent: safe to run twice
- As fast as possible
- Written in one language
Show the answer
Idempotent: safe to run twice. If a step is idempotent, a repeated message has no extra effect. Nobody gets charged twice.
What does the outbox pattern protect against?
- Spam email
- Saving a change but never sending its message
- Slow databases
Show the answer
Saving a change but never sending its message. The change and the message are saved in one transaction, so you can't end up with one and not the other.