Commit across two stores
A single operation must succeed in two databases or neither.
Say it like this
Debiting the wallet and reserving the seat live in two databases, so rather than a blocking two-phase commit I use a saga with compensation, and reserve 2PC for the rare case where a visible intermediate state is unacceptable.
Basic solution
Two-phase commit with a coordinator: prepare on all, then commit on all. Prefer avoiding it via sagas or outbox.
Prepare, then commit, with locks held throughout
The coordinator collects yes votes, writes its commit record, then tells both participants to commit. Between prepare and commit both databases hold locks and depend on the coordinator being alive.
How it works
- A coordinator process receives a transaction that must change data in two or more resource managers, meaning separate databases or message brokers that each have their own transaction log.
- Phase one, prepare: the coordinator asks each participant to do the work and durably promise it can commit. Each participant applies the changes to its own storage, writes a prepared record plus its yes vote to its log with an fsync, keeps the row locks it took, and replies yes. A participant that cannot do the work replies no.
- If every participant votes yes, the coordinator writes a commit record to its own log and fsyncs it. That record is the point of no return: from here the transaction will commit even if the coordinator crashes, because the record survives.
- Phase two, commit: the coordinator sends commit to each participant; each one marks the transaction committed in its log and releases its locks. If any participant voted no, the coordinator sends abort instead and each participant rolls back its prepared changes.
- A participant that crashes after voting yes cannot decide on its own after restart, because it does not know whether the others voted yes. It must ask the coordinator what happened and keep its locks until it hears back.
- The coordinator must itself be durable and highly available, otherwise every participant waiting for its decision stays blocked with locks held.
What it guarantees and what it costs
- Atomic across stores: all commit or none.
- Two round trips and several fsyncs per transaction, locks held across both, and a coordinator that becomes the availability floor of the whole system.
Worked example
Ride matching, charging the rider and starting the trip
- A trip start touches the payments database (place a hold on the card) and the trip database (set state to in_progress). 200 trip starts per second at peak.
- With 2PC: prepare on both (about 5 ms each including fsync), coordinator commit record (3 ms), commit on both (5 ms). Roughly 20 ms per trip with row locks held in both databases the whole time. Any coordinator hiccup leaves hundreds of rows locked in both databases, blocking unrelated transactions that touch them.
- With a saga: write the trip as pending (3 ms), call payments to place the hold (10 ms), set the trip to in_progress (3 ms). If the hold fails, set the trip to failed. Each step is a local transaction; nothing is locked across services. The intermediate state pending is visible to anyone reading the trip, which the product already tolerates because the app shows a confirming screen.
- Error budget: the saga has a window of a few hundred milliseconds where the hold exists and the trip is still pending. If the service crashes in that window, a hold remains with no trip. A reconciliation job that runs every minute finds holds without trips and releases them, so the worst case is a hold on a card for about a minute.
- Decision: saga. 2PC would be chosen only if a pending trip visible to drivers were a product bug, which it is not.
Variants and when each wins
Classic 2PC (XA)
- The protocol as standardised, supported by most relational databases and message brokers through XA drivers. It wins only when both resources are inside one trusted system and you accept that a dead coordinator freezes participants with their locks held.
Three-phase commit
- Adds a pre-commit phase so participants can decide without the coordinator if it dies, at the cost of a third round trip. It is rarely used because its guarantees weaken under network partitions, which is exactly when you would need them.
Saga with compensation
- A sequence of local transactions, each with an undo action that reverses its business effect. It wins across independently owned services because no locks are held between them; the cost is that intermediate states are visible and a compensation is a new action, not a true rollback.
Transactional outbox plus idempotent consumer
- Write the local change and an event row in one local transaction; a relay publishes the event; the other side applies it and ignores duplicates. It wins when the second system only needs to eventually reflect the first, giving atomicity without any coordinator.
Single-database transaction (avoid the problem)
- Put the two tables in the same database and use one ordinary transaction. It wins more often than people admit, because the split into two databases was premature.
Recommendation: a single database if you can, the outbox or a saga if you cannot, and 2PC only inside one trusted system such as a distributed SQL engine that implements it for you.
Failure modes
Coordinator dies after prepare
- You notice rows locked in two databases for minutes, with every other transaction that touches those rows waiting behind them. It happens because the participants voted yes and are now in doubt: they cannot commit or abort on their own until the coordinator tells them the outcome. Run the coordinator with a replicated log and fast failover so the decision is recoverable in seconds, or avoid 2PC altogether.
Heuristic decisions
- You notice one database committed a transaction and the other rolled it back, so a hold exists with no trip. It happens because an operator or a timeout forced an in-doubt participant to decide alone, and it guessed differently from the other. Run reconciliation jobs that detect and repair the mismatch, and treat every heuristic outcome as an incident to investigate.
Throughput ceiling
- You notice the coordinator saturating at a few thousand transactions per second however many participants you add. It happens because each transaction needs a commit record fsync on the coordinator plus two round trips, and that serial work sets the ceiling. Batch commit records so one fsync covers many transactions, or partition the data so most transactions touch one store and skip 2PC.
Locks held across a network
- You notice deadlocks and lock-wait timeouts between transactions that have nothing to do with each other. It happens because prepare holds row locks until phase two completes, and a slow network stretches that window across many other transactions. Keep prepared transactions tiny and short, or move to a saga so no lock spans a network call.
Saga compensation fails
- You notice a card hold that was never released days after the trip failed. It happens because the undo step itself errored, and nothing retried it. Make every compensation idempotent and retry it until it succeeds, with an alert on sagas stuck in compensating for longer than a few minutes.
Interviewer follow-ups
Answer out loud before you open each one.
Why is 2PC called a blocking protocol?
After voting yes a participant has promised to commit and cannot change its mind, so if the coordinator disappears the participant must hold its locks and wait, possibly forever. Nothing in the protocol lets it decide safely on its own.
How does a saga differ from a rollback?
A rollback makes it as if the transaction never happened. A compensation is a new forward action that undoes the business effect, such as refunding a charge, and the original state was visible to others in between. You design each step knowing it may be compensated.
When is 2PC the right choice?
When a visible intermediate state is unacceptable and both resources are inside one system you control with a highly available coordinator, such as a distributed SQL database doing it internally across its own shards. Across independently owned services it is almost never the right choice.
How would you do the wallet debit plus trip start without either 2PC or visible inconsistency?
Put both in one database if the domains allow it. Otherwise reserve first: place the hold, then write the trip with the hold id in one local transaction, and release orphan holds by reconciliation. The order is chosen so the failure mode is a harmless unused hold, never a trip without a payment.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Trip service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Payments DB, Trip DB | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |