Three-phase commit (3PC) is a consensus protocol commonly used in distributed computing environments. In a distributed database management system, each transaction requires data to be changed in multiple places. Consensus algorithms ensure that when a change is made to one database instance, the same change will be applied to every other database instance in the distributed system.
There are two important types of protocols used in consensus: two-phase commits (2PCs) and a three-phase commits. In each type there is is a coordinator that receives transactions and participants (also called cohorts) that commit to the transaction or abort it. The main difference between 2PCs and 3PCs is that 3PCs split the commit phase into two parts to improve fault tolerance. This is done by adding a prepare-to-commit phase.
How three-phase commit works
In many ways, 3PCs can be seen as an extension of the 2PC protocol. In the first phase, the coordinator will send a sub-transaction to all participants and the participants will send the coordinator a reply saying yes to the commit or no to the commit.
If all participants respond yes, the coordinator will send participants a pre-commit message. If any of the participants responds no, the coordinator will send a message that says ABORT. The pre-commit phase ensures that the coordinator will only ask participants to proceed with a commit if there are no failures.
In the second phase, which is the prepare-to-commit stage, the coordinator sends a prepare message to participants from the first phase. In this phase, the coordinator essentially asks the cohorts if they are prepared to commit and, if they are not, the commit is aborted.
If the coordinator succeeds in the prepare phase, it will move on to the commit phase. Once the coordinator receives a yes from all cohorts stating that they are prepared to commit, the coordinator will send out a commit message. The cohorts will then each commit to the specified transaction.
If the coordinator receives a negative message while in a waiting state, times out or fails, then it will automatically abort the transaction. In this case, the coordinator will send an abort message to all cohorts.