by BehindJava
What is a Two-Phase Commit Transactions (2PC) in Microservices
In this tutorial, we are going to learn about Two-Phase Commit Transactions (2PC) in detail.
Two-Phase Commit Transactions (2PC)
- Widely used in database systems because it is very strong transaction.
- Sometimes useful in microservices (only when there are only few microservices involved in building the system).
-
It has two phases due to which it is called a Two-Phase Commit pattern, i.e., a Prepare Phase and a Commit Phase.
- Prepare Phase: To start a transaction, microservices are asked to prepare for a change, is called prepare phase. Example: Create a record in the database and set its status field or column to 0(0 means not stable)
- Commit Phase: Microservices are asked to make the final and actual change, which is the commit phase. Example: Set status field or column to 1 or finalized.
- Coordinator microservices are needed to maintain the life-cycle of the entire transactions due to multiple microservices.
Successful Two-Phase Commit
Here is an example of Successful Two-Phase Commit, which means all the microservices are successfully committed their transactions.
- Coordinator Microservice starts or creates a transaction, which generates or returns the transaction ID.
- Now, CustomerMicroservice is hit by the prepareUpdateCustomerFund(id) followed by the orderMicroservice where PrepareCreateOder(id) is hit and both the microservices returns prepared.
- After preparing the order, we need to update customer funds by hitting the CommitUpdateCustomerFund(id) to the CustomerMicroservice and CommitCreateOrder(id) to the OrderMicroservice and returns done.
Failed Two-Phase Commit
Here is another example of Failed Two-Phase Commit, which means all the microservices are not successfully committed their transactions.
- Similarly, as the previous example, Coordinator microservice starts the transaction and creates a transaction ID.
- It hits CustomerMicroservice and OrderMicroservice to prepareUpdateCustomerFund(id) and PrepareCreateOder(id) in which one of them fails and returns failed.
- In this case, coordinator microservice sends a message to orderMicroservice to abort(id) the current transaction.
- Entire transaction is cancelled.