Round #249
07 May 2026, 20:58· csharp· meta/llama-3.3-70b-instruct· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 0 / 0 / 0
- Journey weight
- 0
- Lightshift ΔL
- —
Prompt
Write a Saga orchestrator for a multi-step order fulfilment workflow
Zero-point index (what the engine surfaced)
ZPI-ZPI-0017 | 2026-05-07T20:58:35Z
Write a Saga orchestrator for a multi-step order fulfilment workflow
ZERO POINT — 0 entries (structural invariants)
UNOBSERVED — 0 entries (implied truths)
OBSERVED — 0 entries (explicit in request)
COMPLEXITY │ 0 entries │ spread: 0° │ band: LOW
Baseline response (no ZPI)
**Order Fulfillment Saga Orchestrator**
=====================================
This C# implementation demonstrates a Saga orchestrator for a multi-step order fulfillment workflow. The Saga pattern is used to manage long-running business processes that involve multiple steps, allowing for compensation actions in case of failures.
**Order Fulfillment Workflow Steps**
---------------------------------
1. **Create Order**: Create a new order with customer details and order items.
2. **Verify Inventory**: Verify the availability of ordered items in the inventory.
3. **Reserve Inventory**: Reserve the ordered items in the inventory.
4. **Process Payment**: Process the payment for the order.
5. **Ship Order**: Ship the order to the customer.
**Saga Orchestrator Implementation**
----------------------------------
```csharp
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class OrderFulfillmentSaga
{
private readonly ILogger<OrderFulfillmentSaga> _logger;
private readonly IOrderRepository _orderRepository;
private readonly IInventoryService _inventoryService;
private readonly IPaymentGateway _paymentGateway;
private readonly IShippingService _shippingService;
public OrderFulfillmentSaga(
ILogger<OrderFulfillmentSaga> logger,
IOrderRepository orderRepository,
IInventoryService inventoryService,
IPaymentGateway paymentGateway,
IShippingService shippingService)
{
_logger = logger;
_orderRepository = orderRepository;
_inventoryService = inventoryService;
_paymentGateway = paymentGateway;
_shippingService = shippingService;
}
public async Task StartSaga(Order order)
{
try
{
// Step 1: Create Order
await CreateOrder(order);
// Step 2: Verify Inventory
await VerifyInventory(order);
// Step 3: Reserve Inventory
await ReserveInventory(order);
// Step 4: Process Payment
await ProcessPayment(order);
// Step 5: Ship Order
await ShipOrder(order);
_logger.LogInformation("Order fulfillment saga completed successfully.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Order fulfillment saga failed.");
await Compensate(order);
}
}
private async Task CreateOrder(Order order)
{
await _orderRepository.CreateOrder(order);
_logger.LogInformation("Order created successfully.");
}
private async Task VerifyInventory(Order order)
{
var inventoryResult = await _inventoryService.VerifyInventory(order.Items);
if (!inventoryResult.IsSuccess)
{
throw new InvalidOperationException("Insufficient inventory.");
}
_logger.LogInformation("Inventory verified successfully.");
}
private async Task ReserveInventory(Order order)
{
await _inventoryService.ReserveInventory(order.Items);
_logger.LogInformation("Inventory reserved successfully.");
}
private async Task ProcessPayment(Order order)
{
var paymentResult = await _paymentGateway.ProcessPayment(order);
if (!paymentResult.IsSuccess)
{
throw new InvalidOperationException("Payment processing failed.");
}
_logger.LogInformation("Payment processed successfully.");
}
private async Task ShipOrder(Order order)
{
await _shippingService.ShipOrder(order);
_logger.LogInformation("Order shipped successfully.");
}
private async Task Compensate(Order order)
{
try
{
// Compensate actions in reverse order
await _shippingService.CancelShipment(order);
await _paymentGateway.RefundPayment(order);
await _inventoryService.ReleaseInventory(order.Items);
await _orderRepository.CancelOrder(order);
_logger.LogInformation("Order fulfillment saga compensated successfully.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Compensation failed.");
}
}
}
```
**Example Usage**
-----------------
```csharp
var order = new Order
{
CustomerName = "John Doe",
Items = new[] { new OrderItem { ProductId = 1, Quantity = 2 } }
};
var saga = new OrderFulfillmentSaga(
logger: new LoggerFactory().CreateLogger<OrderFulfillmentSaga>(),
orderRepository: new OrderRepository(),
inventoryService: new InventoryService(),
paymentGateway: new PaymentGateway(),
shippingService: new ShippingService());
await saga.StartSaga(order);
```
This implementation demonstrates a basic Saga orchestrator for a multi-step order fulfillment workflow. You can extend and modify it to fit your specific requirements and handle more complex scenarios.
Enhanced response (with ZPI)
```csharp
using MassTransit;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
// Define the order state
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string OrderId { get; set; }
public string CustomerId { get; set; }
public string OrderStatus { get; set; }
}
// Define the order state machine
public class OrderStateMachine : MassTransitStateMachine<OrderState>
{
public OrderStateMachine(ILogger<OrderStateMachine> logger)
{
InstanceState(x => x.CurrentState);
Event(() => OrderPlaced, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => OrderVerified, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => OrderShipped, x => x.CorrelateById(m => m.Message.OrderId));
Event(() => OrderDelivered, x => x.CorrelateById(m => m.Message.OrderId));
Initially(
When(OrderPlaced)
.Then(context => context.Saga.OrderStatus = "Placed")
.TransitionTo(Placed));
During(Placed,
When(OrderVerified)
.Then(context => context.Saga.OrderStatus = "Verified")
.TransitionTo(Verified));
During(Verified,
When(OrderShipped)
.Then(context => context.Saga.OrderStatus = "Shipped")
.TransitionTo(Shipped));
During(Shipped,
When(OrderDelivered)
.Then(context => context.Saga.OrderStatus = "Delivered")
.TransitionTo(Delivered));
SetCompletedWhenFinalized();
}
public State Placed { get; private set; }
public State Verified { get; private set; }
public State Shipped { get; private set; }
public State Delivered { get; private set; }
public Event<OrderPlaced> OrderPlaced { get; private set; }
public Event<OrderVerified> OrderVerified { get; private set; }
public Event<OrderShipped> OrderShipped { get; private set; }
public Event<OrderDelivered> OrderDelivered { get; private set; }
}
// Define the order placed event
public class OrderPlaced
{
public string OrderId { get; set; }
public string CustomerId { get; set; }
}
// Define the order verified event
public class OrderVerified
{
public string OrderId { get; set; }
}
// Define the order shipped event
public class OrderShipped
{
public string OrderId { get; set; }
}
// Define the order delivered event
public class OrderDelivered
{
public string OrderId { get; set; }
}
// Register the saga in the DI container
public class OrderFulfilmentWorkflowModule : IModule
{
public void Configure(IServiceCollection services)
{
services.AddMassTransit(x =>
{
x.AddSagaStateMachine<OrderStateMachine, OrderState>()
.InMemoryRepository();
x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
{
cfg.Host("localhost", "/", h =>
{
h.Username("guest");
h.Password("guest");
});
cfg.ReceiveEndpoint("order-fulfilment-workflow", e =>
{
e.StateMachineSaga<OrderStateMachine, OrderState>(provider);
});
}));
});
}
}
```
This code implements a saga orchestrator for a multi-step order fulfilment workflow using MassTransit, a popular .NET library for building distributed applications. The workflow consists of four steps: order placement, verification, shipping, and delivery.
Here's a step-by-step explanation of the code:
1. **Order State**: The `OrderState` class represents the state of an order, which includes the correlation ID, order ID, customer ID, and order status.
2. **Order State Machine**: The `OrderStateMachine` class defines the state machine for the order fulfilment workflow. It uses MassTransit's `SagaStateMachine` to manage the state transitions.
3. **Events**: The code defines four events: `OrderPlaced`, `OrderVerified`, `OrderShipped`, and `OrderDelivered`. These events trigger state transitions in the state machine.
4. **State Transitions**: The state machine defines the state transitions based on the events. For example, when an `OrderPlaced` event is received, the state machine transitions to the `Placed` state.
5. **DI Registration**: The `OrderFulfilmentWorkflowModule` class registers the saga in the DI container using MassTransit's `AddSagaStateMachine` method. It also configures the bus to use RabbitMQ as the message broker.
To use this code, you would need to create a .NET Core application, install the required NuGet packages (
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
BetterV4qwen2.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.