Round #267
07 May 2026, 21:16· csharp· meta/llama-3.3-70b-instruct· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 5 / 0 / 2
- Journey weight
- 507
- Lightshift ΔL
- —
Prompt
Write a distributed transaction coordinator using the Saga pattern
Zero-point index (what the engine surfaced)
ZPI-ZPI-0025 | 2026-05-07T21:16:08Z
Write a distributed transaction coordinator using the Saga pattern
ZERO POINT — 5 entries (structural invariants)
● hsl(27.69, 100%, 50%) async [feature]
● hsl(145.64, 100%, 16%) Task of T [feature]
● hsl(7.18, 100%, 18%) class [feature]
● hsl(0.00, 100%, 18%) public [feature]
● hsl(84.10, 100%, 18%) namespace [feature]
UNOBSERVED — 0 entries (implied truths)
OBSERVED — 2 entries (explicit in request)
◉ hsl(85.13, 100%, 36%) using [feature]
◉ hsl(234.87, 100%, 36%) using [feature]
COMPLEXITY │ 7 entries │ spread: 150° │ band: LOW
Baseline response (no ZPI)
**Distributed Transaction Coordinator using the Saga Pattern**
===========================================================
The Saga pattern is a design pattern that helps to manage distributed transactions in a microservices architecture. It provides a way to handle failures and ensure data consistency across multiple services.
**Overview**
------------
In this example, we will create a distributed transaction coordinator using the Saga pattern in C#. The coordinator will manage a transaction that involves multiple services: `OrderService`, `InventoryService`, and `PaymentService`.
**Saga Pattern Components**
---------------------------
* **Saga**: The Saga is the central component that manages the distributed transaction. It defines the steps involved in the transaction and handles failures.
* **Steps**: Each step in the Saga represents a service call. In this example, we have three steps: `CreateOrder`, `ReserveInventory`, and `ProcessPayment`.
* **Compensating Actions**: Compensating actions are used to undo the effects of a failed step. For example, if the payment fails, we need to cancel the order and release the reserved inventory.
**Implementation**
-----------------
### Saga Coordinator
```csharp
using System;
using System.Threading.Tasks;
public class SagaCoordinator
{
private readonly IOrderService _orderService;
private readonly IInventoryService _inventoryService;
private readonly IPaymentService _paymentService;
public SagaCoordinator(IOrderService orderService, IInventoryService inventoryService, IPaymentService paymentService)
{
_orderService = orderService;
_inventoryService = inventoryService;
_paymentService = paymentService;
}
public async Task ProcessTransaction(Order order)
{
var saga = new Saga();
// Step 1: Create Order
var createOrderStep = new CreateOrderStep(_orderService);
saga.AddStep(createOrderStep);
// Step 2: Reserve Inventory
var reserveInventoryStep = new ReserveInventoryStep(_inventoryService);
saga.AddStep(reserveInventoryStep);
// Step 3: Process Payment
var processPaymentStep = new ProcessPaymentStep(_paymentService);
saga.AddStep(processPaymentStep);
try
{
await saga.Execute(order);
}
catch (Exception ex)
{
await saga.Compensate(order, ex);
}
}
}
```
### Saga Class
```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Saga
{
private readonly List<Step> _steps = new List<Step>();
public void AddStep(Step step)
{
_steps.Add(step);
}
public async Task Execute(object data)
{
foreach (var step in _steps)
{
await step.Execute(data);
}
}
public async Task Compensate(object data, Exception exception)
{
for (int i = _steps.Count - 1; i >= 0; i--)
{
var step = _steps[i];
await step.Compensate(data, exception);
}
}
}
```
### Step Interface
```csharp
using System;
using System.Threading.Tasks;
public interface Step
{
Task Execute(object data);
Task Compensate(object data, Exception exception);
}
```
### Create Order Step
```csharp
using System;
using System.Threading.Tasks;
public class CreateOrderStep : Step
{
private readonly IOrderService _orderService;
public CreateOrderStep(IOrderService orderService)
{
_orderService = orderService;
}
public async Task Execute(object data)
{
var order = (Order)data;
await _orderService.CreateOrder(order);
}
public async Task Compensate(object data, Exception exception)
{
var order = (Order)data;
await _orderService.CancelOrder(order);
}
}
```
### Reserve Inventory Step
```csharp
using System;
using System.Threading.Tasks;
public class ReserveInventoryStep : Step
{
private readonly IInventoryService _inventoryService;
public ReserveInventoryStep(IInventoryService inventoryService)
{
_inventoryService = inventoryService;
}
public async Task Execute(object data)
{
var order = (Order)data;
await _inventoryService.ReserveInventory(order);
}
public async Task Compensate(object data, Exception exception)
{
var order = (Order)data;
await _inventoryService.ReleaseInventory(order);
}
}
```
### Process Payment Step
```csharp
using System;
using System.Threading.Tasks;
public class ProcessPaymentStep : Step
{
private readonly IPaymentService _paymentService;
public ProcessPaymentStep(IPaymentService paymentService)
{
_paymentService = paymentService;
}
public async Task Execute(object data)
{
var order = (Order)data;
await _paymentService.ProcessPayment(order);
}
public async Task Compensate(object data, Exception exception)
{
var order = (Order)data;
Enhanced response (with ZPI)
**Distributed Transaction Coordinator using Saga Pattern**
The Saga pattern is a design pattern that helps to manage distributed transactions by breaking down a long-running business process into a series of local transactions. Each local transaction is responsible for a specific step in the process, and if any step fails, the entire process is rolled back.
Below is an example implementation of a distributed transaction coordinator using the Saga pattern in C#:
```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
// Define the Saga interface
public interface ISaga
{
string Id { get; }
string Name { get; }
Task Start();
Task Compensate();
}
// Define the Saga coordinator interface
public interface ISagaCoordinator
{
Task StartSaga(ISaga saga);
Task CompensateSaga(ISaga saga);
}
// Implement the Saga coordinator
public class SagaCoordinator : ISagaCoordinator
{
private readonly ILogger<SagaCoordinator> _logger;
private readonly Dictionary<string, ISaga> _sagas;
public SagaCoordinator(ILogger<SagaCoordinator> logger)
{
_logger = logger;
_sagas = new Dictionary<string, ISaga>();
}
public async Task StartSaga(ISaga saga)
{
try
{
// Start the saga
await saga.Start();
// Add the saga to the dictionary
_sagas[saga.Id] = saga;
_logger.LogInformation($"Saga {saga.Name} started successfully");
}
catch (Exception ex)
{
// Log the exception and compensate the saga
_logger.LogError(ex, $"Error starting saga {saga.Name}");
await CompensateSaga(saga);
}
}
public async Task CompensateSaga(ISaga saga)
{
try
{
// Compensate the saga
await saga.Compensate();
// Remove the saga from the dictionary
_sagas.Remove(saga.Id);
_logger.LogInformation($"Saga {saga.Name} compensated successfully");
}
catch (Exception ex)
{
// Log the exception
_logger.LogError(ex, $"Error compensating saga {saga.Name}");
}
}
}
// Define a sample saga
public class OrderSaga : ISaga
{
private readonly ILogger<OrderSaga> _logger;
private readonly IOrderService _orderService;
private readonly IPaymentService _paymentService;
public string Id { get; } = Guid.NewGuid().ToString();
public string Name { get; } = "OrderSaga";
public OrderSaga(ILogger<OrderSaga> logger, IOrderService orderService, IPaymentService paymentService)
{
_logger = logger;
_orderService = orderService;
_paymentService = paymentService;
}
public async Task Start()
{
try
{
// Create a new order
await _orderService.CreateOrder();
// Process the payment
await _paymentService.ProcessPayment();
_logger.LogInformation("Order saga completed successfully");
}
catch (Exception ex)
{
// Log the exception and throw
_logger.LogError(ex, "Error processing order saga");
throw;
}
}
public async Task Compensate()
{
try
{
// Cancel the order
await _orderService.CancelOrder();
// Refund the payment
await _paymentService.RefundPayment();
_logger.LogInformation("Order saga compensated successfully");
}
catch (Exception ex)
{
// Log the exception
_logger.LogError(ex, "Error compensating order saga");
}
}
}
// Define the order service interface
public interface IOrderService
{
Task CreateOrder();
Task CancelOrder();
}
// Implement the order service
public class OrderService : IOrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}
public async Task CreateOrder()
{
try
{
// Create a new order
_logger.LogInformation("Creating a new order");
// Simulate a delay
await Task.Delay(1000);
_logger.LogInformation("Order created successfully");
}
catch (Exception ex)
{
// Log the exception and throw
_logger.LogError(ex, "Error creating order");
throw;
}
}
public async Task CancelOrder()
{
try
{
// Cancel the order
_logger.LogInformation("Cancelling the order");
// Simulate a delay
await Task.Delay(1000);
_logger.LogInformation("Order cancelled successfully");
}
catch (Exception ex)
{
// Log the exception
_logger.LogError(ex, "Error cancelling order");
}
}
}
// Define the payment service interface
public interface IPaymentService
{
Grader chain
Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.
V1claude-haiku-4-5-20251001
WorseV4qwen2.5-coder-7b-instruct
BetterComments
Our grader said what it said. What do you say? Comment as a guest below.
No comments yet. Be the first to say what you make of this round.