Sitemap
Mohammed Ben Said

Mohammed Ben Said

Understanding Two-Phase Commit (2PC)

2 min readMar 10, 2023

--

Two-Phase Commit (2PC) is a distributed transaction protocol used to ensure the consistency of transactions that involve multiple distributed systems.

The theory is always clear, but let’s see an example from the e-commerce context.

Suppose Imane wants to buy a book from Xavier’s online bookstore. Imane adds the book to her cart and proceeds to checkout. At this point, the transaction involves three parties: Imane(the buyer), Xavier(the seller), and a payment gateway (to process Imane’s payment).

Phase 1: Prepare

Imane initiates the transaction by sending a message to Xavier and the payment gateway, asking them to prepare for the transaction. This phase ensures that all parties are ready to proceed with the transaction.

Phase 2: Commit or Abort

Assuming that all parties are ready, Imane sends a message to both Xavier and the payment gateway, asking them to commit the transaction.

Get Mohammed Ben Said’s stories in your inbox

Join Medium for free to get updates from this writer.

If either party is unable to commit the transaction (e.g., if Xavier is out of stock, or if the payment gateway declines Imane’s payment), the transaction is aborted, and all parties are notified.

If all parties can commit, then the transaction is completed, and all parties are notified.

Press enter or click to view image in full size

This two-phase commit process ensures that the transaction is completed only if all parties involved can successfully commit. If any party fails, the transaction is aborted, and the system can roll back to the previous state to ensure consistency.

In this way, 2PC provides a reliable way to ensure the integrity of transactions in e-commerce, where multiple parties are involved, and the outcome of the transaction depends on the successful completion of all parties.

Thanks for reading! I hope you found this post informative. See you in another post!

--

--