Atomic Updates Across Orders, Payments and Inventory Services
System DesignModel answerLast updated
Design a protocol that keeps writes consistent across several services and databases, comparing 2PC, 3PC and Sagas, and covering failures, retries, timeouts and delivery guarantees.
A business operation, such as placing an order, must update several independent systems: an orders database, a payments service and an inventory service. Some are databases you control. Others are third-party services you do not.
Design a protocol that coordinates these updates so that the system always ends in a consistent state: either every update takes effect, or the operation is cleanly undone.
Assumptions you may use or adjust
- Peak load of about 10,000 transactions per second, with 2 to 5 participants each.
- Short cross-shard transactions need p99 latency under 50 ms within a region. Long workflows may run from seconds to days.
- Committed work must never be lost. For money movement, correctness matters more than availability.
- Nodes can crash and recover. Messages can be lost, duplicated or reordered. Network partitions happen.
What to cover
- Requirements and the API the client and participants would see.
- The data you persist on the coordinator and on each participant.
- A comparison of two-phase commit, three-phase commit and the Saga pattern: message flows, failure handling and when each is appropriate.
- How you achieve idempotency, which timeouts you set and where, and what delivery guarantees you can honestly offer (at-least-once versus exactly-once).
- Trade-offs, and which approach you would pick for which scenario.
Hints
Hint 1
Start by separating two problems: a short, strongly consistent cross-shard commit versus a long-running business workflow. They call for different protocols.
Hint 2
For each protocol, ask what happens if the coordinator dies at the worst possible moment, and what a participant that has already voted yes is allowed to do.
Hint 3
Exactly-once delivery is not achievable over an unreliable network. Think about at-least-once delivery combined with deduplication written in the same local transaction as the business effect.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the problem
"Distributed transaction" covers two different needs, and the choice of protocol follows from which one you have:
- Short, strongly consistent commits across databases you control (cross-shard writes). Atomicity and isolation matter, and latency is tens of milliseconds.
- Long-running business workflows across services, some third-party. Locks cannot be held for minutes or days, so isolation is relaxed in exchange for availability.
Failure model: crash-recover nodes, lost, duplicated and reordered messages, and partitions. This asynchronous model decides what is safe.
2. Interfaces
Client:
POST /txn(with a client idempotency key) returnstxn_id.POST /txn/{id}/commitis idempotent.GET /txn/{id}returns overall and per-participant state.
Participant, 2PC style: prepare, commit, abort. Participant, Saga style: execute(step) and compensate(step). Every call carries (txn_id, step_id) as its idempotency key.
3. Data model
- Coordinator log:
txn_id, state (INIT, PREPARING, COMMITTED, ABORTED, DONE), participant list, decision, deadline. Stored in a replicated store (Raft/Paxos group or a Spanner-like system) so the coordinator is not a single point of failure. - Participant log: local state (PREPARED, COMMITTED, ABORTED), redo/undo data, held locks.
- Dedup table per participant:
idempotency_key -> result, written in the same local transaction as the business change. - Outbox table: events written atomically with local state and relayed to a message bus.
Coordinator workers are stateless. Any worker can resume a transaction from the log, and a recovery sweeper drives overdue transactions to completion.
4. Two-phase commit
- The coordinator logs PREPARING and sends PREPARE.
- Each participant durably persists its changes and a PREPARED record, keeps its locks and votes YES. Otherwise it aborts locally and votes NO.
- If all vote YES, the coordinator force-writes COMMIT. This write is the commit point. It then sends COMMIT. Any NO or timeout means ABORT.
- Participants apply the decision, release locks and ACK. The coordinator then marks the transaction DONE.
| Failure | Response |
|---|---|
| Timeout before a decision | Abort (always safe) |
| Participant crashes before voting | Counts as NO |
| Participant crashes after PREPARED | On restart it asks the coordinator; it cannot decide alone |
| Coordinator crashes after collecting YES | Participants block holding locks until recovery |
The last row is the core weakness. Mitigations: replicate the coordinator with consensus (as Spanner and Paxos Commit do), so a single crash does not block anyone. Use presumed abort (no log record means abort) to save writes, and let read-only participants skip phase 2. The cost is holding locks across about two round trips plus consensus writes, which fits a 50 ms p99 within a region but not across the world.
5. Three-phase commit
Flow: CanCommit, then PreCommit, then DoCommit. The extra phase ensures no one commits until everyone knows all votes were YES, so after a coordinator timeout the survivors can elect a new coordinator: if anyone reached PreCommit they commit, otherwise they abort.
The catch is that this is non-blocking only with fail-stop crashes and bounded message delay. Under a partition, one side may commit while the other aborts, breaking atomicity. It also costs an extra round trip. Consensus-replicated 2PC gives non-blocking behavior that stays safe under partitions, so 3PC is rarely used in practice.
6. Saga
A saga is a sequence of local transactions T1..Tn, each with a compensation Ci. If Tk fails, run Ck-1..C1 in reverse.
- Orchestration: a central, persisted state machine (Temporal or Cadence style) issues commands and records results. It is easier to observe, time out and debug. Prefer it for complex flows.
- Choreography: services react to each other's events via outboxes. There is less infrastructure, but the flow is implicit and cycles are hard to diagnose.
Failure handling:
- Retry transient step failures with exponential backoff and jitter until a deadline, then compensate.
- Compensations must be retried until they succeed, so design them to always be applicable (a refund rather than a delete).
- Put steps that cannot be undone (shipping, emails) last, after a pivot point.
The main trade-off is no isolation: other transactions see intermediate states. Mitigate with semantic locks (such as an order status of PENDING), commutative updates and re-reading values before acting.
7. Idempotency, timeouts and delivery
Idempotency
- Insert the idempotency key into the dedup table in the same local transaction as the effect. A duplicate returns the stored result.
commitoraborton an already-decided transaction is a no-op.abortfor an unknowntxn_idwrites a tombstone so a lateprepareis rejected.
Timeouts
- Coordinator in the prepare phase: short and bounded (about 100 ms to 1 s), then abort.
- A prepared participant must never time out into a unilateral decision. It keeps asking the coordinator or its replicas.
- Saga steps: per-step deadline plus an overall deadline. Compensation has no deadline, only retries and alerting.
Delivery guarantees Exactly-once delivery is impossible over an unreliable network. What you build is at-least-once delivery plus idempotent processing, which gives exactly-once effect. Use the outbox pattern so state changes and events commit atomically, and a relay publishes them with retries.
8. Choosing
| Scenario | Choice |
|---|---|
| Cross-shard writes in databases you control, need isolation | 2PC with a consensus-replicated coordinator |
| Long workflows, third-party services, no lock holding | Orchestrated Saga |
| Partitions expected, atomic commit required | Not 3PC; use consensus-based commit |
9. Common mistakes
- Claiming exactly-once delivery instead of exactly-once effect.
- Letting a prepared participant abort on its own after a timeout.
- Writing the dedup record outside the local transaction, which reopens a duplicate window.
- Compensations that can fail permanently or are not idempotent.
- Presenting 3PC as the fix for blocking without mentioning partitions.
- Ignoring the lack of isolation in sagas.