Back
+20 XP
Concept

Two-Phase Commit (2PC): Distributed Atomicity

Transactions spanning multiple databases cannot rely on single-node ACID locks. Two-Phase Commit (2PC) separates execution into Phase 1 (Prepare: nodes acquire locks and vote) and Phase 2 (Commit or Abort). A single rejection triggers unanimous rollback 🤝🛑.

python
class DBNode:
    def __init__(self, name, should_fail=False):
        self.name = name
        self.should_fail = should_fail
        self.state = "INIT"

    def prepare(self):
        if self.should_fail:
            self.state = "ABORTED"
            return False
        self.state = "PREPARED"
        return True

    def commit(self):
        self.state = "COMMITTED"

    def abort(self):
        self.state = "ABORTED"

nodes = [DBNode("Accounts_DB"), DBNode("Inventory_DB", should_fail=True)]

# Phase 1: Prepare votes
votes = [n.prepare() for n in nodes]

# Phase 2: Unanimous decision
if all(votes):
    for n in nodes: n.commit()
    print("Transaction Committed 🚀")
else:
    for n in nodes: n.abort()
    print("Transaction Aborted Cleanly 🛡️")

# 38. Two-Phase Commit (2PC): Distributed Atomicity When transferring money from Bank A to Bank B, you cannot simply execute two independent HTTP POST requests. If the second request times out mid-flight, money leaves Bank A and vanishes into thin air 🛑. ```python # The 2PC State Machine: # Phase 1: Coordinator -> "CAN YOU COMMIT?" # Participants -> "YES" / "NO" # Phase 2: If ALL "YES" -> Coordinator -> "GLOBAL COMMIT" # If ANY "NO" -> Coordinator -> "GLOBAL ABORT" ``` ### The 2PC Trade-Offs 1. **Strong Consistency**: Guarantees all-or-nothing atomicity across arbitrary independent databases. 2. **The Coordinator Bottleneck**: The coordinator is a single point of failure. If it crashes after participants enter `PREPARED`, participants hold database row locks indefinitely waiting for the coordinator to reboot. 3. **High Latency**: Requires multiple network round-trips plus synchronous fsync flushes on participant disks before releasing locks 🤝. --- ### Interactive Pop-Quiz 🧠 #### What is the critical failure mode of the traditional Two-Phase Commit (2PC) protocol? - [ ] It is a blocking protocol: if the coordinator crashes during Phase 2, participants remain locked indefinitely 🛑 - [ ] It cannot run on Linux servers without kernel re-compilation - [ ] It causes CPU thermal throttling on memory controllers - [ ] It limits maximum database records to 65,535 rows --- ### Practical Challenge 🎯 Implement a 2PC coordinator function `coordinate_2pc(participants)` where each participant has `.prepare()`, `.commit()`, and `.abort()`. Test with two nodes that vote True and one node that votes False. Assert all nodes end in `'ABORTED'` state, the coordinator returns `'ABORT'`, and print the result. <details> <summary>Solution</summary> ```python class Node: def __init__(self, vote_success): self.vote_success = vote_success self.state = "INIT" def prepare(self): if self.vote_success: self.state = "PREPARED" return True self.state = "ABORTED" return False def commit(self): self.state = "COMMITTED" def abort(self): self.state = "ABORTED" def coordinate_2pc(participants): votes = [p.prepare() for p in participants] if all(votes): for p in participants: p.commit() return "COMMIT" for p in participants: p.abort() return "ABORT" nodes = [Node(True), Node(True), Node(False)] result = coordinate_2pc(nodes) assert result == "ABORT" assert all(n.state == "ABORTED" for n in nodes) print(result) ``` </details>

Checkpoint

What is the critical failure mode of the traditional Two-Phase Commit (2PC) protocol? 🧠

Practice

Implement a 2PC coordinator function `coordinate_2pc(participants)` where each participant has `.prepare()`, `.commit()`, and `.abort()`. Test with two nodes that vote True and one node that votes False. Assert all nodes end in `'ABORTED'` state, the coordinator returns `'ABORT'`, and print the result. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks