Two-phase commit (2PC) is a distributed consensus algorithm primarily used for ensuring atomicity in transactions across multiple systems. It guarantees that either all participants commit or abort a transaction. The algorithm finds application in scenarios where changes need to occur as a single unit, such as reading and writing multiple database shards in a transaction. Consensus is difficult to achieve due to the requirement for unanimous agreement among participants. This poses challenges, especially due to node or network failures, which can impact the effectiveness of 2PC’s operation. This lesson will explore transactions and delve into the intricacies of the 2PC algorithm, including its management of various failure scenarios.

Transactions and atomic commit

In a distributed system, transactions are used to manage the reading and writing of data among nodes. A transaction is a unit of work that reads and writes data from one or more nodes. Achieving atomic commit is essential to maintain consistency and reliability, meaning that all transaction changes are committed or none of them are. However, ensuring atomic commit is challenging in a distributed system because it requires coordination among multiple nodes.

For example, consider a banking application that transfers funds between accounts. The transaction involves deducting the amount from the sender’s account and adding it to the receiver’s account. To ensure atomic commit, the transaction must be coordinated across multiple nodes to ensure that the debit and credit operations occur atomically. The withdrawal and deposit both happen, or they both should not happen at all. In the context of ACID, the C refers to the application's notion of consistency. In the example of account debits and credits, the invariant is that across all accounts, the credit and debit amounts should always be equal. Atomicity helps the application achieve and keep its consistent state. See the following illustration that shows how failures make the consensus about common knowledge challenging.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.