Software Architecture

Saga pattern in .NET: when the payment went through and the stock did not

Team Nippysoft
• • 15 min read
Saga pattern in .NET: when the payment went through and the stock did not

An online store charges a customer, and a moment later the inventory service answers that the item is out of stock. The money has already left the customer's card. Who gives it back? And who finds out when the refund fails too?

This post answers with the Saga pattern and one order from start to finish: order-1001, 2 mugs for 30. Without a saga, the customer pays for an order that never ships. With one, the charge is refunded and the order cancelled; if the refund fails too, the saga is flagged for a person to look at. The ideas come first, in plain words; then the code and the .NET libraries for production.

The code is in a .NET 10 repository, with automated tests for each case. Everything runs in memory, with no broker and no database, so every scenario repeats exactly.

A saga does not stop a step from failing. It gives you a written path to undo the earlier steps and a record of where each order stopped.

Why the refund does not happen on its own

A transaction is a group of changes saved whole or not at all. If something fails halfway, the database undoes what was done: that is a rollback. In a single database, the charge and the reservation would share one transaction, and a failed reservation would erase the charge. That guarantee is called ACID, for atomicity, consistency, isolation and durability.

With several services, that is no longer enough. A service, or microservice, is a program with its own database; here there are four: orders, payments, inventory and email. Payments saves the charge in its database, inventory tries the reservation in its own, and no transaction spans both. The classic way out is 2PC (two-phase commit), a protocol that lets several databases commit together, but many do not support it. In the words of the .NET microservices guide, "most NoSQL databases (like Azure Cosmos DB, MongoDB, etc.) do not support two-phase commit transactions".

Real life works the same way: you pay at the register, and when the clerk goes to the stockroom, the item is not there. Nobody un-swipes your card; the store issues a refund, a separate operation with its own receipt.

The repo starts with the version without a saga, five calls in a row:

public static void PlaceOrder(Shop shop, OrderRequest order)
{
    shop.Orders.Create($"{order.OrderId}:create", order.OrderId);
    shop.Payments.Charge($"{order.OrderId}:charge", order.OrderId, order.Amount);
    shop.Inventory.Reserve($"{order.OrderId}:reserve", order.OrderId, order.Sku, order.Quantity);
    shop.Orders.Confirm($"{order.OrderId}:confirm", order.OrderId);
    shop.Email.SendConfirmation($"{order.OrderId}:email", order.OrderId);
}

With a single mug in stock, the reservation throws and nothing after it runs:

naive checkout threw: inventory.reserve: only 1 of mug left
## 1. Before: no saga, 1 mug in stock
money held: 30 | charges made: 1 | refunds: 0
mugs in stock: 1 | order: Pending | emails: 0

That leaves 30 charged, no refund, and the order in Pending forever. Every line does what it says; what is missing is a plan for when the third step fails.

An idea from 1987 that was not about microservices

A saga is a sequence of local transactions, one per service. Every step that can be undone comes with its compensation: the action that reverses it in business terms, such as refunding the charge or putting the mugs back on the shelf. When a step fails, the compensations of the earlier steps run.

The name comes from a technical report by Garcia-Molina and Salem at Princeton, and it says nothing about microservices. It is about long transactions inside one database: while they run, they hold resources and make the short ones wait. The proposal was to split them into short transactions that interleave with others, with one of two endings guaranteed: either they all finish, or the ones that ran get compensated. In the paper's notation, T1…Tn, or T1…Tj followed by Cj…C1.

Its example is booking several airline seats: "We would not be satisfied with a DBMS that would allow T to reserve three out of five seats and then (due to a crash) do nothing more". The paper also uses a purchase order, with the order, the inventory and accounting: the mug example, almost 40 years earlier.

The idea moved to microservices because it fills the same gap: there is no big transaction at hand. Chris Richardson sums it up in his pattern catalog as "a reliably coordinated sequence of local transactions".

The order in five steps

In the repo, an orchestrator, the object that decides which step comes next, runs the steps in order. Each step is a SagaStep with its action and, when it can be undone, its compensation. The steps that can be undone come first, the ones that cannot come last:

public static IReadOnlyList<SagaStep> For(Shop shop) =>
[
    new("create-order",
        c => shop.Orders.Create(c.KeyFor("do"), c.Order.OrderId),
        c => shop.Orders.Cancel(c.KeyFor("undo"), c.Order.OrderId)),
    new("charge-payment",
        c => shop.Payments.Charge(c.KeyFor("do"), c.Order.OrderId, c.Order.Amount),
        c => shop.Payments.Refund(c.KeyFor("undo"), c.Order.OrderId)),
    new("reserve-stock",
        c => shop.Inventory.Reserve(c.KeyFor("do"), c.Order.OrderId, c.Order.Sku, c.Order.Quantity),
        c => shop.Inventory.Release(c.KeyFor("undo"), c.Order.OrderId)),
    // Point of no return: from here on the saga only moves forward.
    new("confirm-order",
        c => shop.Orders.Confirm(c.KeyFor("do"), c.Order.OrderId)),
    new("send-email",
        c => shop.Email.SendConfirmation(c.KeyFor("do"), c.Order.OrderId)),
];

