Xpandables.Sagas
11.0.0
dotnet add package Xpandables.Sagas --version 11.0.0
NuGet\Install-Package Xpandables.Sagas -Version 11.0.0
<PackageReference Include="Xpandables.Sagas" Version="11.0.0" />
<PackageVersion Include="Xpandables.Sagas" Version="11.0.0" />
<PackageReference Include="Xpandables.Sagas" />
paket add Xpandables.Sagas --version 11.0.0
#r "nuget: Xpandables.Sagas, 11.0.0"
#:package Xpandables.Sagas@11.0.0
#addin nuget:?package=Xpandables.Sagas&version=11.0.0
#tool nuget:?package=Xpandables.Sagas&version=11.0.0
📦 System.Sagas
Distributed sagas over Xpandables.Events: orchestrated, observed and hybrid sagas, state machines, compensation, timeouts, retries, auditing and OpenTelemetry, on the transactional outbox and the idempotent inbox; Native AOT.
Getting started • Model • Steps • State machines • Compensation • Timeouts and retries • Consistency • Operations • Observability • Runbooks • Testing • Native AOT • Reference
The design, its decisions and its comparison with MassTransit, NServiceBus, Temporal and Dapr Workflows are in RFC 0001.
🚀 Getting started
dotnet add package Xpandables.Sagas
A saga is a class: its data, its start event, and its steps.
using System.Events.IntegrationEvents;
using System.Sagas;
public sealed class OrderData
{
public Guid OrderId { get; set; }
public decimal Amount { get; set; }
public Guid? PaymentId { get; set; }
}
[SagaName("Marketplace.Order")] // persisted: never derived from the class name
public sealed class OrderSaga : Saga<OrderData>
{
protected override void Configure(ISagaBuilder<OrderData> saga)
{
saga.StartWith<OrderPlaced>(e => e.OrderId.ToString("N"), (context, e) =>
{
context.Data.OrderId = e.OrderId;
context.Data.Amount = e.Total;
})
.Deadline(TimeSpan.FromHours(72))
.OnCompleted(d => new OrderConfirmed { OrderId = d.OrderId })
.OnCompensated((d, end) => new OrderCancelled { OrderId = d.OrderId, Reason = end.Reason.ToString() });
saga.Step("Payment")
.Send(d => new ProcessPaymentRequested { OrderId = d.OrderId, Amount = d.Amount })
.On<PaymentSucceeded>((d, e) => d.PaymentId = e.PaymentId)
.FailOn<PaymentDeclined>(e => new SagaFailure(e.Reason, IsTransient: e.Retryable))
.Timeout(TimeSpan.FromMinutes(15))
.Retry(new SagaRetryPolicy(MaxAttempts: 3, BaseDelay: TimeSpan.FromMinutes(1), MaxDelay: TimeSpan.FromMinutes(10)))
.CompensateWith(d => new RefundPaymentRequested { OrderId = d.OrderId, PaymentId = d.PaymentId })
.CompensationConfirmedBy<PaymentRefunded>();
saga.Step("Stock")
.Send(d => new ReserveStockRequested { OrderId = d.OrderId })
.On<StockReserved>()
.FailOn<OutOfStock>(_ => new SagaFailure("out of stock"))
.Timeout(TimeSpan.FromMinutes(10))
.CompensateWith(d => new ReleaseStockRequested { OrderId = d.OrderId });
saga.Step("Delivery")
.Send(d => new CreateDeliveryRequested { OrderId = d.OrderId })
.On<DeliveryCreated>()
.FailOn<DeliveryRejected>(e => new SagaFailure(e.Reason))
.Timeout(TimeSpan.FromHours(48))
.Pivot(); // past it, the saga only goes forward
}
}
Every message is an integration event of Xpandables.Events ([EventName], in your JSON context). A participant is an
ordinary inbox consumer that replies through its outbox, while consuming the command: the reply then carries the
command's id as its causation id, which routes it back to the saga.
public sealed class PaymentService(IOutboxStore outbox, IPaymentGateway gateway) : IEventConsumer<ProcessPaymentRequested>
{
public async Task ConsumeAsync(ProcessPaymentRequested command, CancellationToken cancellationToken = default)
{
PaymentResult result = await gateway.CaptureAsync(command.OrderId, command.Amount, cancellationToken);
await outbox.EnqueueAsync([result.Succeeded
? new PaymentSucceeded { OrderId = command.OrderId, PaymentId = result.PaymentId }
: new PaymentDeclined { OrderId = command.OrderId, Reason = result.Reason, Retryable = result.Retryable }],
cancellationToken);
}
}
Registration, with Xpandables.Events over a database:
builder.Services
.AddXJsonSerializerOptions(options => // or an IJsonSerializerContext of your own
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default); // your messages and data
options.SerializerOptions.TypeInfoResolverChain.Add(SagaJsonContext.Default); // the saga messages
})
.AddXMyAppCacheTypes() // your event names (generated)
.AddXData(data => data.UsePostgreSql(connectionString))
.AddXEventConverterProvider()
.AddXEventConverters()
.AddXOutboxStore()
.AddXInboxStore()
.AddXScheduler()
.AddXHostedScheduler()
.AddXMyAppEventConsumers() // the participants (generated)
.AddXSagas() // the engine and its defaults
.AddXMyAppSagas() // every saga of the assembly (generated), or AddXSaga<OrderSaga>()
.AddXSagaHealthCheck()
.AddXEventRetention()
.AddXSagaRetention();
Create the tables with the scripts (SagaTableScriptProviders.PostgreSql.GetCreateTablesScript(), also for SQL Server
and SQLite), next to the event tables, in the database of the events unit of work.
🧭 The model
| Concept | What it is |
|---|---|
| Instance | One row of Saga.SagaInstance: status, state, active steps, compensation stack, data (JSON), version |
| Correlation | A start event's business key (StartWith(e => key)), CorrelateBy<TEvent>(e => key) for later events, and the id of each command sent (its replies' causation id) |
| Transaction | Each message is applied in the inbox's transaction: the inbox receipt, the instance, its history and the outgoing messages commit together |
| Status | Running, Compensating, Completed and Compensated (terminal), Failed (needs an operator; not terminal) |
The three models:
- Orchestration: steps send commands and wait for replies (above).
- Hybrid: an orchestrated core, plus events published with
OnCompleted,OnCompensated,OnFailedor a step'sPublish(...), which other services consume on their own. - Choreography: services react to each other's events with Xpandables.Events alone. An observing saga follows
such a flow:
Observe<TEvent>()withCorrelateBy, explicit states, and a deadline that publishes an event when the flow stalls.
🪜 Steps
| Builder | Effect |
|---|---|
Step("Name") / Step<TStep>() |
A step, run after the previous one (SagaStep<TData> for a reusable step) |
Parallel("Name", p => { p.Step(...); p.Step(...); }) |
Branches sent together; the saga goes on when all completed |
.Send(d => command) |
The command (an IntegrationEvent): sent when the step starts, and again on each retry |
.On<TReply>((d, e) => …) |
A success reply |
.FailOn<TReply>(e => new SagaFailure(reason, IsTransient)) |
A failure reply |
.ExtendedBy<TProgress>() |
A heartbeat: each progress event re-arms the timeout |
.Timeout(…), .Retry(policy) |
Section Timeouts and retries |
.CompensateWith(d => command), .CompensationConfirmedBy<TReply>() |
Section Compensation |
.Pivot() |
The point of no return |
.Retriable() |
Every failure is transient (a step after the pivot that must eventually succeed) |
.Publish(d => event) |
An event published when the step completes |
A command identifies itself to its participant: give it a business idempotency key (the order id). A retry is a new message (a new event id), so the participant's inbox does not deduplicate it; its business key does.
🔀 State machines
For a non-linear process, declare states and transitions; entering a step's or a group's state sends its commands.
saga.StartWith<AuctionOpened>(e => e.AuctionId, (context, e) =>
context.Schedule(new AuctionClosingTime { AuctionId = e.AuctionId }, context.Now + e.Duration))
.CorrelateBy<BidPlaced>(e => e.AuctionId)
.CorrelateBy<AuctionClosingTime>(e => e.AuctionId)
.InitialState("Open");
saga.During("Open")
.On<BidPlaced>().When((d, e) => e.Amount > d.BestBid).Then((context, e) => context.Data.BestBid = e.Amount).Stay()
.On<AuctionClosingTime>().TransitionTo("Settling");
saga.Step("Settling").Send(d => new ChargeWinnerRequested { AuctionId = d.AuctionId }).On<WinnerCharged>();
Then actions see an ISagaContext<TData>: the data, the message, Now (the registered TimeProvider: the only clock
an action reads), and Send, Publish, Schedule, SetMetadata. Actions are deterministic and do no I/O: what they
send is written to the outbox in the transaction.
An event the saga does not expect in its current state follows WhenUnexpected(...): Ignore (the default: recorded in
the history), Defer (thrown back to the inbox, retried later) or Fail.
The registry checks a definition when the host starts: a start event, a success reply per step, no pivot in a parallel
group, no transition to an unknown state, no reserved state name. definition.ToMermaid() draws it.
↩️ Compensation
When a step fails with no retry left (or times out, or the deadline elapses, or the saga is cancelled), the saga enters
Compensating and undoes its completed steps in reverse order: each CompensateWith command is sent; with
CompensationConfirmedBy<TReply>(), the saga waits for its confirmation before the previous one. Then it is
Compensated and OnCompensated publishes its event.
- The step in flight whose outcome is unknown (timed out, deadline, cancellation) is compensated too. A compensation must therefore be idempotent and succeed when there is nothing to undo.
- Parallel groups: when a branch fails, the saga waits for the other branches in flight, then compensates every completed one.
- Late success: a success reply of an abandoned step (after its compensation) sends its compensation again.
- Pivot: once the pivot completed, nothing is compensated; a later failure makes the saga
Failed. - A compensation that fails (no confirmation before its timeout, retries exhausted) makes the saga
Failed(CompensationFailed), for an operator.
⏱️ Timeouts and retries
| Mechanism | How |
|---|---|
| Step timeout | SagaTimeoutElapsed scheduled in the outbox (NotBefore) with a token; ignored if the step moved on |
| Deadline | Deadline(…): one SagaDeadlineElapsed; a running saga compensates (or fails past its pivot) |
| Business retry | A transient failure or a timeout schedules the step again after the backoff (SchedulerBackoff, ±20 % jitter), up to MaxAttempts; persisted, it survives restarts |
| Transport retry | A failure of the engine itself (database, concurrency conflict) is retried by the inbox, then suspended |
Timeouts are delivered by the relay when they fall due: precise to the relay's run, for business delays (minutes,
hours), not sub-second ones. ISagaFailurePolicy (default SagaFailurePolicy) decides retry, compensate or fail;
replace it with AddXSagaFailurePolicy<T>().
🔒 Consistency and delivery
BEGIN
inbox receipt of the message (saga:{SagaName})
instance UPDATE … WHERE Version = @expected
history, correlation keys
outbox: commands, published events, timeouts
COMMIT → the relay is signalled, then publishes
- No lost message, no ghost message: the outgoing messages are outbox rows of the same commit.
- Effectively once: a redelivered message finds its inbox receipt (a duplicate); two messages for one instance at once conflict on its version, and the loser is retried by the inbox.
- External effects (an HTTP call) belong to participants, behind their own inbox, with an idempotency key.
- Same database: the saga tables, the outbox and the inbox must be in the database of the events unit of work. An
EF Core
DbContextbuilt on that unit of work's connection joins its transaction (EntityUnitOfWork.UseTransactionAsync(transaction.DbTransaction)). - Transport: any
IEventBuswith at-least-once delivery, the envelope's headers kept, ordering per partition key when available (a saga's commands use its id).
🛠️ Operations
ISagaManager reads an instance, and asks it to cancel (CancelAsync, refused past the pivot) or to resume
(RetryAsync, for a failed saga): both are messages to the saga through the outbox, serialized with the messages in
flight. ISagaStore answers the monitoring queries (QueryAsync, CountByStatusAsync, CountOverdueAsync,
CountActiveByVersionAsync), ISagaAuditStore reads the history.
HTTP endpoints, behind a required authorization policy: app.MapXSagaOperations("ops") (package
Xpandables.AspNetCore.Sagas) and app.MapXEventOperations("ops") (Xpandables.AspNetCore.Net, the outbox and inbox dead
letters).
| Endpoint | |
|---|---|
GET /_ops/sagas?name=&status=&deadlineBefore=&skip=&take= |
Instances, newest first |
GET /_ops/sagas/counts?name= |
By status |
GET /_ops/sagas/{id}, GET /_ops/sagas/{id}/history |
An instance and its audit trail |
POST /_ops/sagas/{id}/cancel {"reason": "…"}, POST /_ops/sagas/{id}/retry |
202, the operator recorded |
GET /_ops/sagas/definitions, GET /_ops/sagas/definitions/{name}/{version}/diagram |
Definitions, Mermaid diagram |
GET /_ops/events/outbox, GET /_ops/events/outbox/parked, POST …/parked/{id}/requeue, POST …/parked/requeue, DELETE …/parked?olderThan= |
Outbox dead letters |
GET /_ops/events/inbox/suspended?consumer=, POST …/suspended/{id}/requeue?consumer=, POST …/suspended/requeue, DELETE …/suspended?olderThan= |
Inbox dead letters |
Retention: AddXSagaRetention(o => o.Ended = TimeSpan.FromDays(30)) purges completed and compensated instances
(with their keys and history) on the schedule of AddXEventRetention(); HistoryHorizon prunes the history of
long-lived sagas (the creation record is kept). Failed instances are never purged.
Versions: a breaking change of a saga is a new class with [SagaName("…", Version = 2)]. Keep the old class
registered while instances run on it (CountActiveByVersionAsync); an instance whose version is no longer registered
is an orphan: the health check and the xpandables.sagas.orphans gauge report it.
📈 Observability
ActivitySource and Meter named Xpandables.Sagas:
builder.Services.AddOpenTelemetry()
.WithTracing(t => t.AddSource("Xpandables.Sagas", "Xpandables.Events"))
.WithMetrics(m => m.AddMeter("Xpandables.Sagas", "Xpandables.Events"));
| Instrument | Type | Tags |
|---|---|---|
xpandables.sagas.started, .completed, .compensated, .failed, .timed_out |
counter | xpandables.saga.name |
xpandables.sagas.steps.completed, .failed, .retried, .compensated |
counter | xpandables.saga.name, xpandables.saga.step |
xpandables.sagas.messages.ignored, xpandables.sagas.concurrency_conflicts |
counter | xpandables.saga.name |
xpandables.sagas.duration |
histogram (s) | xpandables.saga.name, xpandables.saga.end |
xpandables.sagas.step.duration |
histogram (s) | xpandables.saga.name, xpandables.saga.step |
xpandables.sagas.instances |
gauge | xpandables.saga.status |
xpandables.sagas.overdue, xpandables.sagas.orphans |
gauge |
The gauges are counted at most every 30 seconds while they are observed. Each message a saga handles is a span
saga {SagaName} {EventName} under the inbox's consume span; the outbox carries the trace context, so a saga is one
distributed trace. AddXSagaHealthCheck() reports Degraded while instances are failed, overdue or orphans.
A tested reference stack (Prometheus with its OTLP receiver, Grafana dashboards and alert rules, the Aspire dashboard)
is in Samples/observability.
📕 Runbooks
A saga failed (status=failed, alert XpandablesSagaFailed)
GET /_ops/sagas/{id}:end.reasonandend.detailsay why;GET …/historyshows the last steps.StepFailed/TimedOutpast the pivot: fix the cause (the participant, its dependency), thenPOST …/retry: the active step is sent again, attempts reset.CompensationFailed: the compensation's participant refused or timed out. Fix it, thenPOST …/retry: the compensation is sent again and the saga goes on compensating.- A saga that must be abandoned: settle it in the participants by hand, then cancel it (before its pivot) or leave it
Failed(it is never purged) with a note in your ticketing system.
Parked or suspended messages (alerts XpandablesOutboxParked, XpandablesInboxSuspended)
GET /_ops/events/outbox/parked/GET /_ops/events/inbox/suspended?consumer=:errorMessageholds the failure. Asaga:*consumer is a saga;saga:messagescarries the timeouts and operator requests.- Fix the cause (a bug, a missing event name or JSON metadata after a deployment), deploy.
- Requeue: the inbox receipt first (
POST …/suspended/{id}/requeue?consumer=), then the parked outbox event (POST …/parked/{id}/requeue). A requeued event keeps its partition order. - Purge only what must never be delivered (
DELETE …?olderThan=).
Sagas overdue (alert XpandablesSagaOverdue): their deadline message did not apply; it is parked or suspended:
follow the previous runbook, the deadline then applies.
Draining an old version: deploy the new class with Version = n + 1 next to the old one; new instances start on
it. Watch CountActiveByVersionAsync (or GET /_ops/sagas?…) until the old version has no instance not ended, then
remove its class.
Inbox retention: keep EventRetentionOptions.InboxProcessed above the longest redelivery window of your transport:
a redelivery after its receipt was purged runs the saga again (the state machine still ignores most of them).
🧪 Testing
SagaTestHarness<TSaga, TData> runs a saga without database, broker or host:
var harness = new SagaTestHarness<OrderSaga, OrderData>(AppJsonContext.Default);
harness.Publish(new OrderPlaced { OrderId = id, Total = 120m });
harness.Reply(harness.LastSent<ProcessPaymentRequested>(), new PaymentSucceeded { OrderId = id, PaymentId = paymentId });
harness.AdvanceTime(TimeSpan.FromMinutes(10)); // delivers the due timeouts and scheduled messages
Assert.Equal("Delivery", harness.Instance.CurrentState);
Assert.Single(harness.Sent.OfType<ReleaseStockRequested>());
Reply sets the command's id as the reply's causation id; Cancel and Retry act as an operator; History, Sent,
Scheduled, Data and LastOutcome show what happened. The retries run without jitter, so their times are exact.
🚀 Native AOT
Sagas are registered with closed types: AddXSaga<TSaga>() runs Configure, whose generic methods register the inbox
consumer of each event (SagaEventConsumer<TSaga, TEvent>); nothing is closed at run time. Data and messages are
serialized through the registered JSON context (checked at startup). The operations endpoints are plain request
delegates writing source-generated JSON. The repository's AotProbe publishes a saga flow and the endpoints with 0 trim
and AOT warnings.
AddX{Assembly}Sagas() (Xpandables.Generators) registers every saga of an assembly. A saga that cannot be referenced
by generated code (generic, inaccessible, without a public parameterless constructor) is reported as XSG001;
[ExcludeFromRegistration] leaves one out.
📚 Reference
| Type | Role |
|---|---|
Saga<TData>, SagaStep<TData>, [SagaName] |
A saga, a reusable step, the persisted name and version |
ISagaBuilder<TData>, ISagaStepBuilder<TData>, ISagaParallelBuilder<TData>, ISagaStateBuilder<TData>, ISagaTransitionBuilder<TData, TEvent> |
The declaration |
ISagaContext<TData> |
What an action sees |
ISagaDefinition, ISagaRegistry |
The compiled definitions |
ISagaEngine |
Applies a message (default: in the inbox's transaction) |
ISagaStore (SagaStore), ISagaTableScriptProvider (SagaTableScriptProviders) |
Persistence and scripts (SQL Server, PostgreSQL, SQLite) |
ISagaManager, ISagaAuditStore, ISagaAuditSink |
Operations, audit trail, audit forwarding (after commit) |
ISagaFailurePolicy (SagaFailurePolicy), SagaRetryPolicy, SagaFailure |
Failures and retries |
SagaInstance, SagaActiveStep, SagaHistoryRecord, SagaQuery, SagaStatus, SagaEnd, SagaEndReason |
Values |
SagaTimeoutElapsed, SagaDeadlineElapsed, SagaCancellationRequested, SagaRetryRequested, SagaJsonContext |
The saga messages and their JSON metadata |
SagaHealthCheck, SagaHealthOptions, SagaRetentionOptions |
Health and retention |
SagaTestHarness<TSaga, TData> |
Unit tests |
SagaConcurrencyException, SagaEventDeferredException, SagaDefinitionException |
Errors |
📄 License
Apache License 2.0 — see the LICENSE file for details.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Extensions.DependencyInjection (>= 11.0.0)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 11.0.0)
- Microsoft.Extensions.Hosting (>= 11.0.0)
- Xpandables.Events (>= 11.0.0)
- Xpandables.Generators (>= 11.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Xpandables.Sagas:
| Package | Downloads |
|---|---|
|
Xpandables.AspNetCore.Sagas
ASP.NET Core operations endpoints of Xpandables.Sagas: query saga instances, read their history, cancel, retry and draw their definitions, behind a required authorization policy; Native AOT compatible. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.0.0 | 0 | 11/29/2026 |