Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Saga Pattern Implementation in C#

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Saga Pattern runs in O(n) time and O(n) space, in C# as in every other language.
  • ✓The BCL pieces are Stack<Func<CancellationToken, Task>> for the undo stack, CancellationTokenSource and CreateLinkedTokenSource for bounding the forward path, AggregateException to carry the original plus compensation failures, and IAsyncDisposable with await using for scope-bound cleanup.
  • ✓Push a compensation delegate immediately after each awaited call, take a CancellationToken on every public async method, and use ConfigureAwait(false) in library code.
  • ✓The C# trap: The C#-only trap is async void: a compensation handler declared void cannot be awaited, so the unwind moves on immediately and its exception is rethrown on the captured SynchronizationContext or the thread pool rather than at your catch, taking the process down.
  • ✓Each await that actually suspends boxes the async state machine on the heap, so a twelve-step saga costs about a dozen small gen0 allocations plus one closure object per captured compensation; static lambdas taking state as a parameter remove the capture allocation entirely.

What Saga Pattern actually is

A saga replaces one distributed ACID transaction with a sequence of local transactions, each of which commits immediately and irreversibly. There is no global commit and no global rollback, so the only way back is forward: every step declares a compensating action (refund the charge, release the reservation) that is itself a new business transaction, may fail, may run out of order relative to concurrent readers, and must be safe to retry. That forces idempotency keys per step and per compensation, and it forces a decision about who holds the state machine: an orchestrator that calls services and records its own position, or choreography where each service reacts to an event and nobody knows the whole plan. Intermediate states are visible to everyone, so isolation must be recovered by semantic locks or commutative operations. Languages diverge because the undo stack is a scope-lifetime problem: some have a native LIFO unwind primitive (defer, AsyncExitStack, drop guards), some have structured cancellation that fights compensation, and some push crash-durable resumption entirely into a framework.

Saga Pattern in C#: what you actually reach for

The BCL pieces are Stack<Func<CancellationToken, Task>> for the undo stack, CancellationTokenSource and CreateLinkedTokenSource for bounding the forward path, AggregateException to carry the original plus compensation failures, and IAsyncDisposable with await using for scope-bound cleanup. System.Transactions.TransactionScope is the trap rather than the tool: distributed promotion throws PlatformNotSupportedException on .NET Core through .NET 6 and was reintroduced only on Windows in .NET 7. Durable orchestration comes from MassTransit saga state machines, NServiceBus sagas, or Dapr Workflow and Azure Durable Functions.

C# implementation

Push a compensation delegate immediately after each awaited call, take a CancellationToken on every public async method, and use ConfigureAwait(false) in library code. Reviewers reject async void anywhere except an event handler, reject .Result and .Wait() on a saga path, and reject nullable reference annotations being treated as a runtime guarantee. They expect records for the immutable step results and a dedicated exception carrying the compensation outcomes.
csharp
public async Task<string> PlaceOrderAsync(string orderId, long cents, CancellationToken ct)
{
    var undo = new Stack<Func<CancellationToken, Task>>();
    try
    {
        var charge = await _payments.ChargeAsync($"{orderId}:pay", cents, ct).ConfigureAwait(false);
        undo.Push(c => _payments.RefundAsync(charge.Id, $"{orderId}:refund", c));

        var hold = await _stock.ReserveAsync($"{orderId}:hold", ct).ConfigureAwait(false);
        undo.Push(c => _stock.ReleaseAsync(hold.Id, $"{orderId}:release", c));

        await _shipping.BookAsync($"{orderId}:ship", ct).ConfigureAwait(false); // pivot
        return charge.Id;
    }
    catch (Exception failure)
    {
        // never reuse ct: it is already cancelled and every compensation
        // would throw OperationCanceledException without calling anything
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
        var errors = new List<Exception> { failure };
        while (undo.Count > 0)
        {
            // await every compensation: an unawaited Task here would be an
            // unobserved exception, and an async void handler would crash out
            try { await undo.Pop()(cts.Token).ConfigureAwait(false); }
            catch (Exception ce) { errors.Add(ce); }
        }
        throw new AggregateException($"saga {orderId} compensation", errors);
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The C#-specific trap

The C#-only trap is async void: a compensation handler declared void cannot be awaited, so the unwind moves on immediately and its exception is rethrown on the captured SynchronizationContext or the thread pool rather than at your catch, taking the process down. The quieter sibling is calling a Task-returning compensation without await: it becomes an unobserved task whose exception surfaces only through TaskScheduler.UnobservedTaskException at finalization and faults nothing by default, so a refund that never ran looks like a clean unwind. Third, await rethrows only the first inner exception of a faulted task, so a caller writing catch (AggregateException) around this method never matches and sees one compensation error instead of the set. Nullable reference annotations warn about none of it: they are compiler metadata, not a runtime check.

Performance in C#, beyond the O(n)

Each await that actually suspends boxes the async state machine on the heap, so a twelve-step saga costs about a dozen small gen0 allocations plus one closure object per captured compensation; static lambdas taking state as a parameter remove the capture allocation entirely. ValueTask helps only for paths that usually complete synchronously, which a saga never does. Persisting the record with System.Text.Json source generation avoids the reflection warm-up and the intermediate string. Span<T> is irrelevant here because the cost is sockets, not buffers. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Saga Pattern between languages.

Real-World Applications

Saga Pattern is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Saga Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Saga Pattern appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Saga Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Saga Pattern to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

Frequently Asked Questions

Which C# type or library should I use for Saga Pattern?

The BCL pieces are Stack<Func<CancellationToken, Task>> for the undo stack, CancellationTokenSource and CreateLinkedTokenSource for bounding the forward path, AggregateException to carry the original plus compensation failures, and IAsyncDisposable with await using for scope-bound cleanup. System.Transactions.TransactionScope is the trap rather than the tool: distributed promotion throws PlatformNotSupportedException on .NET Core through .NET 6 and was reintroduced only on Windows in .NET 7. Durable orchestration comes from MassTransit saga state machines, NServiceBus sagas, or Dapr Workflow and Azure Durable Functions.

What is the most common C# mistake when implementing Saga Pattern?

The C#-only trap is async void: a compensation handler declared void cannot be awaited, so the unwind moves on immediately and its exception is rethrown on the captured SynchronizationContext or the thread pool rather than at your catch, taking the process down. The quieter sibling is calling a Task-returning compensation without await: it becomes an unobserved task whose exception surfaces only through TaskScheduler.UnobservedTaskException at finalization and faults nothing by default, so a refund that never ran looks like a clean unwind. Third, await rethrows only the first inner exception of a faulted task, so a caller writing catch (AggregateException) around this method never matches and sees one compensation error instead of the set. Nullable reference annotations warn about none of it: they are compiler metadata, not a runtime check.

How does Saga Pattern actually perform in C#?

Each await that actually suspends boxes the async state machine on the heap, so a twelve-step saga costs about a dozen small gen0 allocations plus one closure object per captured compensation; static lambdas taking state as a parameter remove the capture allocation entirely. ValueTask helps only for paths that usually complete synchronously, which a saga never does. Persisting the record with System.Text.Json source generation avoids the reflection warm-up and the intermediate string. Span<T> is irrelevant here because the cost is sockets, not buffers. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.