- To manage distributed transactions across multiple microservices.
- It divides a large transaction into a series of smaller local transactions.
- Executed independently.
- Each service performs its own transaction via events or commands.
- If one transaction fails --> compensating actions are executed to undo previously completed operations.
Distributed Transaction
- Multiple db or system working together to complete a single task.
- If any step fails --> the entire transaction may need to be rolled back.
Why SAGA
- To manage distributed transaction in microservices without using complex protocols like 2PC.
- All these are achieved because they are executed independently.
- 2PC is notorious for blocking resource locks over a network, creating performance bottlenecks and single points of failure in high-throughput banking systems, whereas Saga decouples local transactions and relies on compensation.
Working of SAGA
- Distributed transactions by dividing them into a sequence of smaller transactions that execute independently across multiple services.
Example
Flow
Approaches
Choreography-Based Approach (Event-Driven)
- No central coordinator
- each service knows what to do ( independent )
- Events based via message queues or event streams.
- If a service fails --> it publishes a failure event accordyingly perform compensating actions.
Orchestration-Based Approach (Centralized)
- SAGA Execution Coordinator (orchestrator) controls the flow.
- The orchestrator tells each service when to start, what to do, and when to proceed to the next step.
- In choreography, services listen to and emit events without a central coordinator. As the system scales, understanding the exact workflow path becomes complex, and accidental event loops can occur.
Advantages
- flexibility & scalability --> to execute transactions independently without global locking.
- NO single points of failure since transactions are distributed across multiple services.
- fault tolerance --> ompensating actions to handle failures gracefully.
- Sagas embrace eventual consistency. The system transitions through intermediate states, and good banking application UX transparently reflects this operational reality to the end user.
Dis-Advantages
- Increase system complexity due to distributed transaction handling and compensating operations.
- Consider how communication happens when there is no "conductor" or central manager directing the traffic between microservices
Notes :
- 2PC --> two phase commit
Questions
DE
Source
This article was originally published by DEV Community and written by technonotes-hacker.
Read original article on DEV Community









