What is the SAGA Pattern?
The SAGA pattern is a design pattern used in microservices architecture to handle long-running transactions and ensure data consistency across multiple services. It is commonly used when distributed transactions with two-phase commits (2PC) are not feasible due to their blocking nature.
A SAGA is a sequence of local transactions, where each step updates the database and triggers the next step. If a failure occurs, compensating transactions are executed to undo previous operations.
Types of SAGA Patterns
There are two primary ways to implement a SAGA pattern:
-
Choreography (Event-driven)
- Each service listens to events and reacts accordingly.
- No centralized controller; services coordinate via events.
- Best for simple workflows with fewer services.
-
Orchestration (Command-driven)
- A central orchestrator service manages the transaction flow.
- The orchestrator calls each service and waits for responses.
- Suitable for complex workflows with multiple services.
Implementing SAGA in .NET
Below is a step-by-step guide to implementing both Choreography and Orchestration using .NET.
1. Choreography-based SAGA (Event-driven)
In this approach, each service listens for events and reacts accordingly.
Technologies Used
- ASP.NET Core Web API
- MassTransit with RabbitMQ (for event-driven communication)
- Entity Framework Core (for persistence)
Example: Order Processing System
- Order Service → Places an order and publishes an
OrderCreated
event. - Payment Service → Listens to
OrderCreated
and processes payment, then publishesPaymentProcessed
. - Inventory Service → Listens to
PaymentProcessed
and updates stock.
Step 1: Create a Shared Event Model
public class OrderCreatedEvent
{
public Guid OrderId { get; set; }
public decimal Amount { get; set; }
}
public class PaymentProcessedEvent
{
public Guid OrderId { get; set; }
}
Step 2: Publish Events in Order Service
public class OrderService
{
private readonly IBus _bus;
public OrderService(IBus bus)
{
_bus = bus;
}
public async Task CreateOrder(Guid orderId, decimal amount)
{
// Save order to database (skipped for brevity)
await _bus.Publish(new OrderCreatedEvent { OrderId = orderId, Amount = amount });
}
}
Step 3: Handle Events in Payment Service
public class OrderCreatedConsumer : IConsumer<OrderCreatedEvent>
{
private readonly IBus _bus;
public OrderCreatedConsumer(IBus bus)
{
_bus = bus;
}
public async Task Consume(ConsumeContext<OrderCreatedEvent> context)
{
var orderId = context.Message.OrderId;
// Process payment logic here (skipped for brevity)
await _bus.Publish(new PaymentProcessedEvent { OrderId = orderId });
}
}
Step 4: Handle Events in Inventory Service
public class PaymentProcessedConsumer : IConsumer<PaymentProcessedEvent>
{
public async Task Consume(ConsumeContext<PaymentProcessedEvent> context)
{
var orderId = context.Message.OrderId;
// Update inventory (skipped for brevity)
}
}
2. Orchestration-based SAGA (Command-driven)
In this approach, a central orchestrator manages the entire transaction.
Example: Order Processing Orchestrator
- Order Service → Calls the orchestrator.
- SAGA Orchestrator → Calls Payment and Inventory services.
- Compensation logic → If one step fails, previous steps are undone.
Step 1: Define the SAGA State
public class OrderSagaState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; }
public string CurrentState { get; set; }
}
Step 2: Create the SAGA State Machine
public class OrderStateMachine : MassTransitStateMachine<OrderSagaState>
{
public State AwaitingPayment { get; private set; }
public Event<OrderCreatedEvent> OrderCreated { get; private set; }
public Event<PaymentProcessedEvent> PaymentProcessed { get; private set; }
public OrderStateMachine()
{
InstanceState(x => x.CurrentState);
Event(() => OrderCreated, x => x.CorrelateById(context => context.Message.OrderId));
Event(() => PaymentProcessed, x => x.CorrelateById(context => context.Message.OrderId));
Initially(
When(OrderCreated)
.Then(context => Console.WriteLine("Processing payment..."))
.TransitionTo(AwaitingPayment)
.Publish(context => new PaymentProcessedEvent { OrderId = context.Data.OrderId })
);
During(AwaitingPayment,
When(PaymentProcessed)
.Then(context => Console.WriteLine("Updating inventory..."))
.Finalize()
);
}
}
Step 3: Register and Configure MassTransit in .NET
services.AddMassTransit(cfg =>
{
cfg.AddSagaStateMachine<OrderStateMachine, OrderSagaState>()
.InMemoryRepository();
cfg.UsingRabbitMq((context, cfg) =>
{
cfg.ConfigureEndpoints(context);
});
});
Compensation (Handling Failures)
If a failure occurs, we need to roll back the previous steps.
Example: Payment Fails, So Order is Cancelled
Modify the OrderStateMachine to handle failures:
public Event<PaymentFailedEvent> PaymentFailed { get; private set; }
During(AwaitingPayment,
When(PaymentFailed)
.Then(context => Console.WriteLine("Payment failed. Cancelling order..."))
.Publish(context => new OrderCancelledEvent { OrderId = context.Data.OrderId })
.Finalize()
);
When to Use Choreography vs. Orchestration?
Factor | Choreography | Orchestration |
---|---|---|
Complexity | Low (fewer services) | High (many services) |
Scalability | High (loosely coupled) | Moderate |
Observability | Harder (many events) | Easier (central control) |
Flexibility | High (autonomous services) | Moderate |
Conclusion
- Choreography is best when services are independent and event-driven.
- Orchestration is better for complex workflows requiring centralized control.
- Use MassTransit with RabbitMQ for implementing event-driven SAGA in .NET.
Use Azure Service Bus instead of RabbitMQ in your SAGA implementation with MassTransit in .NET.
Azure Service Bus is a fully managed messaging service that integrates well with MassTransit, making it a great choice for cloud-based applications.
How to Use Azure Service Bus with MassTransit in SAGA
We’ll update the previous SAGA implementation by replacing RabbitMQ with Azure Service Bus.
1. Install Dependencies
First, install the required NuGet packages:
dotnet add package MassTransit.AzureServiceBus
2. Configure MassTransit to Use Azure Service Bus
Modify the Program.cs
or Startup.cs
file in your .NET application.
using MassTransit;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMassTransit(cfg =>
{
cfg.AddSagaStateMachine<OrderStateMachine, OrderSagaState>()
.EntityFrameworkRepository(r =>
{
r.ExistingDbContext<OrderDbContext>(); // Use EF Core for saga persistence
});
cfg.UsingAzureServiceBus((context, config) =>
{
config.Host("your-azure-service-bus-connection-string");
config.ReceiveEndpoint("order-created-queue", e =>
{
e.ConfigureSaga<OrderSagaState>(context);
});
});
});
builder.Services.AddMassTransitHostedService();
var app = builder.Build();
app.Run();
🔹 Key Changes:
- Replaced
UsingRabbitMq
withUsingAzureServiceBus
- Set the Service Bus connection string from Azure
- Configured a queue for the Order SAGA state machine
3. Publish Events to Azure Service Bus
Instead of publishing to RabbitMQ, we now publish to Azure Service Bus.
Publishing an Event
public class OrderService
{
private readonly IPublishEndpoint _publishEndpoint;
public OrderService(IPublishEndpoint publishEndpoint)
{
_publishEndpoint = publishEndpoint;
}
public async Task CreateOrder(Guid orderId, decimal amount)
{
await _publishEndpoint.Publish(new OrderCreatedEvent
{
OrderId = orderId,
Amount = amount
});
}
}
Consuming an Event
public class OrderCreatedConsumer : IConsumer<OrderCreatedEvent>
{
public async Task Consume(ConsumeContext<OrderCreatedEvent> context)
{
var orderId = context.Message.OrderId;
// Process payment logic
await context.Publish(new PaymentProcessedEvent { OrderId = orderId });
}
}
4. Enable Compensation (Rollback) on Failure
If Payment Service fails, we trigger a compensating transaction.
Define a Compensation Event
public class PaymentFailedEvent
{
public Guid OrderId { get; set; }
}
Handle Failure in the SAGA Orchestrator
public Event<PaymentFailedEvent> PaymentFailed { get; private set; }
During(AwaitingPayment,
When(PaymentFailed)
.Then(context => Console.WriteLine("Payment failed! Cancelling order..."))
.Publish(context => new OrderCancelledEvent { OrderId = context.Data.OrderId })
.Finalize()
);
5. Configure Azure Service Bus in Azure Portal
- Go to Azure Portal → Service Bus
- Create a Namespace (if not already created)
- Create a Queue (e.g.,
order-created-queue
) - Copy Connection String and update the .NET configuration
Summary
✅ Replaced RabbitMQ with Azure Service Bus
✅ Configured MassTransit to use Azure Service Bus
✅ Published & consumed messages from Azure Service Bus
✅ Handled SAGA failures with compensating transactions
Azure Service Bus is a reliable, cloud-native alternative to RabbitMQ, making it ideal for enterprise-grade microservices.
Would you like a GitHub sample project for this? 🚀
Comments
Post a Comment