Every call gets a key that comes out the same on every retry, KeyFor("do") or KeyFor("undo"); its purpose shows up further down. With 5 mugs in stock, the saga ends Completed: 30 charged, 3 mugs left, the order Confirmed, one email and 12 log entries, one at the start, one at the end and a pair per step, before and after calling the service.

Undoing is not going back

Compensations run in reverse order: the last thing done is undone first. When the reservation fails, the orchestrator walks the started steps from newest to oldest:

// Undo every step that was started, newest first. A step that failed is undone too:
// it may have applied its change before the error (a timeout after the charge).
foreach (var step in _steps.Where(s => s.IsCompensable && state.Started.Contains(s.Name)).Reverse())
{
    if (state.Compensated.Contains(step.Name))
        continue;
    var failure = await TryAsync(() => step.Compensate!(new StepContext(sagaId, step.Name, order)));
    if (failure is not null)
        return Stuck(sagaId, $"undo of {step.Name} failed: {failure.Message}");
    Write(sagaId, SagaEventType.StepCompensated, step.Name);
    state.Compensated.Add(step.Name);
}

Write(sagaId, SagaEventType.Compensated, detail: state.Reason);
return new SagaOutcome(sagaId, SagaStatus.Compensated, state.Reason);

With a single mug, the log reads:

outcome: Compensated (inventory.reserve: only 1 of mug left)
money held: 0 | charges made: 1 | refunds: 1
mugs in stock: 1 | order: Cancelled | emails: 0
  log: Started
  log: StepStarted create-order
  log: StepCompleted create-order
  log: StepStarted charge-payment
  log: StepCompleted charge-payment
  log: StepStarted reserve-stock
  log: CompensationRequested reserve-stock | inventory.reserve: only 1 of mug left
  log: StepCompensated reserve-stock
  log: StepCompensated charge-payment
  log: StepCompensated create-order
  log: Compensated | inventory.reserve: only 1 of mug left

Result: 0 held, 1 charge and 1 refund, the mug still in stock and the order Cancelled.

Compensating does not put the database back the way it was either. The paper explains it with the seats: to cancel a reservation you subtract one from the counter instead of writing the old number, because others may have booked in between. That is why Release adds the reserved units to the current stock instead of setting a value. And the business sets its own rules; in the Compensating Transaction pattern, Microsoft gives an example: "canceling a flight reservation might not entitle the customer to a complete refund".

Some steps are never undone. Confirming the order and sending the email come after the point of no return: if they fail, they are retried, and nobody gets a refund over an email that did not go out. Microsoft's Saga guidance calls the step that marks that point the pivot and asks for the steps after it to be idempotent: running them again leaves the same result as running them once. In the repo, the pivot is the last step that can be undone, the reservation, and the orchestrator rejects a step with a compensation placed after one without it.

The step that failed is compensated too, because it may have applied its change before the error, like a charge that went through and whose answer was lost to a timeout. That is why Refund with no charge and Release with no reservation do nothing. The Temporal guide asks the same of that compensation: "its implementation must be idempotent".

There is the reverse case too, which the repo cannot show because its services answer at once: on a real network, the charge that timed out can arrive after the refund and go through. To close it, payments has to remember that the order was already refunded and reject a later charge.

Choreography or orchestration

So far, the orchestrator decides which step comes next. The other style is choreography: with no coordinator, each service reacts to events, messages that say something happened. In production a broker carries them, the messaging system between services, such as RabbitMQ or Azure Service Bus.

The repo runs the same order with events, on an in-memory bus. With one mug, the chain is OrderPlaced, PaymentCharged, StockRejected and PaymentRefunded, and the order ends Cancelled. To learn what happens when stock runs out, you have to follow three handlers in three services; these are the orders and payments ones:

// Orders
bus.Subscribe<OrderPlaced>(e => shop.Orders.Create($"{e.OrderId}:create", e.OrderId));
bus.Subscribe<StockReserved>(e => shop.Orders.Confirm($"{e.OrderId}:confirm", e.OrderId));
bus.Subscribe<PaymentDeclined>(e => shop.Orders.Cancel($"{e.OrderId}:cancel", e.OrderId));
bus.Subscribe<PaymentRefunded>(e => shop.Orders.Cancel($"{e.OrderId}:cancel", e.OrderId));

