LinKit.Sagas 2.0.1

dotnet add package LinKit.Sagas --version 2.0.1
                    
NuGet\Install-Package LinKit.Sagas -Version 2.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LinKit.Sagas" Version="2.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LinKit.Sagas" Version="2.0.1" />
                    
Directory.Packages.props
<PackageReference Include="LinKit.Sagas" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LinKit.Sagas --version 2.0.1
                    
#r "nuget: LinKit.Sagas, 2.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LinKit.Sagas@2.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LinKit.Sagas&version=2.0.1
                    
Install as a Cake Addin
#tool nuget:?package=LinKit.Sagas&version=2.0.1
                    
Install as a Cake Tool

LinKit.Sagas

LinKit.Sagas provides saga state/step contracts, a coordinator for one explicitly supplied step at a time, and a replaceable repository abstraction.

The default repository is in-memory and volatile. This package does not provide a durable event log, distributed locking, or exactly-once execution.

Install

dotnet add package LinKit.Sagas

Define state and a step

using LinKit.Sagas;

public sealed class CheckoutSagaData : SagaData
{
    public Guid OrderId { get; set; }
    public bool ReservationCompleted { get; set; }
}

public sealed class ReserveStockStep(IStockService stock) :
    ISagaStep<CheckoutSagaData, OrderSubmitted>
{
    public async Task ExecuteAsync(
        CheckoutSagaData data,
        OrderSubmitted message,
        CancellationToken cancellationToken = default)
    {
        await stock.ReserveAsync(message.OrderId, cancellationToken);
        data.OrderId = message.OrderId;
        data.ReservationCompleted = true;
    }

    public async Task CompensateAsync(
        CheckoutSagaData data,
        OrderSubmitted message,
        CancellationToken cancellationToken = default)
    {
        if (data.ReservationCompleted)
        {
            await stock.ReleaseAsync(data.OrderId, cancellationToken);
            data.ReservationCompleted = false;
        }
    }
}

Register and execute

builder.Services.AddLinKitSagas<CheckoutSagaData>();
builder.Services.AddScoped<ReserveStockStep>();

var app = builder.Build();
var coordinator = app.Services.GetRequiredService<SagaCoordinator<CheckoutSagaData>>();
var step = app.Services.GetRequiredService<ReserveStockStep>();

await coordinator.ExecuteStepAsync(
    correlationId,
    submittedEvent,
    step,
    nextState: "StockReserved",
    cancellationToken);

The coordinator loads state by correlation ID or creates a new data object, runs the supplied step, updates CurrentState, and saves. If execution throws, it invokes that same step's compensation with a separate bounded token, records a compensated state when possible, and rethrows the original exception.

Concurrency and idempotent compensation

ISagaData carries two fields that the coordinator and the repository rely on:

  • Version — an optimistic concurrency token. ISagaRepository<TData>.SaveAsync must increment it and reject a save whose token no longer matches the persisted value by throwing SagaConcurrencyException. Two workers on the same correlation ID therefore cannot interleave; the loser reloads the state and decides whether the step should be retried.
  • CompensatedSteps — the ledger of steps that already ran their compensation. It is persisted with the state, so a redelivered saga (at-least-once transports redeliver) never undoes the same side effect twice. A compensation that throws is not recorded, so a later retry attempts it again.

The in-memory repository implements both, so the same code paths are exercised in tests.

public sealed class DurableSagaRepository<TData> : ISagaRepository<TData> where TData : class, ISagaData
{
    public Task SaveAsync(TData data, CancellationToken cancellationToken = default)
    {
        // UPDATE saga SET ..., version = @new, compensated_steps = @steps
        //  WHERE correlation_id = @id AND version = @data.Version
        // 0 rows affected -> throw new SagaConcurrencyException(data.CorrelationId, data.Version, actualVersion).
        throw new NotImplementedException();
    }

    // FindByCorrelationIdAsync and GetStuckAsync are the other two members.
}

Stuck sagas

ISagaRepository<TData>.GetStuckAsync(TimeSpan olderThan) returns every saga whose UpdatedAtUtc is older than the threshold — the signature of a step that threw after its side effect ran, or of a process that died mid-step. AddLinKitSagas<TData>() registers a background monitor that logs a warning with the correlation IDs whenever that set is non-empty.

builder.Services.AddLinKitSagas<CheckoutSagaData>(options =>
{
    options.StuckAfter = TimeSpan.FromMinutes(5);
    options.StuckSagaCheckInterval = TimeSpan.FromMinutes(1);
    options.EnableStuckSagaMonitor = true;      // default
    options.CompensationTimeout = TimeSpan.FromSeconds(30); // default
});

Production persistence

Register a durable ISagaRepository<TData> implementation before AddLinKitSagas<TData> so the default registration does not replace it. Because the in-memory fallback loses every in-flight saga on restart, resolution throws in the Production environment unless you opt in explicitly:

builder.Services.AddLinKitSagas<CheckoutSagaData>(options => options.AllowInMemoryInProduction = true);

Durable persistence alone does not make a saga operation exactly-once: protect step side effects with idempotency keys, and design recovery for crashes between the remote side effect and the state save. Saga history and compensation-failure recovery remain application/provider responsibilities.

Native AOT

The coordinator uses statically typed generic contracts; validate serialization and the concrete repository in the published application. AOT support of a custom persistence provider is outside this package.

License

MIT. See the repository license.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.1 90 11/8/2026
1.2.1 114 10/31/2026
1.2.0 105 10/30/2026
1.1.0 118 10/22/2026
1.0.0 121 10/20/2026

v2.0.1: documentation and packaging patch - every public member now carries XML documentation (CS1591 is enforced as a build error) and the README was reviewed for accuracy. Previous release: v2.0.0 - ISagaRepository gains optimistic concurrency (Version), idempotent compensation tracking and GetStuckAsync. In-memory repository is rejected in Production unless explicitly allowed. Full documentation & release notes: https://quoclinh.id.vn/docs/linkit