Sagas and Workflows
Coordinate long-running processes.
Sagas and Workflows is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Coordinating Long Workflows
Some business processes span multiple messages and steps over time: place order, charge payment, reserve stock, ship. A saga coordinates such a long-running workflow and tracks its state across messages.
What Is A Saga?
A saga is a stateful consumer. It correlates related messages, holds the workflow's current state, and reacts to events by transitioning between states until the process completes.
State Machine Sagas
MassTransit models sagas as state machines using MassTransitStateMachine. You define states, events, and transitions declaratively.
dotnet add package MassTransit
// state machine sagas are built inThe Saga State
The state is a class implementing SagaStateMachineInstance. It carries a CorrelationId plus any data you need to remember between steps.
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; }
public decimal Amount { get; set; }
}Declaring States And Events
Inside the state machine you declare State properties and Event properties that map to message types.
public class OrderSaga : MassTransitStateMachine<OrderState>
{
public State AwaitingPayment { get; private set; }
public State Completed { get; private set; }
public Event<OrderPlaced> OrderPlaced { get; private set; }
public Event<PaymentReceived> PaymentReceived { get; private set; }
}Correlation
Every event must correlate to the right saga instance, usually by a shared id like OrderId. This routes incoming messages to the correct in-flight workflow.
Event(() => PaymentReceived, e =>
e.CorrelateById(m => m.Message.OrderId));Defining Transitions
The constructor wires behavior: the initial event creates the instance, stores data, and transitions to the next state.
Initially(
When(OrderPlaced)
.Then(ctx => ctx.Saga.Amount = ctx.Message.Amount)
.TransitionTo(AwaitingPayment));Reacting In A State
Use During to handle events valid only in a particular state, then publish follow-up messages and transition onward.
During(AwaitingPayment,
When(PaymentReceived)
.Publish(ctx => new OrderConfirmed(ctx.Saga.CorrelationId))
.TransitionTo(Completed)
.Finalize());Persisting Saga State
Saga state must survive restarts, so it is stored in a repository: Entity Framework, MongoDB, Redis or others. MassTransit loads and saves the instance around each message.
x.AddSagaStateMachine<OrderSaga, OrderState>()
.EntityFrameworkRepository(r =>
{
r.ExistingDbContext<OrderDbContext>();
});Timeouts With Schedules
Sagas can schedule a timeout (for example, cancel if payment is not received in 30 minutes) using a Schedule, then handle the timeout event to compensate.
Compensation
If a later step fails, a saga can run compensating actions to undo earlier ones (refund a charge, release stock), keeping the overall process consistent without distributed transactions.
Quick Check
Test sagas and workflows.
Recap
A saga coordinates long-running workflows as a stateful, correlated consumer. MassTransit uses MassTransitStateMachine with a SagaStateMachineInstance state, declared State/Event members, correlation by id, and transitions via Initially/During. State is persisted in a repository, timeouts use schedules, and compensation undoes earlier steps on failure.
Frequently asked questions
Is the “Sagas and Workflows” lesson free?
Yes — the full text of “Sagas and Workflows” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Sagas and Workflows”?
Coordinate long-running processes. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sagas and Workflows” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Messaging Concepts
- Producing and Consuming Messages
- Sagas and Workflows
- Error Handling and Retries