Two Phase Commit: How It Works and When to Use It
two phase commit is a protocol used to ensure all parts of a distributed system agree to complete a transaction together or none at all. It works by coordinating a prepare phase where participants vote, followed by a commit phase where the transaction is finalized if all agree.How It Works
Imagine you and your friends want to decide on a restaurant together. First, you ask everyone if they agree on a place (this is the prepare phase). If everyone says yes, then you all go to that restaurant (this is the commit phase). But if even one friend says no, you all decide not to go anywhere.
In two phase commit, a coordinator asks all the systems involved if they are ready to commit a change. Each system replies with a yes or no. If all say yes, the coordinator tells everyone to commit the change. If anyone says no, the coordinator tells all to roll back and not make any changes. This way, the system stays consistent and no partial changes happen.
Example
class Participant { constructor(name) { this.name = name; } prepare() { // Simulate participant readiness console.log(`${this.name} is preparing.`); return true; // Always ready in this example } commit() { console.log(`${this.name} commits the transaction.`); } rollback() { console.log(`${this.name} rolls back the transaction.`); } } class Coordinator { constructor(participants) { this.participants = participants; } twoPhaseCommit() { console.log('Coordinator: Starting prepare phase.'); const votes = this.participants.map(p => p.prepare()); if (votes.every(vote => vote === true)) { console.log('Coordinator: All participants agreed. Committing.'); this.participants.forEach(p => p.commit()); } else { console.log('Coordinator: Not all participants agreed. Rolling back.'); this.participants.forEach(p => p.rollback()); } } } const p1 = new Participant('Service A'); const p2 = new Participant('Service B'); const coordinator = new Coordinator([p1, p2]); coordinator.twoPhaseCommit();
When to Use
Use two phase commit when you need strong consistency across multiple services or databases that must all succeed or fail together. It is common in financial systems, booking platforms, or inventory management where partial updates can cause serious errors.
However, it can slow down the system because it waits for all participants to respond and can block resources during the process. For high-scale microservices, consider alternatives like eventual consistency or compensation transactions if strict atomicity is not required.
Key Points
- Two phase commit ensures all-or-nothing transactions across distributed systems.
- It has a prepare phase to ask if participants are ready, and a commit phase to finalize.
- If any participant votes no, the transaction is rolled back everywhere.
- It guarantees consistency but can reduce performance and availability.
- Best used when strict atomicity is critical, like in banking or inventory systems.