Compensable 1.1.0-alpha.1

This is a prerelease version of Compensable.
dotnet add package Compensable --version 1.1.0-alpha.1
NuGet\Install-Package Compensable -Version 1.1.0-alpha.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="Compensable" Version="1.1.0-alpha.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Compensable --version 1.1.0-alpha.1
#r "nuget: Compensable, 1.1.0-alpha.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.
// Install Compensable as a Cake Addin
#addin nuget:?package=Compensable&version=1.1.0-alpha.1&prerelease

// Install Compensable as a Cake Tool
#tool nuget:?package=Compensable&version=1.1.0-alpha.1&prerelease


A library to facilitate the compensating (rolling back) of a series of successfully completed workflow steps when an exception occurs.

Where do I get it

Compensable can be installed using the Nuget package manager

PM> Install-Package Compensable

or the dotnet CLI.

dotnet add package Compensable

How to get started

  1. Define a compensator.

    Compensator is for use in synchronous contexts and only supports synchronous executions, compensations, and tests.

    // using Compensable;
    var compensator = new Compensator();

    AsyncCompensator is for use in asynchronous contexts and supports both synchronous and asynchronous executions, compensations, and tests.

    // using Compensable;
    var asyncCompensator = new AsyncCompensator();
  2. Execute the steps of your workflow in the context of the compensator.

    • Upon successful completion of a step's execution, its defined compensation is added to the top of an internal stack. If a compensateAtTag is specified the compensation will be inserted at the position of the tag. See Tags for more details.

    • If an exception is thrown in any execution, test, or items enumeration, then the compensations in the stack are called in reverse order and the original exception is re-thrown.

    • If an exception is thrown when calling a compensation, then a CompensationException is thrown that contains WhileExecuting and WhileCompensating properties and whose inner exception is also the original WhileExecuting exception. See CompensateAsync for its alternate behavior.

    Overloads are available for steps that do not require compensation, non-method-based tests, and for AsyncCompensator, calling both async and non-async target methods.

    • Do / DoAsync - executes a step that does not return a result.

          execution: () => step(),
          compensation: () => compensateStep(),
          compensateAtTag: null);
      await asyncCompensator.DoAsync(
          execution: async () => await stepAsync(),
          compensation: async () => await compensateStepAsync(),
          compensateAtTag: null);
    • Get / GetAsync - executes a step that returns a result.

      Its compensation can optionally define a _result parameter that is equivalent to result, but will be unaffected if result is reassigned. Be aware that if result is an object whose properties are reassigned, the compensation will be affected as well.

      var result = compensator.Get(
          execution: () => step(),
          compensation: (_result) => compensateStep(_result),
          compensateAtTag: null);
      var result = await asyncCompensator.GetAsync(
          execution: async () => await stepAsync(),
          compensation: async (_result) => await compensateStepAsync(_result),
          compensateAtTag: null);
    • DoIf / DoIfAsync - executes a step if its test evaluates to true.

          test: () => test(),
          execution: () => step(),
          compensation: () => compensateStep(),
          compensateAtTag: null);
      await asyncCompensator.DoIfAsync(
          test: async () => await testAsync(),
          execution: async () => await stepAsync(),
          compensation: async () => await compensateStepAsync(),
          compensateAtTag: null);
    • Foreach / ForeachAsync - executes a step per item in an IEnumerable<T>.

      If the item enumerator or execution throws an exception, then remaining items are not executed.

      // var items = new[] { "item1", "item2", "item3" };
          items: items,
          execution: (item) => step(item),
          compensation: (item) => compensateStep(item),
          compensateAtTag: null);
      // var items = new[] { "item1", "item2", "item3" };
      await asyncCompensator.ForeachAsync(
          items: items,
          execution: async (item) => await stepAsync(item),
          compensation: async (item) => await compensateStepAsync(item),
          compensateAtTag: null);
    • AddCompensation / AddCompensationAsync - defines a step that only provides compensation.

          compensation: () => compensateStep(),
          compensateAtTag: null);
      await asyncCompensator.AddCompensationAsync(
          compensation: async () => await compensateStepAsync(),
          compensateAtTag: null);
    • Commit / CommitAsync - clears all defined compensations from the stack without calling them.

      await asyncCompensator.CommitAsync();
    • Compensate / CompensateAsync - invokes compensation directly.

      If an exception occurs when calling a compensation, then a CompensationException is thrown that only contains a WhileCompensating value and whose inner exception is also the WhileCompensating exception.

      await asyncCompensator.CompensateAsync();
    • CreateTag / CreateTagAsync - defines a "tagged" position in the stack. See Tags for more details.

      var tag = compensator.CreateTag();
      var tag = await asyncCompensator.CreateTagAsync();


Compensations are types that a step's execution can return that encapsulate the compensation logic so that a calling compensator does not have to know the implemenation.

There are four types that apply to different scenarios.

  • Compensation - a synchrous compensation.
  • Compensation<TResult> - a synchronous compensation with a Result.
  • AsyncCompensation - an asynchronous compensation.
  • AsyncCompensation<TResult> - an asynchronous compensation with a Result.

Each type defines one or more constructors that accept a compensation action, and a result for TResult types. In addition, each compensation also defines either a static Noop property or method for use when a step's internal logic does not need compensation.

When used with a compensator, the returned compensation is added to the compensation stack, and in the case of Get / GetAsync steps, the applicable result is returned.

When used without a compensator, each compensation type defines a Compensate / CompensateAsync method that can be called to invoke the defined compensation. In the case of a (Async)Compensation<TResult> a Result property contains the result, but the compensation type also implements an implicit type conversion.

Disclaimer: this example is to demonstrate the use of Compensations and should NOT be considered a good example of application security.

internal enum AccountStatus { Active, Inactive };

internal class Account
    private readonly ISsoTokenRepository _ssoTokenRepository;

    public string Id { get; }

    public AccountStatus Status { get; private set; }

    public Compensation SetStatus(AccountStatus status)
        // short-circuit status is already set
        if (Status == status)
            return Compensation.Noop;

        // capture compensation data
        var rollback = new { Status };

        // update status
        Status = status;

        // return compensation
        return new Compensation(() =>
            Status = rollback.Status;

    public async Task<AsyncCompensation<string>> GenerateSsoTokenAsync()
        // generate a token
        var token = Guid.NewGuid().ToString("n");

        // store token
        await _ssoTokenRepository.CreateAsync(Id, token);

        // return token + compensation (in case an exception occurs and we need to delete token)
        return new AsyncCompensation<string>(
            result: token, 
            compensation: _ssoTokenRepository.DeleteToken);


The compensator exposes a Status property that can be used to inspect its current internal state.

If the Status is anything other than Executing, it cannot be used for executing additional steps. Attempts to do so will result in a CompensatorStatusException being thrown.

  • Executing - the compensator is idle or executing a step.

  • FailedToExecute - a step's execution has failed, but compensation has not yet started.

  • Compensating - the compensator is compensating steps in the compensation stack.

  • Compensated - the compensator has successfully compensated all steps.

  • FailedToCompensate - the compensator failed to compensate a step in the stack.


Tags define a position in the stack.

  • They do nothing unless a step defines a compensation that should compensateAtTag. When that happens the compensation is pushed into the stack at the position of the tag instead of the top of the stack.

  • More than one step can reference the same tag, and their compensations will be called in reverse order when compensating.

  • If a tag does not exist in the stack, a TagNotFoundException will be thrown.

Tags should be used sparingly!

// create tag
var tag = await asyncCompensator.CreateTagAsync();

// step 1
await asyncCompensator.DoAsync(
    async () => await step1Async(),
    compensation: async () => await compensateStep1Async());

// step 2
await asyncCompensator.DoAsync(
    async () => await step2Async(),
    compensation: async () => await compensateStep2Async(),
    compensateAtTag: tag);

// compensate
// compensateStep1Async will be called first, followed by compensateStep2Async.
await asyncCompensator.CompensateAsync();

Practical Example

This example creates an email service on an async email platform and stores a reference to it in a non-async account service repository. A tag is used alter the compensation stack to delete the entry from the local account service repository last.

public async Task CreateEmailAsync(
    Guid accountId,
    string domainName,
    int mailboxQuota,
    int diskQuotaMb,
    string adminMailboxAddress,
    string adminMailboxPassword,
    int adminMailboxDiskQuotaMb,
    bool adminMailboxIsCatchall,
    string[] adminAliasAddresses)
    // define a new compensator
    var compensator = new AsyncCompensator();

    // define a tag
    var deleteFromRepositoryTag = await compensator.CreateTagAsync();

    // create email service on the email platform
    // on compensate delete the email service and any mailboxes
    var emailServiceId = await compensator.GetAsync(
        async () =>
            return await _emailPlatform.CreateServiceAsync(
        compensation: async (_emailServiceId) =>
            await _emailPlatform.DeleteServiceAsync(_emailServiceId);

    // add an email service to the account service repository
    // on compensate remove the email service from the repository at the deleteFromRepositoryTag
    await compensator.DoAsync(
        () =>
            _accountServiceRepository.Create(accountId, "Email", platformId: emailServiceId);
        compensation: () =>
            _accountServiceRepository.Delete(accountId, "Email");
        compensateAtTag: deleteFromRepositoryTag);

    // create admin mailbox
    // no compensation necessary
    await compensator.DoAsync(
        async () =>
            await _emailPlatform.CreateAdminMailboxAsync(emailServiceId,

    // optionally set admin mailbox as the catchall
    // no compensation necessary
    await compensator.DoIfAsync(adminMailboxIsCatchall,
        async () =>
            await _emailPlatform.SetCatchallAsync(emailServiceId, adminMailboxAddress);

    // create aliases
    // no compensation necessary
    await compensator.ForeachAsync(adminAliasAddresses,
        async (adminAliasAddress) =>
            await _emailPlatform.CreateAliasAsync(


In order to ensure a predictable order of operations, the compensator is intended to be single-threaded. However, it is thread-safe through a set of execution, compensation, and status locks.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

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
1.1.0-alpha.1 191 10/20/2023
1.0.0 751 2/22/2023
0.4.0-beta-4 110 11/5/2022
0.3.1-beta-3 123 10/10/2022
0.3.0-beta-3 110 10/10/2022
0.2.4-beta-2 116 10/8/2022
0.2.3-beta-2 119 10/7/2022
0.2.2-beta-1 123 10/4/2022
0.2.1-beta-1 111 10/4/2022
0.2.0-beta-1 115 10/4/2022
0.1.1-beta-1 125 9/26/2022
0.1.0-beta-1 153 9/22/2022
0.0.0-alpha-1 132 9/20/2022