What a saga is, and how NServiceBus runs one
A long-running workflow that reacts to messages, keeps its own state between them, and can wait for something that may never come.
Some business processes don't finish in one request. A payment gets requested, a bank answers seconds or minutes later, a receipt goes out after that. The steps happen in different services, at different times, and any of them can fail or never answer.
A saga is the piece of code that follows one of those processes from start to finish. It reacts to messages, remembers where the process is, and decides what to do next.
- PaymentSaga → Authorize handler · command. Sent to one handler: please do this
- PaymentSaga → PaymentSaga · timeout. The saga asks to be woken up later
- The bank answers in time
- Authorize handler → PaymentSaga · event. Found by PaymentId; the saga saves Authorized
- PaymentSaga → Subscribers · event. Published, then MarkAsComplete() deletes the state
- No answer in 5 minutes
- PaymentSaga → PaymentSaga · timeout. Not authorized yet, so the saga gives up
- PaymentSaga → Subscribers · event. "No answer in time", then MarkAsComplete()
How a saga works
- Started by a message.
PaymentRequestedarrives and a new saga instance is created for that payment. - State between messages. The saga stores its data (for example, the payment ID and its status) after each message, so the next message can pick up where it left off.
- Correlation. Each incoming message carries an ID that finds the right saga instance. Here that's
PaymentId. - Timeouts. The saga can ask to be woken up later. If the bank hasn't answered in 5 minutes, it gives up and tells everyone.
The saga doesn't do the slow work itself. It sends commands to other handlers and reacts to the events they publish.
A small example
public sealed class PaymentSagaData : ContainSagaData
{
public Guid PaymentId { get; set; }
public bool Authorized { get; set; }
}
public sealed class PaymentSaga : Saga<PaymentSagaData>,
IAmStartedByMessages<PaymentRequested>,
IHandleMessages<PaymentAuthorized>,
IHandleTimeouts<PaymentTimedOut>
{
protected override void ConfigureHowToFindSaga(SagaPropertyMapper<PaymentSagaData> mapper) =>
mapper.MapSaga(saga => saga.PaymentId)
.ToMessage<PaymentRequested>(m => m.PaymentId)
.ToMessage<PaymentAuthorized>(m => m.PaymentId);
public async Task Handle(PaymentRequested message, IMessageHandlerContext context)
{
await context.Send(new AuthorizePayment(message.PaymentId, message.Amount));
await RequestTimeout<PaymentTimedOut>(context, TimeSpan.FromMinutes(5));
}
public async Task Handle(PaymentAuthorized message, IMessageHandlerContext context)
{
Data.Authorized = true;
await context.Publish(new PaymentCompleted(Data.PaymentId));
MarkAsComplete();
}
public async Task Timeout(PaymentTimedOut state, IMessageHandlerContext context)
{
if (Data.Authorized) return;
await context.Publish(new PaymentFailed(Data.PaymentId, "No answer in time"));
MarkAsComplete();
}
}MarkAsComplete() deletes the saga's state. After that, a late PaymentAuthorized for the same payment finds no saga and is discarded by default, because only PaymentRequested can start one. A timeout that fires after completion is dropped too.
Commands and events
- A command (
AuthorizePayment) is sent to one place and asks for something to happen. - An event (
PaymentCompleted) is published and says something already happened. Any service can subscribe to it.
The saga sits in the middle. It listens to events and sends the next command.
Things that bite
- Messages can arrive twice. Make each handler safe to run again. Check the state before acting, and give outgoing messages stable IDs.
- Messages can arrive out of order. Decide what the saga does if
PaymentAuthorizedcomes before it expects it. - Keep the saga thin. It decides what happens next. The work, like calling a bank or sending an email, goes in separate handlers that the saga sends commands to.
- Keep the state small. It's loaded and saved on every message, so store IDs and statuses, not whole documents.
When you don't need a saga
If the whole process fits in one request and one database transaction, a saga only adds moving parts. Use one when the steps are spread over time and across services.