How it works
A purchase that debits a wallet in one database and claims a seat in another needs both to commit or neither. Two-phase commit (2PC) does this; it is unrelated to two-phase locking. A coordinator asks each participant to prepare, meaning to store the changes durably and promise it can commit. If all vote yes, the coordinator records the decision and tells them to commit. One no, and everyone aborts.
The weak point is the wait. Suppose both databases vote yes and the coordinator crashes before sending the decision. Neither may decide alone, because the coordinator might have decided either way, so seat 14 stays locked until it recovers. One unreachable participant also prevents a commit. Consensus differs: a majority decides, so it continues through a minority of failures. Spanner combines them, running 2PC across Paxos groups so that a coordinator’s decision survives its crash.
Coordination services package consensus for you. etcd and ZooKeeper offer small, strongly consistent stores with watches, leases or sessions, and ordering numbers usable as fencing tokens. Kubernetes keeps its cluster state in etcd. Use one to elect a leader, hold a lock, or publish shard ownership and configuration, not for business data or heavy traffic, since every write passes through a majority. Do not write your own consensus, because its bugs surface only under rare combinations of faults.
You may not need a service. If one Postgres primary is already a hard dependency, a leases table with a token column can be enough, and you accept that it is down when the primary is.
Checkout writes an order to Postgres and must publish an event to Kafka. A teammate suggests two-phase commit across both so they always agree. What do you do instead?
Use a transactional outbox: write the order and an outbox row in one Postgres transaction, and have a relay publish the row to Kafka, retrying until acknowledged. Kafka does not take part in XA, the usual standard for 2PC across systems, so that option is not really there. The outbox also avoids tying checkout’s availability to Kafka’s. Delivery is at least once, so consumers must tolerate duplicates. The costs are a relay to run and a short publication delay.
Use this as a guide for self review; written answers are not graded.Keep in mind
- 2PC needs every participant and can block if its coordinator fails; consensus needs only a majority.
- Use etcd or ZooKeeper for small coordination data, not business records or heavy traffic.
- Prefer a tested service, or your existing database, to writing your own consensus.