| Domain-Driven Design (DDD) :👈 | 👉:Building Microservices Using RabbitMQ |
ASP.NET Core Distributed Transactions: Saga Pattern and Outbox Pattern |
ASP.NET Core Distributed Transactions: Saga Pattern and Outbox Pattern
1. Introduction
In a monolithic application, multiple database operations can often be executed within a single database transaction. If one operation fails, the transaction can be rolled back.
However, in a microservices architecture, each service generally owns its own database. A single business operation may involve multiple services and databases.
For example, when a customer places an order, the application may need to:
- Create an order.
- Reserve inventory.
- Process payment.
- Arrange shipping.
- Confirm the order.
Each operation may belong to a different microservice and database. A traditional SQL transaction cannot normally cover all these independent databases.
Two important patterns help solve this problem:
- Saga Pattern: Coordinates a business transaction across multiple services using local transactions and compensating actions.
- Outbox Pattern: Ensures that a database update and the event describing that update are stored reliably together.
2. What is a Distributed Transaction?
A distributed transaction is a business operation involving multiple independent systems, services, or databases.
Consider an e-commerce application:
- Order Service owns the Order database.
- Inventory Service owns the Inventory database.
- Payment Service owns the Payment database.
- Shipping Service owns the Shipping database.
When an order is placed, all these services may need to participate in the same business workflow.
Distributed Transaction Architecture – SVG Diagram
3. Why Not Use One Database Transaction?
Consider the following operation:
BEGIN TRANSACTION;
INSERT INTO Orders (...);
UPDATE Inventory
SET Quantity = Quantity - 1;
INSERT INTO Payments (...);
COMMIT;
This approach may work when all operations are managed by one database transaction and one database connection.
But in microservices:
- Order Service has its own database.
- Inventory Service has a separate database.
- Payment Service may communicate with an external payment provider.
- Shipping Service may use a third-party logistics API.
There is no ordinary local SQL transaction that atomically controls all these independent resources.
4. Two-Phase Commit (2PC)
Two-Phase Commit is a distributed transaction protocol that coordinates participating resources through a transaction coordinator.
It has two phases:
- Prepare Phase: The coordinator asks all participants whether they can commit. Participants prepare their changes and respond.
- Commit Phase: If all participants vote to commit, the coordinator instructs them to commit. Otherwise, it instructs them to roll back.
Two-Phase Commit SVG Diagram
Limitations of 2PC:
- Can block participants while waiting for the coordinator.
- Requires compatible transaction managers and resource support.
- Can introduce operational complexity.
- Does not naturally fit workflows involving external APIs and long-running business operations.
For many independently deployed microservices, the Saga Pattern is a more practical approach.
5. What is the Saga Pattern?
The Saga Pattern manages a distributed business transaction as a sequence of smaller local transactions.
Each service performs its own local transaction and communicates the result to the next participant.
If a later step fails, the system executes compensating transactions to reverse or counteract the business effects of previously completed steps.
Example: E-commerce order processing.
- Order Service creates an order.
- Inventory Service reserves stock.
- Payment Service processes payment.
- Shipping Service creates a shipment.
- Order Service marks the order as confirmed.
If payment fails after inventory reservation, the system can release the reserved inventory and cancel the order.
6. Saga Pattern Architecture – SVG Diagram
The diagram shows the successful forward workflow and possible compensating operations. The actual compensation sequence depends on which steps completed successfully and the business rules.
7. How Does the Saga Pattern Work?
Suppose a customer places an order for a product worth ₹5,000.
| Step | Service | Operation | Result |
|---|---|---|---|
| 1 | Order | Create order | Success |
| 2 | Inventory | Reserve product | Success |
| 3 | Payment | Charge ₹5,000 | Failure |
Since payment failed, the system needs to compensate for the completed operations.
| Compensation | Service | Action |
|---|---|---|
| 1 | Inventory | Release reserved product |
| 2 | Order | Mark order as cancelled or payment failed |
Notice that a Saga does not literally roll back all databases to an earlier state. It executes new business operations that compensate for earlier operations.
8. Types of Saga Pattern
There are two main approaches to implementing Saga.
8.1 Choreography-Based Saga
In choreography, there is no central coordinator. Each service publishes events and other services react to those events.
Example:
Order Service
|
| OrderCreated
v
Inventory Service
|
| InventoryReserved
v
Payment Service
|
| PaymentCompleted
v
Shipping Service
|
| ShipmentCreated
v
Order Service
|
v
Order Confirmed
Choreography SVG Diagram
Advantages:
- Services are loosely coupled.
- No central orchestrator is required.
- Works well for relatively simple event-driven workflows.
Disadvantages:
- Business workflow becomes difficult to understand as services increase.
- Event dependencies can become difficult to trace.
- Error handling and compensation may become scattered across services.
8.2 Orchestration-Based Saga
In orchestration, a central component called the Saga Orchestrator controls the workflow.
It sends commands to services, receives results, decides the next step, and initiates compensating actions when necessary.
Orchestration SVG Diagram
Advantages:
- Workflow logic is centralized.
- Easy to understand complex business processes.
- Compensation and failure handling can be managed centrally.
- Useful for long-running business workflows.
Disadvantages:
- Orchestrator requires careful design and monitoring.
- Can become a large component if workflow logic is not separated properly.
- Services need well-defined commands and response contracts.
9. What is the Outbox Pattern?
The Outbox Pattern solves a different but related problem: how to reliably publish an event after updating a database.
Consider the following code:
await _context.Orders.AddAsync(order);
await _context.SaveChangesAsync();
await _messagePublisher.PublishAsync(
new OrderCreatedEvent(order.Id));
There is a potential failure:
- Order is successfully saved in SQL Server.
- The application tries to publish OrderCreated.
- RabbitMQ is temporarily unavailable.
- The event is not published.
Now the order exists, but other services never received the event.
This is called the Dual Write Problem.
10. Dual Write Problem – SVG Diagram
11. How Does the Outbox Pattern Work?
Instead of publishing directly to RabbitMQ, the application stores the event in an Outbox table in the same database transaction as the business update.
Steps:
- Receive a business command.
- Create or update the business entity.
- Create an Outbox record containing the event.
- Save both changes in one database transaction.
- A background worker reads pending Outbox records.
- The worker publishes the event to the message broker.
- After successful publication, the Outbox record is marked as processed.
Transactional Outbox SVG Diagram
Important: The business data and Outbox record are committed atomically in one local database transaction. Publishing to the broker happens afterward and is retried if necessary.
12. Outbox Table Structure
A simple Outbox table may contain the following columns:
| Column | Purpose |
|---|---|
| Id | Unique Outbox record identifier. |
| EventId | Unique identifier for the business event. |
| EventType | Event contract type. |
| Payload | Serialized event data. |
| OccurredAtUtc | When the event occurred. |
| ProcessedAtUtc | When the event was successfully published. |
| RetryCount | Number of publication attempts. |
| Error | Last publication error, if any. |
SQL Server Table Example
CREATE TABLE OutboxMessages
(
Id BIGINT IDENTITY PRIMARY KEY,
EventId UNIQUEIDENTIFIER NOT NULL,
EventType NVARCHAR(300) NOT NULL,
Payload NVARCHAR(MAX) NOT NULL,
OccurredAtUtc DATETIME2 NOT NULL,
ProcessedAtUtc DATETIME2 NULL,
RetryCount INT NOT NULL DEFAULT 0,
Error NVARCHAR(MAX) NULL
);
CREATE UNIQUE INDEX UX_OutboxMessages_EventId
ON OutboxMessages(EventId);
13. Implementing Outbox Pattern in ASP.NET Core
Let's implement a simplified Transactional Outbox using ASP.NET Core, EF Core, SQL Server, and a background worker.
Step 1: Create the Event Contract
public record OrderCreatedEvent(
Guid EventId,
int OrderId,
string CustomerName,
decimal TotalAmount,
DateTime OccurredAtUtc
);
Step 2: Create the Outbox Entity
public class OutboxMessage
{
public long Id { get; set; }
public Guid EventId { get; set; }
public string EventType { get; set; } = "";
public string Payload { get; set; } = "";
public DateTime OccurredAtUtc { get; set; }
public DateTime? ProcessedAtUtc { get; set; }
public int RetryCount { get; set; }
public string? Error { get; set; }
}
Step 3: Add Outbox to DbContext
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Order> Orders => Set<Order>();
public DbSet<OutboxMessage> OutboxMessages
=> Set<OutboxMessage>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<OutboxMessage>()
.HasIndex(x => x.EventId)
.IsUnique();
modelBuilder.Entity<OutboxMessage>()
.HasIndex(x => x.ProcessedAtUtc);
}
}
Step 4: Save Order and Outbox Event Together
public class CreateOrderService
{
private readonly AppDbContext _context;
public CreateOrderService(AppDbContext context)
{
_context = context;
}
public async Task<int> CreateAsync(
string customerName,
decimal totalAmount,
CancellationToken cancellationToken)
{
await using var transaction =
await _context.Database.BeginTransactionAsync(
cancellationToken);
var order = new Order(customerName);
_context.Orders.Add(order);
await _context.SaveChangesAsync(cancellationToken);
var eventMessage = new OrderCreatedEvent(
Guid.NewGuid(),
order.Id,
customerName,
totalAmount,
DateTime.UtcNow
);
var outboxMessage = new OutboxMessage
{
EventId = eventMessage.EventId,
EventType = nameof(OrderCreatedEvent),
Payload = JsonSerializer.Serialize(eventMessage),
OccurredAtUtc = eventMessage.OccurredAtUtc
};
_context.OutboxMessages.Add(outboxMessage);
await _context.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return order.Id;
}
}
Both the order and Outbox record are committed in the same database transaction.
The example assumes the Order entity is mapped by EF Core and that the database transaction covers all participating changes.
Step 5: Define a Message Publisher
public interface IMessagePublisher
{
Task PublishAsync(
string eventType,
string payload,
CancellationToken cancellationToken);
}
A RabbitMQ, Azure Service Bus, or Kafka implementation can implement this interface.
Step 6: Create a Background Worker
The background worker reads pending records and publishes them.
public class OutboxBackgroundService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<OutboxBackgroundService> _logger;
public OutboxBackgroundService(
IServiceScopeFactory scopeFactory,
ILogger<OutboxBackgroundService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ProcessMessages(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Outbox processing failed.");
}
await Task.Delay(
TimeSpan.FromSeconds(5),
stoppingToken);
}
}
private async Task ProcessMessages(
CancellationToken cancellationToken)
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider
.GetRequiredService<AppDbContext>();
var publisher = scope.ServiceProvider
.GetRequiredService<IMessagePublisher>();
var messages = await context.OutboxMessages
.Where(x => x.ProcessedAtUtc == null)
.OrderBy(x => x.Id)
.Take(20)
.ToListAsync(cancellationToken);
foreach (var message in messages)
{
try
{
await publisher.PublishAsync(
message.EventType,
message.Payload,
cancellationToken);
message.ProcessedAtUtc = DateTime.UtcNow;
message.Error = null;
}
catch (Exception ex)
{
message.RetryCount++;
message.Error = ex.Message;
_logger.LogWarning(
ex,
"Failed to publish outbox event {EventId}",
message.EventId);
}
await context.SaveChangesAsync(cancellationToken);
}
}
}
Important: This is a learning example, not a complete production dispatcher. Multiple workers could select the same pending record, and a process crash after broker publication but before marking the record as processed can cause duplicate delivery.
Production implementations should use safe message claiming or leasing, concurrency control, bounded retries, backoff, dead-letter handling, and idempotent consumers. For high-throughput systems, consider a dedicated Outbox dispatcher or a CDC-based solution.
Step 7: Register the Background Worker
builder.Services.AddHostedService<OutboxBackgroundService>();
Register the message publisher implementation as well:
builder.Services.AddSingleton<IMessagePublisher, RabbitMqPublisher>();
The publisher should be designed for safe concurrent use and should manage broker connections appropriately. Its implementation depends on the messaging library and broker configuration.
14. What Happens If the Worker Crashes?
Consider this sequence:
- Worker reads an Outbox record.
- Worker successfully publishes the event to RabbitMQ.
- Worker crashes before updating ProcessedAtUtc.
- After restart, the worker reads the same record.
- The event is published again.
This is why the Outbox Pattern generally provides at-least-once delivery, rather than exactly-once delivery.
The consumer must be idempotent.
15. Idempotent Consumer Pattern
An idempotent consumer prevents the same event from producing the same business effect multiple times.
For example, Inventory Service should not reserve stock twice for the same OrderCreated event.
Processed Events Table
CREATE TABLE ProcessedEvents
(
EventId UNIQUEIDENTIFIER PRIMARY KEY,
ProcessedAtUtc DATETIME2 NOT NULL
);
Consumer Processing Logic
public async Task HandleAsync(
OrderCreatedEvent message,
CancellationToken cancellationToken)
{
await using var transaction =
await _context.Database.BeginTransactionAsync(
cancellationToken);
var alreadyProcessed =
await _context.ProcessedEvents
.AnyAsync(
x => x.EventId == message.EventId,
cancellationToken);
if (alreadyProcessed)
return;
// Apply the business operation.
await ReserveInventoryAsync(
message.OrderId,
cancellationToken);
_context.ProcessedEvents.Add(
new ProcessedEvent
{
EventId = message.EventId,
ProcessedAtUtc = DateTime.UtcNow
});
await _context.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
}
The inventory update and processed-event record must be committed in the same local transaction. The database should enforce uniqueness on EventId to protect against concurrent duplicate deliveries.
16. Combining Saga and Outbox Patterns
Saga and Outbox solve different problems and work particularly well together.
- Saga coordinates the overall business workflow.
- Outbox reliably records outgoing messages alongside local database changes.
- Idempotent consumers protect against duplicate event delivery.
Combined Saga + Outbox SVG Diagram
17. Saga vs Outbox Pattern
| Aspect | Saga Pattern | Outbox Pattern |
|---|---|---|
| Main purpose | Coordinate distributed business transactions. | Reliably publish events after database changes. |
| Problem solved | Multi-service workflow and compensation. | Dual write problem. |
| Key concept | Local transactions and compensating actions. | Business data and Outbox record in one transaction. |
| Coordinator | Optional, depending on choreography or orchestration. | Background publisher or CDC mechanism. |
| Failure handling | Compensating business operations. | Retry message publication. |
| Can be combined? | Yes. | Yes. |
18. Saga vs Outbox vs Two-Phase Commit
| Feature | 2PC | Saga | Outbox |
|---|---|---|---|
| Atomic transaction across services | Coordinates distributed commit | No global atomic commit | Atomic within one local database |
| Compensation | Rollback before commit | Business compensation | Not its responsibility |
| Message publishing | Not its primary purpose | Often uses messages | Its primary purpose |
| Typical use | Compatible distributed transaction resources | Long-running microservice workflows | Reliable event publishing |
19. Important Production Considerations
19.1 Idempotency
Every consumer should be prepared to receive duplicate messages. Use unique event IDs and transactional deduplication.
19.2 Retry Policy
Use bounded retries with exponential backoff and jitter for temporary failures. Avoid retrying permanent business failures indefinitely.
19.3 Dead-Letter Queue
Messages that repeatedly fail should be moved to a dead-letter queue for investigation and controlled recovery.
19.4 Saga State Persistence
Persist Saga state so that the workflow can continue after application restarts.
Typical Saga state fields include:
- SagaId
- OrderId
- CurrentStep
- Status
- StartedAtUtc
- LastUpdatedAtUtc
- FailureReason
19.5 Compensation Must Be Business-Aware
Compensation is not always a literal reversal.
For example:
- Payment captured: issue a refund.
- Inventory reserved: release the reservation.
- Shipment created: request shipment cancellation, if possible.
- Email sent: a previously delivered email cannot be unsent. A corrective notification may be required.
19.6 Observability
Use structured logging, correlation IDs, distributed tracing, metrics, and dashboards to track distributed workflows.
Useful metrics include:
- Saga completion rate.
- Saga failure rate.
- Compensation count.
- Outbox pending message count.
- Oldest pending Outbox message age.
- Message delivery failures.
- Consumer processing latency.
- Dead-letter queue size.
20. Common Tools for ASP.NET Core
| Tool | Purpose |
|---|---|
| ASP.NET Core | Build APIs and background services. |
| Entity Framework Core | Database transactions and persistence. |
| RabbitMQ | Message broker and event routing. |
| Azure Service Bus | Managed messaging and enterprise integration. |
| Apache Kafka | Distributed event streaming. |
| MassTransit | .NET messaging abstraction with Saga and Outbox support. |
| NServiceBus | .NET messaging and distributed workflow infrastructure. |
| OpenTelemetry | Distributed tracing and observability. |
21. MassTransit for Saga and Outbox
MassTransit is a .NET messaging framework that provides abstractions for message publishing, consumers, retries, and Saga state machines.
It can integrate with message brokers such as RabbitMQ and Azure Service Bus. Its Entity Framework Core integration also supports transactional Outbox scenarios.
A typical implementation includes:
- Define message contracts.
- Create consumers.
- Define Saga state and state machine.
- Configure the message broker transport.
- Configure the Entity Framework Outbox.
- Configure retry, error handling, and observability.
Package APIs and registration methods depend on the MassTransit version. Follow the documentation for the version used by the application.
22. When Should You Use Saga?
- Business operations span multiple microservices.
- Each service owns its own database.
- Transactions are long-running.
- Business compensation is possible.
- There is no suitable global transaction across the participating services.
23. When Should You Use Outbox?
- A service updates a database and publishes an event.
- Database updates must not lose their corresponding events.
- Message broker availability may be intermittent.
- Reliable asynchronous integration is important.
- Consumers must receive events even when publication needs to be retried.
24. When Should You Avoid These Patterns?
- Simple CRUD applications with no distributed workflow.
- Applications where a normal database transaction is sufficient.
- Workflows where compensation cannot be defined and business owners have not agreed on failure handling.
- Small applications where the operational overhead is greater than the benefit.
25. Enterprise Interview Questions and Answers
Q1. What is a distributed transaction?
A business operation involving multiple independent services, databases, or systems.
Q2. What is the Saga Pattern?
A pattern that coordinates a distributed business transaction through a sequence of local transactions and compensating actions.
Q3. What is a compensating transaction?
A business operation that counteracts the effect of an earlier successful operation when a later step fails.
Q4. What are the two types of Saga?
Choreography-based Saga and orchestration-based Saga.
Q5. What is the difference between choreography and orchestration?
Choreography relies on services reacting to events without a central coordinator. Orchestration uses a central Saga component to manage the workflow.
Q6. What is the Outbox Pattern?
It stores a business data change and its outgoing event record in the same local database transaction. A background process publishes the event afterward.
Q7. What is the dual write problem?
It occurs when an application writes to a database and publishes to a message broker as separate operations. One can succeed while the other fails.
Q8. Does the Outbox Pattern guarantee exactly-once message delivery?
No. It generally provides at-least-once publication. Consumers must handle duplicate delivery using idempotency.
Q9. How does Saga handle failures?
It executes compensating transactions for previously completed steps according to the business workflow.
Q10. Can Saga and Outbox be used together?
Yes. Saga coordinates the business workflow, while Outbox reliably records and publishes messages from each participating service.
Q11. What is the difference between Saga and 2PC?
2PC coordinates a distributed commit using transaction participants. Saga uses independent local transactions and business compensations without requiring one global atomic transaction.
Q12. What happens if a Saga service crashes?
A persistent Saga state allows the workflow to resume or recover after restart. Message redelivery and idempotent processing are also important.
Q13. What is a dead-letter queue?
A queue where messages are placed after they cannot be processed successfully under the configured retry and error-handling policy.
Q14. Why is idempotency important in microservices?
Because message brokers and retry mechanisms can deliver the same message more than once. Idempotency prevents duplicate business effects.
Q15. Can an external payment API participate in a SQL transaction?
Usually not. The payment operation is handled as an independent step in the Saga. If a later step fails after payment succeeds, the application may need to issue a refund or void operation.
Q16. What is the difference between an Outbox and an Inbox?
Outbox stores outgoing messages that need to be published. Inbox stores or tracks incoming messages to support deduplication and reliable processing.
Q17. What is the purpose of correlation ID?
It links related logs, messages, and service operations to help trace one distributed business workflow.
Q18. What is the role of MassTransit?
MassTransit provides .NET abstractions for messaging, consumers, retries, Saga state machines, and Outbox integration.
26. Final Summary
- Distributed Transaction: A business operation involving multiple independent systems.
- 2PC: A distributed commit protocol using prepare and commit phases.
- Saga: Coordinates a business workflow using local transactions and compensation.
- Choreography: Services coordinate through events.
- Orchestration: A central coordinator controls the workflow.
- Outbox: Stores business changes and outgoing event records in one local transaction.
- Idempotency: Prevents duplicate messages from causing repeated business effects.
- Dead-Letter Queue: Holds messages that repeatedly fail processing.
- MassTransit: Helps implement messaging, Saga, and Outbox patterns in .NET.
Key takeaway: Saga solves the problem of coordinating business operations across multiple services. Outbox solves the problem of reliably publishing events after local database changes. In enterprise ASP.NET Core microservices, combining Saga, Outbox, idempotent consumers, and observability provides a robust foundation for distributed workflows.
| Domain-Driven Design (DDD) :👈 | 👉:Building Microservices Using RabbitMQ |