by BehindJava
What is a Saga Pattern in Microservices and Why distributed transactions named as SAGA?
In this tutorial, we are going to learn about Saga Pattern in the context of managing distributed transactions.
Saga is not an abbreviation. The term “saga” was first defined in a 1987 publication. It also mentions that it was proposed by Bruce Lindsay.
In their original version, the term saga refers to Long Lived Transactions(LLT).
- A LLT is a saga if it can be written as a sequence of transactions that can be interleaved with other transactions.
The reason for choosing the word itself is not disclosed. Perhaps one of the literary meanings of the word saga was meant:
- A long, detailed story of connected events
Saga Pattern for Distributed Transactions
- It is an asynchronous way of managing distributed transactions because in Two-Phase Commit Transactions, we have to wait for the other microservices to send us acknowledgement, and then we determine the final state of the transaction.
- Whereas in the Saga Pattern each microservice is responsible for managing its own transaction and there is no waiting for the other microservices to finish the transaction which means it is asynchronous.
There are two types of sub-patterns in Saga pattern, i.e.,
- Choreography Pattern: If something goes wrong in one microservice, it has to notify the up-stream or previous microservices to roll back the transaction.
- Orchestration Pattern: A central microservice delivers the messages for roll-back of a transaction.
These patterns are not only used for managing distributed transactions, but also used for managing and implementing the business work flows.
- For example, if you got to an E-commerce system and place an order for shoes, all the microservices that work in the background to make the workflow happen and finish.
- They have work either under Choreography Pattern or Orchestration Pattern or mix of these two patterns.