The Wayback Machine - https://web.archive.org/web/20240724173022/https://www.geeksforgeeks.org/saga-design-pattern/
Open In App

SAGA Design Pattern

Last Updated : 24 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

SAGA pattern is a design pattern that is a long-lived sequence of smaller transactions. This pattern is used to manage and maintain data consistency across multiple microservices. Each transaction is executed by a single service, and the state changes are broadcasted to other services involved in the Saga. It helps to maintain data consistency by providing an alternative approach to the traditional ACID transactions model that may not be feasible in a distributed environment.

The name “SAGA” comes from the concept of a long story with many parts, just like a distributed transaction. In a SAGA, each part of the story is a local transaction, and together, they form the complete story.

Note: Strangler and SAGA patterns are extremely important while designing microservices and at same instance SAGA is extremely important from interview perceptive.

It is responsible for managing the overall transaction and coordinating the compensating actions required in case of any failures. It is useful when dealing with complex business processes that involve multiple services, such as order processing, shipping, and billing. In such cases, it is often necessary to coordinate the execution of multiple transactions to maintain data consistency across the services involved.

Features of SAGA Pattern

  1. Coordinated transactions: The SAGA pattern provides a way to coordinate transactions that involve multiple services or processes. The pattern defines a sequence of steps, each of which can involve a separate service or process, that are executed in a coordinated manner to complete the transaction.
  2. Compensation and rollback: The SAGA pattern includes a mechanism for compensating or rolling back the transaction if one of the steps fails. This mechanism ensures that the transaction remains consistent even if one or more of the steps fail.
  3. Distributed transactions: The SAGA pattern supports distributed transactions that span multiple services or processes. The pattern provides a way to coordinate the transaction across these services or processes in a consistent manner.
  4. Asynchronous processing: The SAGA pattern can support asynchronous processing, which allows for greater concurrency and performance. This is especially important in distributed systems where the processing time of different services or processes may vary.
  5. Error handling: The SAGA pattern provides a standardized way to handle errors that occur during the transaction. The pattern ensures that errors are handled consistently across all services or processes involved in the transaction.
  6. Scalability: The SAGA pattern can scale to handle large and complex transactions that involve multiple services or processes. The pattern provides a way to break down the transaction into smaller, more manageable steps, which can be executed in parallel across different services or processes.

Example:

Let us take a look at an example of how the SAGA pattern works in practice. Consider an e-commerce application that allows users to purchase products. When an order is placed, the payment must be processed, the seller’s inventory must be checked and reserved, and finally, the order must be shipped. If any of these steps fail, the entire order should be rolled back.

To implement the pattern, we can create a separate service for each of the above functionality. It has to be designed in such a manner, that all these transactions are synchronized with each other.

A typical flow for such a website should look like this:

  1. Begin Order: Start the order saga and create a new order in the database.
  2. Process Payment: Attempt to charge the user’s debit card/credit card. If successful, mark the order as paid in the database. If unsuccessful, cancel the order and roll back any previous steps.
  3. Check Inventory: Check if the items in the order are in stock. If not, cancel the order and roll back any previous steps.
  4. Reserve Inventory: Reserve the items in the order. If unsuccessful, cancel the order and roll back any previous steps.
  5. Ship Order: Mark the order as shipped in the database.

It is evident that each step is dependent on its previous step. Each of the steps would be implemented as a separate service. When a step is completed successfully, it would send a message to the next step. If a step fails, it would send a message to the previous step to roll back any changes made so far.

A typical architecture for the SAGA pattern.

Implementation:

Here is an overview of how the SAGA pattern can be implemented for the flow:

1. Begin Order: When a new order is initiated, create a new saga instance and store it in a database. The saga instance should include all the data required to perform the order process, such as the user’s information and the order details. The initial step in the saga is to create a new order in the database.

2. Process Payment: The next step in the saga is to process the payment. If the payment is successful, update the saga instance to mark the order as paid in the database. If the payment fails, the saga should trigger a compensation step to cancel the order and roll back any previous steps.

3. Check Inventory: After the payment has been processed successfully, the next step is to check the inventory to see if all the items in the order are available. If any items are out of stock, the saga should trigger a compensation step to cancel the order and roll back any previous steps.

4. Reserve Inventory: If all the items are available, the next step is to reserve the inventory for the order. If the inventory cannot be reserved for any reason, the saga should trigger a compensation step to cancel the order and roll back any previous steps.

5. Ship Order: The final step in the saga is to ship the order. If the order has been paid for, all the items are available, and the inventory has been reserved, mark the order as shipped in the database. If any of the previous steps fail, the saga should trigger the appropriate compensation steps to cancel the order and roll back any previous steps.

Events are used to coordinate the different steps of the order process across multiple services or processes. For instance, the service responsible for processing the payment can publish an event when the payment is successfully processed. This event can be consumed by the service responsible for marking the order as paid, which in turn can publish an order-paid event. This event can be consumed by the service responsible for reserving the inventory, which can publish an inventory-reserved event. This event can be consumed by the service responsible for shipping the order, which can publish an order shipped event to update the order status in the database.

Advantages and Disadvantages of SAGA Pattern

Advantage of SAGA Pattern

Disadvantage of SAGA Pattern

Provides better fault tolerance: With SAGA, if one step fails, the entire process can be rolled back or compensated without affecting other steps. Increased complexity: Implementing SAGA requires additional coding and architecture to handle compensation and rollback steps.
Simplifies error handling: SAGA provides a clear and standardized way to handle errors and compensations, making it easier to debug and maintain. Limited support: Not all frameworks or platforms support SAGA out of the box, which can make implementation more difficult.
Allows for asynchronous processing: SAGA can support asynchronous processing, allowing for greater concurrency and performance. Requires careful design: The SAGA pattern requires careful design to ensure that the compensations and rollbacks are implemented correctly and can handle all possible failure scenarios.
Supports distributed transactions: SAGA can handle transactions across multiple services or databases, allowing for more scalable and distributed architectures. Increased latency: SAGA may result in additional latency due to the need to coordinate between different services or databases.

Overall, the SAGA pattern is a powerful tool for managing distributed transactions and providing fault tolerance. However, it requires careful design and implementation to ensure that it is used effectively and does not introduce additional complexity or latency.



Similar Reads

Difference Between SAGA Pattern and 2-Phase Commit in Microservices
The SAGA Pattern and 2 Phase Commit (2PC) are prominent strategies for managing distributed transactions in microservices architectures. While both aim to ensure data consistency across services, they differ significantly in approach and application. The SAGA Pattern, a sequence of local transactions, offers high availability and fault tolerance bu
3 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Article Tags :
three90RightbarBannerImg