Skip to main content

What is the SAGA Pattern?

 

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:

  1. 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.
  2. 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 publishes PaymentProcessed.
  • 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 with UsingAzureServiceBus
  • 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

  1. Go to Azure PortalService Bus
  2. Create a Namespace (if not already created)
  3. Create a Queue (e.g., order-created-queue)
  4. 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

Popular posts from this blog

Azure key vault with .net framework 4.8

Azure Key Vault  With .Net Framework 4.8 I was asked to migrate asp.net MVC 5 web application to Azure and I were looking for the key vault integrations and access all the secrete out from there. Azure Key Vault Config Builder Configuration builders for ASP.NET  are new in .NET Framework >=4.7.1 and .NET Core >=2.0 and allow for pulling settings from one or many sources. Config builders support a number of different sources like user secrets, environment variables and Azure Key Vault and also you can create your own config builder, to pull in configuration from your own configuration management system. Here I am going to demo Key Vault integrations with Asp.net MVC(download .net framework 4.8). You will find that it's magical, without code, changes how your app can read secretes from the key vault. Just you have to do the few configurations in your web config file. Prerequisite: Following resource are required to run/complete this demo · ...

How to Make a Custom URL Shortener Using C# and .Net Core 3.1

C# and .Net Core 3.1:  Make a Custom URL Shortener Since a Random URL needs to be random and the intent is to generate short URLs that do not span more than 7 - 15 characters, the real thing is to make these short URLs random in real life too and not just a string that is used in the URLs Here is a simple clean approach to develop custom solutions Prerequisite:  Following are used in the demo.  VS CODE/VISUAL STUDIO 2019 or any Create one .Net Core Console Applications Install-Package Microsoft.AspNetCore -Version 2.2.0 Add a class file named ShortLink.cs and put this code: here we are creating two extension methods. public   static   class   ShortLink {      public   static   string   GetUrlChunk ( this   long   key ) =>            WebEncoders . Base64UrlEncode ( BitConverter . GetBytes ( key ));      public   static   long   GetK...

Azure Logic Apps Send Email Using Send Grid Step by Step Example

Azure Logic Apps Send Email Using Send Grid Step by Step     Step 1- Create Send Grid Account Create a SendGrid Account  https://sendgrid.com/ Login and Generate Sendgrid Key and keep it safe that will be used further to send emails You can use Free service. it's enough for the demo purpose Step 2- Logic App Design Login to  https://portal.azure.com Go to Resources and Create Logic App Named "EmailDemo" Go To Newly Created Rosoure Named "EmailDemo" and Select a Trigger "Recurrence", You can choose according to your needs like HTTP, etc. Note* Without trigger you can not insert new steps or Actions Click on Change Connection and add Send Grid Key  Click on Create and Save Button on the Top. As we have recurrence so it will trigger according to our setup(every 3 months) so just for the test click on "RUN" button  Finally, you should get an email like below one: