The Saga pattern is a technique used to implement a business transaction spanning multiple systems. A system in this context is anything that owns its own data, e.g. a database within your own application, a microservice or a third-party SaaS. A **Saga** represents a high-level business process (such as booking a trip) that consists of several low-level **Requests** that each update data within a single service. Each Request has a **Compensating Request** that is executed when the Request fails or the saga is aborted.[^yos1] ![[saga-pattern.png]] In distributed systems, business transactions spanning multiple services require a mechanism to ensure data consistency across services. The Distributed Saga pattern is **a pattern for managing failures**, where each action has a compensating action for rollback. Distributed Sagas help ensure consistency and correctness across microservices. [^yos1] [^yos1]: [Distributed sagas](https://yos.io/2017/10/30/distributed-sagas/) by yosriady ## Strategies for implementing saga patterns There are two ways of coordinating sagas: [^cr1] - Choreography - each local transaction publishes domain events that trigger local transactions in other services - Orchestration - an orchestrator (object) tells the participants what local transactions to execute [^cr1]: [Saga microservices pattern](https://microservices.io/patterns/data/saga.html) by Chris Richardson ### Choreography strategy Choreography is the simplest way to implement SAGA pattern. Each local transaction in chain is independent as they don’t have direct knowledge of each other. **If your distributed transaction only includes from 2 to 4 local transactions then Choreography is very fit option.** But having too many local transactions will make tracking which services listen to which events becomes very complex. [^tl1] [^tl1]: [What is SAGA Pattern and How important is it?](https://medium.com/swlh/microservices-architecture-what-is-saga-pattern-and-how-important-is-it-55f56cfedd6b) by Thanh Le ### Orchestration strategy Orchestration brings to us some advantages:[^tl1] - Easy to maintain the whole workflow in one place — Orchestrator. - Avoid cyclic dependencies between services. All services only communicate with Orchestrator. - The complexity of transaction remains linear when new steps are added. However, in order to achieve the above advantages, you need to design a comprehensive orchestrator flow. And having too much logic in a centralised orchestrator might lead to difficulties in maintenance. ## Services for implementing saga patterns - [[AWS EventBridge]] can help provide a choreography-based implementation of sagas - [[AWS Step Functions]] can help provide an orchestration-style implementation of sagas --- tags: #SoftwareEngineering #ArchitecturePatterns