Overview
This lecture explains distributed transactions using the Two-Phase Commit (2PC) protocol and applies it to Zomato's 10-minute food delivery example to illustrate atomicity across multiple microservices.
Distributed Transactions in Microservices
- Distributed transactions ensure changes across multiple services are atomic: all succeed or all fail.
- In Zomato's 10-minute delivery, both food and a delivery agent must be available and assigned simultaneously to guarantee fast delivery.
- Without atomicity, inconsistent states can occur (e.g., food reserved but no agent, or vice versa), causing business losses and poor user experience.
The Two-Phase Commit Protocol (2PC)
- 2PC splits a transaction into two phases: Prepare and Commit.
- Prepare Phase: Services reserve resources (e.g., food, delivery agent) and make them unavailable to others, but do not act on them yet.
- Commit Phase: If all reservations succeed, the system assigns the reserved resources to the order and completes the process.
- If any reservation fails in the Prepare Phase, the process aborts and all reservations are cancelled.
- Reservations have a timer to prevent indefinite locking if services become unresponsive.
Handling Failures and Edge Cases
- If reservation of food or agent fails, abort the process and release any reserved resources.
- If only one resource is reserved successfully, cancel the reservation immediately.
- Reservations are time-bound and auto-cancel after a timeout, preventing deadlocks or resource starvation.
- In the Commit Phase, assignment failures result in cancelling the reservation and retrying; eventual success is likely due to the reservation blocking other claims.
Advantages and Disadvantages of 2PC
- Advantages:
- Guarantees atomicity and isolation in distributed systems, ensuring transaction integrity.
- Disadvantages:
- Slow performance due to sequential steps and network calls.
- Prone to deadlocks, requiring deadlock detection and resolution mechanisms.
Key Terms & Definitions
- Distributed Transaction — A transaction that involves changes across multiple services or databases.
- Atomicity — A property ensuring all steps of a transaction are completed or none are.
- Two-Phase Commit (2PC) — A protocol with Prepare and Commit phases to guarantee atomicity in distributed systems.
- Isolation — Ensuring reserved resources are not accessible to others until the transaction completes.
- Deadlock — A state where two or more operations wait indefinitely for each other to release resources.
Action Items / Next Steps
- Review and simulate a distributed transaction using the two-phase commit protocol.
- Be prepared for hands-on implementation and failure/retry scenarios in the next session.