Introduction
Distributed applications often perform business operations across multiple services. An order-processing system, for example, may communicate with inventory, payment, shipping, and notification services. Each service manages its own data and performs its own operations. The application coordinates these services to complete a larger business process.
The challenge begins when one operation succeeds but a later operation fails.
Consider a customer placing an order for a laptop. The application needs to perform several operations:
Reserve the laptop in the inventory system.
Process the customer's payment.
Create a shipment.
Confirm the order.
Notify the customer.
Suppose inventory reservation succeeds and payment is completed, but the Shipping Service cannot create the shipment because the delivery address is invalid.
The order cannot proceed normally. However, simply marking the order as failed does not solve the problem. The inventory is still reserved, and the customer has already been charged.
The application needs to take additional actions to correct the situation. It may need to refund the payment and release the inventory reservation.
These corrective operations are called compensation actions.
The Saga pattern provides a way to coordinate these actions across multiple services. Instead of relying on a single database transaction that spans every service, a saga manages a sequence of independent operations. When a later operation fails, the saga executes appropriate compensation actions for the operations that have already completed.
MassTransit provides saga state machines that allow developers to define these workflows using states, events, and transitions.
In this article, we will implement a compensation workflow using MassTransit and ASP.NET Core. We will create an order saga that reserves inventory, processes payment, and creates a shipment. If shipment creation fails, the saga will request a payment refund and release the inventory reservation.
We will also examine compensation failures, duplicate messages, partial completion, operation ordering, and production considerations.
Understanding Compensation Actions in a Saga
A compensation action is a business operation that attempts to correct or counteract the effect of an earlier successful operation.
For example, when an application reserves inventory, the corresponding compensation action is to release that reservation.
When an application captures a payment, the compensation action may be to refund the payment.
When an application creates a shipment, the compensation action may be to cancel the shipment, provided the shipment has not already been handed to the carrier.
The compensation action depends on the business operation. It does not necessarily restore the system to exactly the same technical state it had before the operation.
Consider these examples:
Original operation | Possible compensation |
|---|---|
Reserve inventory | Release inventory reservation |
Capture payment | Refund payment |
Create shipment | Cancel shipment |
Book hotel room | Cancel booking |
Create subscription | Cancel subscription |
Allocate account credit | Reverse the credit allocation |
A compensation action is not the same as a database rollback.
A database rollback can undo changes within a transaction before they are committed. Compensation is a separate business operation that runs after an earlier operation has already been committed.
For example, once a payment provider has successfully charged a customer, the order application cannot simply roll back that transaction in its own database. It must send a refund request to the payment provider.
The refund is a new operation with its own processing time, result, and possible failure.
This distinction is important because compensation can also fail. A payment refund request may be rejected, a shipping cancellation may arrive too late, or an inventory service may be temporarily unavailable.
A reliable saga must therefore track compensation progress just as carefully as it tracks the original business operations.
Understanding the Order Workflow
We will build a simplified order-processing application with four participating services:
Order Service: Starts the order workflow and coordinates the process.
Inventory Service: Reserves and releases product inventory.
Payment Service: Processes payments and refunds.
Shipping Service: Creates shipments and reports shipment failures.
The Order Service contains the saga state machine. It does not directly modify the databases owned by the other services. Instead, it sends commands and receives events.
The normal workflow is:
Submit Order
|
v
Reserve Inventory
|
v
Inventory Reserved
|
v
Process Payment
|
v
Payment Completed
|
v
Create Shipment
|
v
Shipment Created
|
v
Order CompletedNow consider what happens if shipment creation fails.
Shipment Creation Failed
|
v
Refund Payment
|
v
Payment Refunded
|
v
Release Inventory
|
v
Inventory Released
|
v
Order CancelledThis is a compensation workflow.
The saga remembers which operations succeeded and sends the corresponding compensation commands in the required order.
For this example, we will refund the payment before releasing inventory. The order is not marked as fully cancelled until both compensation operations have completed.
This order is a business decision rather than a universal rule. Another application may release inventory first or perform both compensations independently. The important requirement is that the workflow explicitly defines what happens if each compensation succeeds or fails.
Creating the ASP.NET Core Project
Create a new Web API project:
dotnet new webapi -n OrderCompensationApi
cd OrderCompensationApiInstall MassTransit with RabbitMQ support:
dotnet add package MassTransit.RabbitMQFor this example, RabbitMQ will transport commands and events between services.
You can run the services as separate ASP.NET Core applications or as separate worker services. The saga itself belongs to the Order Service, while inventory, payment, and shipping operations should be handled by their respective service boundaries.
For a local demonstration, these components can run on the same machine. They should still communicate through messages so that the example follows the same architecture used in a distributed deployment.
Defining the Message Contracts
Create a folder named Contracts.
The message contracts describe the commands and events exchanged between the services.
Order Messages
Create OrderMessages.cs:
public record SubmitOrder(
Guid OrderId,
Guid CustomerId,
decimal Amount,
string ProductCode,
int Quantity);
public record OrderCompleted(
Guid OrderId);
public record OrderCancelled(
Guid OrderId,
string Reason);
public record OrderCompensationFailed(
Guid OrderId,
string Operation,
string Reason);SubmitOrder starts the workflow. It contains the order identifier, customer identifier, amount, product code, and requested quantity.
OrderCompleted indicates that the complete order workflow succeeded.
OrderCancelled indicates that the workflow was cancelled after a failure and the required compensation actions were completed.
OrderCompensationFailed is an operational notification that indicates that the application could not complete one or more corrective operations. This message should not be treated as proof that the order has been safely restored.
Inventory Messages
Create InventoryMessages.cs:
public record ReserveInventory(
Guid OrderId,
string ProductCode,
int Quantity);
public record InventoryReserved(
Guid OrderId,
Guid ReservationId);
public record InventoryReservationFailed(
Guid OrderId,
string Reason);
public record ReleaseInventory(
Guid OrderId,
Guid ReservationId);
public record InventoryReleased(
Guid OrderId,
Guid ReservationId);
public record InventoryReleaseFailed(
Guid OrderId,
Guid ReservationId,
string Reason);ReserveInventory asks the Inventory Service to reserve the requested quantity.
If the reservation succeeds, the service publishes InventoryReserved with a ReservationId.
The ReservationId is important because inventory systems may support several reservations for the same order or product. Compensation should target the exact reservation created by the original operation.
ReleaseInventory requests the release of that reservation.
The Inventory Service should make the release operation idempotent. If the same ReleaseInventory command is delivered more than once, it should not release additional inventory or produce an inconsistent result.
Payment Messages
Create PaymentMessages.cs:
public record ProcessPayment(
Guid OrderId,
Guid CustomerId,
decimal Amount,
Guid PaymentOperationId);
public record PaymentCompleted(
Guid OrderId,
Guid PaymentOperationId,
string TransactionId);
public record PaymentFailed(
Guid OrderId,
Guid PaymentOperationId,
string Reason);
public record RefundPayment(
Guid OrderId,
Guid PaymentOperationId,
string TransactionId);
public record PaymentRefunded(
Guid OrderId,
Guid PaymentOperationId,
string RefundTransactionId);
public record PaymentRefundFailed(
Guid OrderId,
Guid PaymentOperationId,
string Reason);PaymentOperationId identifies the original payment operation. It should remain unchanged when the payment is refunded.
TransactionId identifies the payment transaction that was completed successfully.
RefundPayment uses both identifiers so that the Payment Service can locate and refund the correct transaction.
PaymentRefunded confirms that the refund was completed. PaymentRefundFailed indicates that the refund could not be completed.
The saga must wait for the actual refund result. Sending a refund command does not mean that the money has already been returned to the customer.
Shipping Messages
Create ShippingMessages.cs:
public record CreateShipment(
Guid OrderId,
string ProductCode,
int Quantity);
public record ShipmentCreated(
Guid OrderId,
Guid ShipmentId);
public record ShipmentCreationFailed(
Guid OrderId,
string Reason);
public record CancelShipment(
Guid OrderId,
Guid ShipmentId);
public record ShipmentCancelled(
Guid OrderId,
Guid ShipmentId);CreateShipment asks the Shipping Service to create a shipment.
If the operation succeeds, ShipmentCreated contains the ShipmentId.
ShipmentCreationFailed indicates that the shipment could not be created.
The example focuses on shipment creation failure. In a more complete workflow, a shipment may already have been created and later need cancellation. The Shipping Service would then need to support CancelShipment and report whether cancellation was successful.
Creating the Saga Instance
Create a folder named Sagas and add OrderState.cs:
using MassTransit;
public class OrderState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; } = string.Empty;
public Guid OrderId { get; set; }
public Guid CustomerId { get; set; }
public decimal Amount { get; set; }
public string ProductCode { get; set; } = string.Empty;
public int Quantity { get; set; }
public Guid? ReservationId { get; set; }
public Guid PaymentOperationId { get; set; }
public string? PaymentTransactionId { get; set; }
public Guid? ShipmentId { get; set; }
public string? FailureReason { get; set; }
public string? CompensationFailureReason { get; set; }
public bool InventoryReleased { get; set; }
public bool PaymentRefunded { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public byte[] RowVersion { get; set; } = [];
}The saga instance stores the information needed to continue the order workflow and perform compensation actions.
CorrelationId identifies the saga instance. We will use OrderId as the correlation identifier so that messages for the same order reach the same saga.
ReservationId identifies the inventory reservation that must be released if the workflow is cancelled.
PaymentOperationId identifies the payment operation. PaymentTransactionId stores the transaction identifier required to request a refund.
ShipmentId stores the shipment identifier if shipment creation succeeds.
FailureReason records why the original workflow failed. CompensationFailureReason stores information about a failed corrective operation.
InventoryReleased and PaymentRefunded indicate whether the corresponding compensation action has completed.
These properties allow the saga to retain its progress even when several messages arrive over time.
In production, the saga instance should be stored in a durable repository. The application must not depend on in-memory state because a restart could otherwise remove the information needed to complete compensation.
Implementing the Order Saga State Machine
Create OrderStateMachine.cs.
The state machine will use the following states:
State | Purpose |
|---|---|
WaitingForInventory | Waiting for the inventory reservation result |
WaitingForPayment | Waiting for the payment result |
WaitingForShipment | Waiting for the shipment result |
RefundingPayment | Waiting for payment compensation |
ReleasingInventory | Waiting for inventory compensation |
CompensationFailed | One or more compensation actions could not be completed |
Completed | The order workflow succeeded |
Cancelled | The order was cancelled and required compensation completed |
The state machine also needs events for every command result.
The following implementation demonstrates the main successful and compensation paths:
using MassTransit;
public class OrderStateMachine :
MassTransitStateMachine<OrderState>
{
public State WaitingForInventory { get; private set; } = null!;
public State WaitingForPayment { get; private set; } = null!;
public State WaitingForShipment { get; private set; } = null!;
public State RefundingPayment { get; private set; } = null!;
public State ReleasingInventory { get; private set; } = null!;
public State CompensationFailed { get; private set; } = null!;
public State Completed { get; private set; } = null!;
public State Cancelled { get; private set; } = null!;
public Event<SubmitOrder> SubmitOrder { get; private set; } = null!;
public Event<InventoryReserved> InventoryReserved { get; private set; } = null!;
public Event<InventoryReservationFailed> InventoryReservationFailed
{ get; private set; } = null!;
public Event<PaymentCompleted> PaymentCompleted { get; private set; } = null!;
public Event<PaymentFailed> PaymentFailed { get; private set; } = null!;
public Event<ShipmentCreated> ShipmentCreated { get; private set; } = null!;
public Event<ShipmentCreationFailed> ShipmentCreationFailed
{ get; private set; } = null!;
public Event<PaymentRefunded> PaymentRefunded { get; private set; } = null!;
public Event<PaymentRefundFailed> PaymentRefundFailed
{ get; private set; } = null!;
public Event<InventoryReleased> InventoryReleased { get; private set; } = null!;
public Event<InventoryReleaseFailed> InventoryReleaseFailed
{ get; private set; } = null!;
public OrderStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => SubmitOrder,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => InventoryReserved,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => InventoryReservationFailed,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentCompleted,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentFailed,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => ShipmentCreated,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => ShipmentCreationFailed,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentRefunded,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => PaymentRefundFailed,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => InventoryReleased,
x => x.CorrelateById(
context => context.Message.OrderId));
Event(() => InventoryReleaseFailed,
x => x.CorrelateById(
context => context.Message.OrderId));
ConfigureOrderSubmission();
ConfigureInventoryBehavior();
ConfigurePaymentBehavior();
ConfigureShippingBehavior();
ConfigurePaymentCompensation();
ConfigureInventoryCompensation();
ConfigureFinalStates();
SetCompletedWhenFinalized();
}
private void ConfigureOrderSubmission()
{
Initially(
When(SubmitOrder)
.Then(context =>
{
context.Saga.OrderId =
context.Message.OrderId;
context.Saga.CustomerId =
context.Message.CustomerId;
context.Saga.Amount =
context.Message.Amount;
context.Saga.ProductCode =
context.Message.ProductCode;
context.Saga.Quantity =
context.Message.Quantity;
context.Saga.PaymentOperationId =
Guid.NewGuid();
context.Saga.CreatedAt =
DateTime.UtcNow;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Send(
context => new Uri(
"queue:inventory-service"),
context => new ReserveInventory(
context.Saga.OrderId,
context.Saga.ProductCode,
context.Saga.Quantity))
.TransitionTo(WaitingForInventory));
}
private void ConfigureInventoryBehavior()
{
During(
WaitingForInventory,
When(InventoryReserved)
.Then(context =>
{
context.Saga.ReservationId =
context.Message.ReservationId;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Send(
context => new Uri(
"queue:payment-service"),
context => new ProcessPayment(
context.Saga.OrderId,
context.Saga.CustomerId,
context.Saga.Amount,
context.Saga.PaymentOperationId))
.TransitionTo(WaitingForPayment),
When(InventoryReservationFailed)
.Then(context =>
{
context.Saga.FailureReason =
context.Message.Reason;
})
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason = context.Message.Reason
}))
.TransitionTo(Cancelled));
}
private void ConfigurePaymentBehavior()
{
During(
WaitingForPayment,
When(PaymentCompleted)
.Then(context =>
{
context.Saga.PaymentTransactionId =
context.Message.TransactionId;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Send(
context => new Uri(
"queue:shipping-service"),
context => new CreateShipment(
context.Saga.OrderId,
context.Saga.ProductCode,
context.Saga.Quantity))
.TransitionTo(WaitingForShipment),
When(PaymentFailed)
.Then(context =>
{
context.Saga.FailureReason =
context.Message.Reason;
})
.Send(
context => new Uri(
"queue:inventory-service"),
context => new ReleaseInventory(
context.Saga.OrderId,
context.Saga.ReservationId!.Value))
.TransitionTo(ReleasingInventory));
}
private void ConfigureShippingBehavior()
{
During(
WaitingForShipment,
When(ShipmentCreated)
.Then(context =>
{
context.Saga.ShipmentId =
context.Message.ShipmentId;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Publish(context =>
context.Init<OrderCompleted>(
new
{
context.Saga.OrderId
}))
.TransitionTo(Completed),
When(ShipmentCreationFailed)
.Then(context =>
{
context.Saga.FailureReason =
context.Message.Reason;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Send(
context => new Uri(
"queue:payment-service"),
context => new RefundPayment(
context.Saga.OrderId,
context.Saga.PaymentOperationId,
context.Saga.PaymentTransactionId!))
.TransitionTo(RefundingPayment));
}
private void ConfigurePaymentCompensation()
{
During(
RefundingPayment,
When(PaymentRefunded)
.Then(context =>
{
context.Saga.PaymentRefunded = true;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Send(
context => new Uri(
"queue:inventory-service"),
context => new ReleaseInventory(
context.Saga.OrderId,
context.Saga.ReservationId!.Value))
.TransitionTo(ReleasingInventory),
When(PaymentRefundFailed)
.Then(context =>
{
context.Saga.CompensationFailureReason =
context.Message.Reason;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Publish(context =>
context.Init<OrderCompensationFailed>(
new
{
context.Saga.OrderId,
Operation = "Payment refund",
Reason = context.Message.Reason
}))
.TransitionTo(CompensationFailed));
}
private void ConfigureInventoryCompensation()
{
During(
ReleasingInventory,
When(InventoryReleased)
.Then(context =>
{
context.Saga.InventoryReleased = true;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Publish(context =>
context.Init<OrderCancelled>(
new
{
context.Saga.OrderId,
Reason =
context.Saga.FailureReason
?? "Order processing failed."
}))
.TransitionTo(Cancelled),
When(InventoryReleaseFailed)
.Then(context =>
{
context.Saga.CompensationFailureReason =
context.Message.Reason;
context.Saga.UpdatedAt =
DateTime.UtcNow;
})
.Publish(context =>
context.Init<OrderCompensationFailed>(
new
{
context.Saga.OrderId,
Operation = "Inventory release",
Reason = context.Message.Reason
}))
.TransitionTo(CompensationFailed));
}
private void ConfigureFinalStates()
{
During(
Completed,
Ignore(PaymentCompleted),
Ignore(ShipmentCreated));
During(
Cancelled,
Ignore(PaymentRefunded),
Ignore(InventoryReleased));
}
}
Join the conversation! Your thoughts help the community grow.