// Payments
bus.Subscribe<OrderPlaced>(e =>
{
    try
    {
        shop.Payments.Charge($"{e.OrderId}:charge", e.OrderId, e.Amount);
        bus.Publish(new PaymentCharged(e.OrderId, e.Sku, e.Quantity));
    }
    catch (BusinessRuleException ex)
    {
        bus.Publish(new PaymentDeclined(e.OrderId, ex.Message));
    }
});
bus.Subscribe<StockRejected>(e =>
{
    shop.Payments.Refund($"{e.OrderId}:refund", e.OrderId);
    bus.Publish(new PaymentRefunded(e.OrderId));
});

The refund lives in payments, the cancel in orders, and the full flow is not written down anywhere. That is the cost. The repo's bus also does not retry: if inventory times out, the exception goes up to whoever published OrderPlaced, with the charge made and the order in Pending, because the handler only catches business errors. A real broker adds one more risk: a service that saves its change and crashes before publishing the event. For that, Richardson proposes the Transactional Outbox, which the repo does not have.

Microsoft's guidance compares both styles. Choreography suits simple workflows with few services and adds no single point of failure, but it gets confusing as steps are added and is hard to test. Orchestration fits complex workflows, at the price of writing the coordination and adding a point of failure. A rule of thumb: few steps and one team, choreography; many steps, compensations or several teams, orchestration.

When the refund fails too

The 1987 paper already raised this case: if a compensation cannot finish because of an error, such as a missing file or a bug, "the system is stuck: it cannot abort the transaction nor can it complete it". The repo handles it with four pieces.

Retry only what can change

A timeout may succeed on the second try; running out of stock will fail the same way every time. RetryPolicy retries only TransientException, waiting 1 s and then 2 s across 3 attempts; any other exception goes straight up.

public async Task ExecuteAsync(Action call)
{
    for (var attempt = 1; ; attempt++)
    {
        try
        {
            call();
            return;
        }
        catch (TransientException) when (attempt < MaxAttempts)
        {
            var delay = BaseDelay * Math.Pow(2, attempt - 1);
            Waits.Add(delay);
            await _wait(delay);
        }
    }
}

It has no jitter, a random variation in each wait, and no cap on total time: with many clients at once, they can all hit the recovering service together. The rule is Microsoft's: "Only stop the operation and trigger compensation if the step fails repeatedly or you can't recover it".

One key per step, so nobody is charged twice

A retry can reach a service that already applied the change. Every call carries a fixed key, {SagaId}:{Step}:{action}, and a service that has seen it before does not apply the change again:

protected void Run(string operation, string idempotencyKey, Action apply)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(idempotencyKey);

    // The planned fault plays the network or the service being down, so it comes first.
    var fault = faults.Take(operation);
    if (fault == Fault.Transient)
        throw new TransientException($"{operation}: service unavailable");
    if (fault == Fault.Business)
        throw new BusinessRuleException($"{operation}: rejected");

    // Same key seen before: the change is already there, so it is not applied again.
    // In a real service the change and the key are saved in the same database transaction.
    if (!_appliedKeys.Contains(idempotencyKey))
    {
        apply();
        _appliedKeys.Add(idempotencyKey);
        AppliedCount++;
    }

    if (fault == Fault.ApplyThenTimeout)
        throw new TransientException($"{operation}: timeout after the change was applied");
}

It is the idea behind the post on idempotency in ASP.NET Core and Stripe's keys: a charge that went through and lost its answer ends, after the retry, as a single charge. If you copy this, watch two things. A real service has to save the change and the key in the same database transaction; one that saves only the change charges twice on the retry. And the fake service does not compare the content: the same key with 300 instead of 30 is ignored without an error, where Stripe returns one. The orchestrator makes a similar check: it refuses a repeated sagaId with a different order.

A log that survives the crash

If the process dies between the charge and the next log entry, another process has to know where the saga stopped. The orchestrator writes StepStarted before calling the service and StepCompleted after, and FileSagaLog flushes each line to disk before moving on:

public void Append(SagaEvent e)
{
    var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(e, Json) + "\n");
    lock (_gate)
    {
        using var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
        TrimUnfinishedLine(file);
        file.Seek(0, SeekOrigin.End);
        file.Write(bytes);
        file.Flush(flushToDisk: true);
    }
}

