Saga Pattern Implementation in C#
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
Saga Pattern in C#: what you actually reach for
C# implementation
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 FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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 trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.