Middle — Middle+
Can you explain the principle of the two-phase commit (2PC) pattern and its usage?
sobes.tech AI
Answer from AI
The Two-Phase Commit (2PC) pattern is a protocol used to ensure the atomicity of distributed transactions when multiple resources (e.g., databases) must confirm changes in a coordinated manner.
Working principle:
-
Prepare phase:
- The transaction coordinator sends a request to all participants to prepare for commit.
- Each participant checks if it can perform the transaction and responds with "ready" or "not ready".
-
Commit phase:
- If all participants respond with "ready," the coordinator sends a command to commit the changes.
- If at least one responds with "not ready," the coordinator sends a rollback command.
This guarantees that either all participants commit the changes or none do, ensuring data consistency.
Example of a simplified implementation in Python:
class Participant:
def prepare(self):
# Check if commit is possible
return True # or False
def commit(self):
print("Commit executed")
def rollback(self):
print("Rollback executed")
class Coordinator:
def __init__(self, participants):
self.participants = participants
def two_phase_commit(self):
if all(p.prepare() for p in self.participants):
for p in self.participants:
p.commit()
print("Transaction successfully committed")
else:
for p in self.participants:
p.rollback()
print("Transaction rolled back")
# Usage
participants = [Participant(), Participant()]
coord = Coordinator(participants)
coord.two_phase_commit()
2PC is widely used in distributed systems to ensure data integrity but has drawbacks, such as resource locking during failures.