Introduction
In the previous lesson, we established asynchronous messaging with RabbitMQ. However, successfully publishing a message does not automatically make a distributed system reliable. The Order service may save an order and then stop before publishing its event. A request may time out after the broker accepted a message, causing the application to publish it again. A consumer may update its database and terminate before sending an acknowledgement, so RabbitMQ delivers the message again.
In this lesson, we will make the order workflow more reliable. The Order service will store the order and its integration event in the same local database transaction. A separate publisher will forward pending outbox records to RabbitMQ. The Inventory service will process events idempotently. Temporary failures will be retried with limits, while permanent failures will be moved to a dead-letter queue.
The main principle is that exactly-once processing is usually not a practical assumption in distributed systems. Instead, design for at-least-once delivery and make consumers safe to run more than once.
1. Identify the reliability problem
A simplified order workflow contains these steps:
- The Order service saves a new order to SQL Server.
- The Order service publishes an
OrderCreatedmessage to RabbitMQ. - The Inventory service consumes the message and reserves stock.
If the process fails between the first and second steps, the order exists in the database but other services never receive the event. In the opposite direction, if the message was accepted but the HTTP request timed out, the application may publish the same event again. If the consumer writes the stock reservation and stops before the acknowledgement reaches RabbitMQ, the broker may redeliver the event.
Separate these failure categories:
- Message loss: The database commit succeeds, but publishing to the broker does not happen.
- Duplicate delivery: The consumer completes its work, but the acknowledgement is lost or delayed.
- Transient failure: A database, network, or broker dependency is temporarily unavailable.
- Permanent failure: The event schema is invalid or the business rule cannot succeed through another retry.
2. Use the Outbox Pattern for atomic recording
The Outbox Pattern stores business data and the event that must be published in the same database transaction. If the order is committed, the outbox record is committed as well. If the transaction rolls back, both records are rolled back. The application does not need to publish directly during the request; it first records a durable delivery task.
Example entity:
public sealed class OutboxMessage
{
public Guid Id { get; set; }
public string Type { get; set; } = null!;
public string Payload { get; set; } = null!;
public DateTimeOffset OccurredOnUtc { get; set; }
public DateTimeOffset? ProcessedOnUtc { get; set; }
public int AttemptCount { get; set; }
public string? LastError { get; set; }
}Keep the order and outbox insert in the same SaveChangesAsync operation:
public async Task<Guid> CreateOrderAsync(
CreateOrderCommand command,
CancellationToken cancellationToken)
{
var order = new Order
{
Id = Guid.NewGuid(),
CustomerId = command.CustomerId,
Status = OrderStatus.Pending
};
db.Orders.Add(order);
var message = new OrderCreatedIntegrationEvent(
order.Id,
order.CustomerId,
command.Items);
db.OutboxMessages.Add(new OutboxMessage
{
Id = Guid.NewGuid(),
Type = nameof(OrderCreatedIntegrationEvent),
Payload = JsonSerializer.Serialize(message),
OccurredOnUtc = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync(cancellationToken);
return order.Id;
}When the relational provider supports transactions, EF Core executes a single SaveChanges operation transactionally. If you introduce multiple save operations or manually controlled transactions, define the boundary deliberately. Trying to include RabbitMQ publishing inside the SQL transaction creates a distributed transaction problem between two independent systems. The outbox approach avoids that coupling.
3. Build the outbox publisher worker
The outbox publisher periodically loads unprocessed records and publishes them to a RabbitMQ exchange. After a successful publish, it sets ProcessedOnUtc. If the result is uncertain, the record should remain available for another attempt instead of being deleted immediately.
public sealed class OutboxPublisherWorker(
IServiceScopeFactory scopeFactory,
IMessageBus bus,
ILogger<OutboxPublisherWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider
.GetRequiredService<OrdersDbContext>();
var messages = await db.OutboxMessages
.Where(x => x.ProcessedOnUtc == null)
.OrderBy(x => x.OccurredOnUtc)
.Take(20)
.ToListAsync(stoppingToken);
foreach (var message in messages)
{
try
{
await bus.PublishAsync(
message.Type,
message.Payload,
stoppingToken);
message.ProcessedOnUtc = DateTimeOffset.UtcNow;
}
catch (Exception ex)
{
message.AttemptCount++;
message.LastError = ex.Message;
logger.LogError(ex,
"Outbox message {MessageId} failed",
message.Id);
}
}
await db.SaveChangesAsync(stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
}
}
}In production, multiple publisher instances must not claim the same outbox row simultaneously. Use row locking, leasing, or an explicit processing state. The sample assumes a single publisher for clarity. With multiple instances, evaluate SQL Server locking hints or a lease column appropriate for your deployment.
4. Connect RabbitMQ through Aspire
Define RabbitMQ in the AppHost and reference it from the Order and Inventory services:
var builder = DistributedApplication.CreateBuilder(args);
var rabbitmq = builder.AddRabbitMQ("messaging")
.WithManagementPlugin();
var sql = builder.AddSqlServer("sql")
.AddDatabase("ordersdb");
builder.AddProject<Projects.OrderService>("orders")
.WithReference(sql)
.WithReference(rabbitmq);
builder.AddProject<Projects.InventoryService>("inventory")
.WithReference(rabbitmq);
builder.Build().Run();In the Order and Inventory projects, use the same resource name when registering the client integration:
builder.AddRabbitMQClient("messaging");Aspire supplies the connection information and lets you inspect the resource, logs, and management endpoint from the dashboard. Aspire does not, however, guarantee that an event was processed safely according to your business rules. Outbox, retry, and idempotency remain application responsibilities.
5. Design a retry strategy
Retrying every error indefinitely is unsafe. Temporary network failures, short broker outages, and brief database connectivity problems may be retryable. Invalid JSON, an unknown event type, or an impossible business operation generally represents a permanent failure.
Use exponential backoff with a maximum attempt count:
static TimeSpan GetRetryDelay(int attempt)
{
var seconds = Math.Min(Math.Pow(2, attempt), 60);
return TimeSpan.FromSeconds(seconds);
}A sequence such as 1, 2, 4, 8, and 16 seconds is easy to observe during development. Add a small random jitter when multiple consumer instances retry simultaneously, so they do not all reconnect or query the same dependency at exactly the same moment.
A consumer processing flow can be structured as follows:
- Deserialize and validate the message.
- Check the idempotency record.
- Apply business changes and database updates.
- Acknowledge the message only after successful completion.
- For a transient error, perform a controlled retry or requeue.
- For a permanent error, reject the message without requeue so it can enter the dead-letter flow.
6. Implement an idempotent consumer
The Inventory service may receive the same OrderCreated event more than once. Treat this as an expected distributed-systems behavior rather than an exceptional condition. Give each integration event a unique EventId and store processed event identifiers in the consumer database.
public sealed class ProcessedMessage
{
public Guid EventId { get; set; }
public DateTimeOffset ProcessedOnUtc { get; set; }
}Apply the business operation and insert the processed marker in one database transaction:
await using var transaction =
await db.Database.BeginTransactionAsync(cancellationToken);
var alreadyProcessed = await db.ProcessedMessages
.AnyAsync(x => x.EventId == message.EventId, cancellationToken);
if (!alreadyProcessed)
{
await inventory.ReserveAsync(message.Items, cancellationToken);
db.ProcessedMessages.Add(new ProcessedMessage
{
EventId = message.EventId,
ProcessedOnUtc = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync(cancellationToken);
}
await transaction.CommitAsync(cancellationToken);Create a unique database index on EventId. If two consumer instances process the same event concurrently, the database constraint prevents a second marker from being inserted. An in-memory HashSet<Guid> is not sufficient because it disappears on restart and cannot coordinate multiple instances.
7. Configure a dead-letter queue
When retry attempts are exhausted, continuously returning the message to the main queue creates an infinite loop. Configure a dead-letter exchange and queue instead. Record the failure reason, attempt count, and last exception. Operations staff can inspect the dead-letter queue and replay a message after correcting the underlying problem.
RabbitMQ can route a message to dead-letter configuration when it is negatively acknowledged with requeue: false. A dead-letter queue is not an automatic trash can. Monitor its depth, create alerts, and define a documented replay procedure.
8. Test the failure scenarios
Run these scenarios manually:
- Stop the Order service immediately after saving the order. Restart it and verify that the outbox worker publishes the event.
- Throw a controlled exception in the Inventory consumer. Observe that the message is retried according to the configured limit.
- Prevent acknowledgement immediately after the business operation completes. Verify that the repeated event does not create a second stock reservation.
- Publish an invalid event payload. Confirm in the RabbitMQ management interface that it reaches the dead-letter queue after the retry limit.
- Compare Order, Inventory, and RabbitMQ logs in the Aspire dashboard over the same time interval.
Common mistakes
- Publishing before storing the business data: The broker operation may succeed while the subsequent SQL operation fails.
- Deleting the outbox row before a confirmed publish: A publisher crash can lose the message. Publish first, then mark it processed.
- Unlimited retry: A poison message can consume resources and block healthy traffic.
- Keeping idempotency only in memory: Restarting the application or adding another instance removes the protection.
- Treating every error as retryable: Schema and business-rule errors should usually go to a dead-letter workflow.
- Failing to acknowledge after successful processing: The broker can redeliver the same message repeatedly.
Practice exercise
Add an OutboxMessages table to the Order service. Update order creation so that it also stores an OrderCreatedIntegrationEvent. Add a background worker that publishes pending records to the RabbitMQ exchange. Then add event-id checking and limited exponential backoff to the Inventory consumer.
Record three test results: successful first delivery, duplicate delivery, and a permanent failure that reaches the dead-letter queue. For each result, note the event identifier, attempt count, and relevant log entry.
Conclusion
Reliable messaging is not achieved by one RabbitMQ setting. The Outbox Pattern addresses consistency between the database and the broker. An idempotent consumer handles duplicate delivery. Bounded retry manages transient failures, while a dead-letter queue isolates permanent failures. Aspire brings RabbitMQ, services, health checks, and observability into one application model, but the application must still define safe business behavior.
In the next step, we can extend this workflow with richer resilience policies, message replay operations, and distributed tracing so the design more closely resembles a production environment.