If the process dies right after charging, the new one reads the log, sees the step started and not finished, retries it with the same key and ends with one charge; halfway through the undo, the refund is not issued twice either. The limit is the file: one writer per file. Two FileSagaLog objects writing to the same file at once, even inside one process, collide with IOException. Nothing stops two processes from resuming the same saga either, and two RunAsync calls with the same sagaId can start it twice: checking whether it exists and writing Started is not one atomic step. Resuming needs a lease (a lock that expires if its owner dies) or a row lock; for the double start, a unique constraint on the sagaId of the Started entry is enough. The idea comes from the paper: "Each saga command (e.g., begin-saga) is recorded in the log before any action is taken".

A person at the end of the line

If the refund fails on all 3 attempts, the orchestrator stops trying: it marks the saga Stuck, sends an alert with the reason, and SagaMonitor lists it along with the sagas that started a while ago and nobody resumed:

public static IReadOnlyList<SagaAlert> NeedsAttention(ISagaLog log, DateTimeOffset now, TimeSpan maxRunning)
{
    var alerts = new List<SagaAlert>();
    foreach (var sagaId in log.SagaIds())
    {
        var events = log.Read(sagaId);
        var last = events[^1];
        if (last.Type is SagaEventType.Completed or SagaEventType.Compensated)
            continue;
        if (last.Type == SagaEventType.Stuck)
            alerts.Add(new SagaAlert(sagaId, $"stuck: {last.Detail}"));
        else if (now - events[0].At > maxRunning)
            alerts.Add(new SagaAlert(sagaId, $"running for {(now - events[0].At).TotalMinutes:0} min, last entry {last.Type} {last.Step}".TrimEnd()));
    }
    return alerts;
}

With one mug and the refund service down, the saga ends like this:

outcome: Stuck (undo of charge-payment failed: payments.refund: service unavailable)
money held: 30 | charges made: 1 | refunds: 0
mugs in stock: 1 | order: Pending | emails: 0
retry waits: 1s, 2s
  log: Started
  log: StepStarted create-order
  log: StepCompleted create-order
  log: StepStarted charge-payment
  log: StepCompleted charge-payment
  log: StepStarted reserve-stock
  log: CompensationRequested reserve-stock | inventory.reserve: only 1 of mug left
  log: StepCompensated reserve-stock
  log: Stuck | undo of charge-payment failed: payments.refund: service unavailable

The 30 are still held, the mug is still in stock and the order is still Pending. That is what a person needs to see. Once someone fixes the service, ResumeAsync finishes the undo without repeating work already done; resumed before the fix, the saga gets stuck again and another alert goes out. What the monitor does not catch in time is a hung step that neither fails nor answers: there is no per-step timeout. And an exception other than TransientException or BusinessRuleException leaves RunAsync or ResumeAsync without marking the saga Stuck or sending an alert; the saga only shows up in the monitor once it passes its maximum time (maxRunning). Microsoft puts it this way: "the system should raise an alert that includes detailed information about the reason for the failure".

Before writing the first compensation, decide who gets the alert for a stuck saga and what data they need to fix it.

What to use in .NET for production

The repo uses no library: it is there to show the mechanics. For production, pick one of these, and read the license before installing:

ToolWhat it offers for sagasLicense
MassTransitState machines in C# for long-running, event-driven workflows, with instances kept in a saga repositoryv9 is commercial; v8 stays Apache-2.0, unsupported under the v9 agreement
NServiceBusSagas as Saga<T> classes, message-driven state machines, with optimistic or pessimistic locking depending on the persistenceDual license: RPL 1.5 (requires publishing your code) or Particular's commercial agreement; free outside production
Dapr WorkflowThe Dapr.Workflow package, with durable workflows that resume and a compensation pattern in the docsApache-2.0
Durable Functions or the Durable Task SDKAn orchestrator in C#: an activity's exception goes back to the orchestrator, which compensatesMIT; Azure hosting is paid separately
TemporalDurable workflows, with an official Saga sample in .NETMIT; Temporal Cloud is paid separately

Two more gaps in the repo

  • Isolation. While the saga runs, another request can see an order that is charged but has no stock reserved yet. Microsoft lists the anomalies (lost updates, dirty reads, fuzzy reads) and countermeasures such as a semantic lock, a flag saying the order is in progress; the repo implements none of them.
  • Currency. Amounts are not checked for precision or currency: an order for 0.001 is charged without complaint.

What a saga gives you

A saga does not prevent failure: it makes failure visible and reversible. The charge without stock becomes a refund with its line in the log, and the refund that does not go through becomes an alert with a name and a reason. For that, compensations need retries only for transient errors, an idempotent key per step, a log written before acting, and someone watching the stuck sagas.

Clone the repository, run dotnet test and watch the refund-down scenario with dotnet run --project tools/SagaDemo.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code