Q6Distributed System
Question
Explain the two-phase commit protocol for distributed transactions.
Answer
A rigorous architectural breakdown of the Two-Phase Commit (2PC) protocol, detailing the strict Voting and Execution phases that mathematically guarantee absolute distributed transaction atomicity across multiple databases.
In a distributed database, a single transaction might violently modify data on Server A, Server B, and Server C simultaneously (e.g., transferring money across three international banks). The absolute mathematical rule of Atomicity dictates that EITHER all three servers successfully commit the data, OR all three absolutely abort and roll back. Partial commits destroy data integrity. The Two-Phase Commit (2PC) protocol is the rigid architectural engine that guarantees this.
The architecture utilizes one supreme Coordinator node and multiple Participant nodes.
Phase 1: The Voting Phase (Preparation)
- 1. The Coordinator blasts a
PREPARE_TO_COMMITmessage to all Participants. - 2. Every Participant aggressively locks their local database tables and physically writes a "prepare log" to their hard drive to survive a crash.
- 3. Each Participant calculates if they can mathematically execute the transaction. If yes, they reply
VOTE_COMMIT. If they encounter an error (e.g., insufficient funds), they replyVOTE_ABORT.
Phase 2: The Execution Phase (Commit/Rollback)
- 1. The Coordinator collects all votes. It mathematically requires absolute unanimity.
- 2. If even ONE SINGLE Participant voted
VOTE_ABORT(or timed out), the Coordinator violently blasts aGLOBAL_ABORTcommand to everyone. All nodes instantly roll back the transaction, dropping the locks. - 3. If, and only if, ALL Participants voted
VOTE_COMMIT, the Coordinator blasts aGLOBAL_COMMITcommand. All nodes permanently write the data to disk and release the locks. - 4. Participants reply with an
ACKto confirm execution.
While mathematically brilliant for data integrity, 2PC is a "blocking" protocol. If the Coordinator violently crashes during Phase 2, all Participants are mathematically frozen, holding massive database locks infinitely until the Coordinator reboots.