Microservices- Handling Distributed Transactions
Two Phase Commit (2PC)

please 🔔 to https://youtube.com/@bitbeee?si=srx28oTYErpgswxD
For DSA & System Design interview preparation…
The Two-Phase Commit (2PC) protocol is a distributed algorithm used to achieve atomicity in distributed transactions. It ensures that all participating nodes in a distributed transaction either commit or rollback the transaction consistently, even in the presence of failures. Here’s a high-level overview of the two phases:
Voting Phase (Phase 1): The coordinator node sends a prepare message to all participating nodes, asking them if they are ready to commit the transaction.
Each participant responds with either a “Yes” vote (prepared to commit) or a “No” vote (not prepared or encountering issues).
If any participant votes “No” or if a timeout occurs without receiving responses from all participants, the coordinator initiates the rollback phase.
Decision Phase (Phase 2): If all participants vote “Yes” during the voting phase, the coordinator sends a commit message to all participants.
Upon receiving the commit message, each participant commits the transaction locally and acknowledges the coordinator.
If any participant votes “No” during the voting phase, or if a timeout occurs, the coordinator sends a rollback message to all participants.
Upon receiving the rollback message, each participant aborts the transaction locally and acknowledges the coordinator.
Key points about the Two-Phase Commit protocol:
Ensures that either all nodes commit the transaction or none of them commit, preventing inconsistencies.
Guarantees atomicity but introduces some blocking during the commit process, especially if there are network delays or failures.
Relies on coordination from a central coordinator node, which can become a single point of failure and scalability bottleneck.
Vulnerable to coordinator failure, requiring additional mechanisms (such as timeouts and timeouts) for fault tolerance and recovery.
Overall, the Two-Phase Commit protocol is a fundamental technique for achieving distributed transactional consistency, although it may not be suitable for all scenarios due to its blocking nature and reliance on a central coordinator. Other protocols like Three-Phase Commit and Paxos address some of the limitations of 2PC while introducing additional complexity.