Skip to the guide

Distributed transactions and two-phase commit

AdvancedConcept3 pages

Once data is sharded, one business action can touch two machines: a transfer from an account on shard 3 to an account on shard 11. Each shard can commit its own part, but nothing yet makes both happen or neither. Two-phase commit (2PC) is the classic protocol for that. Interviewers want you to know how it works, where it gets stuck, and when to avoid it altogether.

The travel agent

A travel agent books a trip: a flight, a hotel and a car. She doesn't buy any of them straight away. She phones each one and asks them to hold a seat, a room and a car, and each says "held" or "sorry, none left". Only when all three say "held" does she write "go ahead" in her diary and phone each to confirm. If any says no, she phones the others to release their holds.

Once the hotel has said "held", it can't give the room to anyone else, and it can't release it on its own either: maybe the agent has already confirmed the flight. So if the agent vanishes after collecting the holds, the room sits held, unsold, until someone reaches her or her diary.