What is a saga?
A saga is a long-lived transaction managed by a coordinator. Sagas are initiated by an event, sagas orchestrates events, and sagas maintain the state of the overall transaction. They are designed to manage the complexity of a distributed transaction without locking and immediate consistency. They manage state, and track compensations that are required if a partial failure occurs.
We didn't create it, we learned it from:
Cornell paper: http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf
Arnon Rotem-Gal-Oz's book chapter: http://www.rgoarchitects.com/Files/SOAPatterns/Saga.pdf
How do I create a saga using MassTransit?
A saga is implemented as a class that contains the behavior of the transaction. This can either be done entirely the developer or with some help from the SagaStateMachine syntax.
Using the Saga State Machine
The saga state machine was added in 0.6 as a way to declaratively define a saga without dealing with all of the messaging noise.
The Starbucks example uses two sagas that are built this way, one for the cashier and one for the barista. Check the sample for details on the syntax. An example will be added here once I figure out how to get code posted nicely.
Using the Standard Saga Syntax
The syntax for declaring a saga is done using a series of interfaces on your class.
public class MySaga :
InitiatedBy<InitiatingMessage>,
Orchestrates<SubsequentMessage>
Messages that initiate the saga will create a new instance of the saga and fail if the saga has already been created. It is important that the originating message contain a unique Guid for each instance. If the initiating message does not assign a Guid, a new one will be created.
Subscribing Sagas
Once you have defined your saga class using either method, a service must subscribe that saga to be handled. The service would use the IServiceBus interface to subscribe via:
UnsubscribeAction unsubscribe = bus.Subscribe<MySaga>();
This should be called when the service starts to begin processing the saga.
Saga Repositories
Sagas are created, updated and saved using an ISagaRepository< T > that should be provided by the developer. A default InMemorySagaRepository is available for testing. An NHibernate version is in the MassTransit.Infrastructure assembly if you are using NHibernate.
Comments (0)
You don't have permission to comment on this page.