by BehindJava
What is a Distributed Transaction in Microservices
In this tutorial, we are going to learn about Distributed Transaction in detail. This is an important question for passing the interview and also for building the Microservices.
Distributed Transaction
- In microservice-based architecture each service has its own database due to which we cannot use the traditional transactions also referred as asset transactions.
- We need to make sure transactions (insert, update, delete) are ATOMIC across all services, which means all the databases at the end of the transaction will be in a trustworthy transaction state. For example, assume an order that is in the order service database and its related payment is in the payment database, where everything is in a reliable state.
- Managing transactions across multiple services is Distributed Transaction, and also it is also referred as eventual consistency because eventually we want everything to be consistent and atomic.
Let’s look at an example for more detailed understanding.
- In a monolithic application, we normally have a system, and it has a database.
- Now the user puts an order and sequence starts with the begin transaction and updates the customer table followed by updating the order table and transaction is committed and database goes into the reliable state.
To break the above monolithic application into microservices looks something like this.
- We have two microservices, i.e., customer microservice and order microservice. Conductor is something like a circuit breaker, which is like a facade layer.
- Now, we need to send a command to customer microservices to create the customer or update the customer fund.
- In this example, we need to update the customer’s fund. So we need to send a message to customer service and order microservice to create an order.
- we need to make sure that if the order is not created successfully, the funds are not deducted from the customer’s balance or funds deducted only if the order is created successfully.
- To achieve this, we need to have two databases to update, and we need to make sure that they are in a reliable state at the end of their transaction.
There are two ways of handling distributed transactions, i.e.,