two phase commit

A good way of thinking about two phase commit is when a marriage solemnizer ask the couple on whether they want to get married. Each of the couple will need to say “I do”, before the solemnizer declares them married.

In a two phase commit:

  • the coordinator (solemnizer) ask each participants if they are able to perform the transaction.
  • each participant will check to make sure that they are able to perform the transaction. each participant that says “yes” must obtain the necessary locks and values and that they promised that if asked, they will be able to perform the transaction. For example, if Alice wants to transfer to Bob $100, a participant with Alice’s data must validate that Alice do have $100, and then put a hold on that $100.
  • Every participant must say “yes” before the transaction happens. If not, the coordinator will simply inform everyone to roll back the transaction.
  • Once the coordinator receives “yes” from everyone, it writes to its write-ahead log that the commit happens. This is the commit point of the transaction.

Notes:

  • All writes goes through the coordinator.
  • The coordinator must wait for every participant to say “yes”; if a slow participant takes a while to respond, the transaction will be held back.
  • If the coordinator dies at any point, the transaction can’t proceed. Participants might be locking a resource simply to wait for the coordinator. This is why the coordinator is usually replicated with Paxos to elect a leader and have a concensus on what the WAL/paxos log looks like. This also ensures that any replica can take on the role as Coordinator.
  • The dangerous state in 2PC is PREPARED: once a participant votes YES, it has given up its ability to independently decide the transaction’s outcome, and may therefore have to block waiting for the coordinator’s decision.

Links to this note