The two-phase commit (2PC) protocol is a distributed algorithm used to ensure that all participants in a transaction either commit or abort their changes in a coordinated manner across multiple systems. It is particularly useful in scenarios where data integrity is critical, such as banking transactions or online order processing. The protocol is divided into two distinct phases: the prepare phase and the commit phase, which work together to achieve a unanimous decision among all involved parties.
In the first phase, known as the prepare phase, the coordinator sends a request to all participants (or nodes) involved in the transaction asking if they are ready to commit. Each participant then checks its local conditions and resources. If a participant is ready, it votes "yes"; otherwise, it votes "no." This phase is critical because it allows each participant to independently evaluate the transaction before making a final commitment. Once all participants have responded, the coordinator evaluates the votes. If all responses are "yes," it proceeds to the second phase.
The second phase, the commit phase, occurs once the coordinator has received all positive votes. It sends a commit message to all participants, instructing them to finalize the transaction. If any participant voted "no," the coordinator sends an abort message instead, prompting all participants to roll back their changes. This ensures that the state of the system remains consistent, even in the presence of failures. An example of where this might be applied is an online retail site, where a user places an order involving inventory adjustments, payment processing, and order tracking. Here, it’s essential that all these actions are completed successfully; if one fails, the entire transaction must also be aborted to maintain accurate inventory and payment records.