Senior
Tell me about 2PC and 3PC — how do they differ?
sobes.tech AI
Answer from AI
2PC (Two-Phase Commit) and 3PC (Three-Phase Commit) are protocols for distributed commit, used to ensure transaction consistency in distributed systems.
2PC (Two-Phase Commit):
- Phase 1 (Prepare): the coordinator sends a request to participants to prepare for commit.
- Participants respond whether they are ready to commit the transaction.
- Phase 2 (Commit): if all participants are ready, the coordinator sends a commit command; otherwise, abort.
Problems of 2PC:
- Blocking protocol: if the coordinator fails after phase 1, participants may remain in an uncertain state, waiting for a decision.
3PC (Three-Phase Commit):
- Adds an intermediate phase between prepare and commit — pre-commit.
- Phases:
- CanCommit? — request for readiness.
- PreCommit — notification of upcoming commit, participants block resources.
- DoCommit — final confirmation of commit.
The advantage of 3PC is reducing lock time and avoiding lock states in case of coordinator failures.
Overall, 3PC is more resilient to failures but more complex and requires more messages, so 2PC is more commonly used, while 3PC is used in systems with high availability requirements.