What architectural patterns allow to eliminate atomicity between microservices? Have you worked with the Saga pattern? What are the two types of Saga and what is the difference?
sobes.tech AI
Answer from AI
Architectural patterns that allow avoiding the need for atomic transactions between microservices are usually based on asynchronous processing and compensation mechanisms. One such pattern is Saga.
Saga is a pattern for managing distributed transactions, which breaks a large transaction into a series of local transactions, each executed within a separate microservice. If one of the transactions fails, compensation transactions are executed to rollback previous changes.
There are two main types of Saga:
-
Choreography
- Each service publishes events and subscribes to events from other services.
- There is no central orchestrator; services independently react to events and initiate their local transactions.
- Example: Service A completes an operation and publishes an event; Service B, subscribed to this event, initiates its transaction.
-
Orchestration
- A central orchestrator manages the sequence of microservice calls.
- The orchestrator calls services in order and handles errors, initiating compensations if necessary.
Difference:
- In choreography, there is no single control point, which increases decentralization but complicates state tracking.
- In orchestration, there is a centralized controller, which simplifies management but creates a potential point of failure.
An example of simplified orchestration in Go (pseudocode):
func SagaOrchestrator() error {
if err := ServiceA(); err != nil {
return err
}
if err := ServiceB(); err != nil {
compensateServiceA()
return err
}
return nil
}
Thus, the Saga pattern allows avoiding distributed transactions with atomicity by using local transactions and compensations.