In DDD, a saga is a long-running transaction that coordinates multiple local transactions or operations to ensure that a consistent outcome is achieved. It is used in distributed systems or in systems with long-running processes, where it is not possible to execute all operations in a single transaction. The purpose of a saga is to ensure that the system reaches a consistent state, even if one or more of the local transactions fail. A saga is implemented as a sequence of steps, where each step is a transaction or a compensating action to undo a previous transaction. The steps of a saga are designed to be idempotent, meaning that they can be executed multiple times without changing the final outcome. Sagas are typically implemented using asynchronous messaging and event-driven architectures.
At a high level, there are two types of sagas:
- Process Manager Sagas: These sagas are used to manage a business process or workflow by coordinating and coordinating the actions of several domain entities. A process manager saga acts as an intermediary between entities and can have its own persistence mechanism to record the state of the process.
- Event-Driven Sagas: These sagas respond to events triggered by entities in the domain and react to those events. Event-driven sagas typically persist their state to ensure they can continue processing even after a system restart.
Both types of sagas are used to handle complex business processes and ensure that they are performed in the correct order with the appropriate conditions being met.
In their book, Software Architecture, The Hard Parts, Neal Ford and Mark Richardson discuss a number of transactional saga types on the basis of the communication style, consistency model, and coordination style.
| Pattern Name | Communication | Consistency | Coordination |
| Epic Saga | Synchronous | Atomic | Orchestrated |
| Phone Tag | Synchronous | Atomic | Choreographed |
| Fairy Tale | Synchronous | Eventual | Orchestrated |
| Time Travel | Synchronous | Eventual | Choreographed |
| Fantasy Fiction | Asynchronous | Atomic | Orchestrated |
| Horror Story | Asynchronous | Atomic | Choreographed |
| Parallel | Asynchronous | Eventual | Orchestrated |
| Anthology | Asynchronous | Eventual | Choreographed |
Example
An example of a saga could be an order processing system where a customer places an order, which triggers a series of steps such as reserving stock, charging the customer’s credit card, and shipping the items. Each step may involve a different aggregate, and the saga is responsible for ensuring that the steps are executed in the correct order, and compensating for any failures. For example, if there is an issue with charging the customer’s credit card, the saga could undo the stock reservation, and the customer would not be charged.