What is two-phase commit (2PC)?
A two-phase commit is a standardized protocol that ensures that a database commit is implemented in the situation where a commit operation must be broken into two separate parts.
In database administration, saving changes to data is called commit and undoing changes is called rollback. Both can easily be achieved by using transaction logging when a single server is involved, but when the data is spread across geographically diverse servers (i.e. each server is an independent entity with separate log records) the process can become more difficult.
A special object known as a coordinator is needed in a distributed transaction. As the name suggests, the coordinator organizes activities and synchronization between distributed servers. The two-phase commit is implemented as follows:
Phase 1 - Each server that needs to commit data writes its records to the log. If a server is unsuccessful, it responds with an error message. If successful, the server replies with an OK message.
Phase 2 - This phase begins after all participants have answered OK. Then the coordinator sends a signal to each server with commit instructions. Once committed, everyone writes the commit as part of their log record for reference and sends a message to the coordinator that their commit was successfully implemented. When a server fails, the coordinator sends instructions to all servers to roll back the transaction. After the servers are reset, everyone sends feedback that this has been completed.