Introduction
In the previous lessons, we worked with RabbitMQ producers and consumers, retry policies, dead-letter queues, and Hangfire background jobs. This lesson focuses on one of the most important reliability problems in production systems: dual-write, the need to write both business data and an integration message as part of one operation.
Consider an API that creates an order. It saves the order to SQL Server and then publishes an OrderCreated message to RabbitMQ. If the database commit succeeds but the RabbitMQ connection fails, the order exists while downstream services never hear about it. If the message is published first and the database transaction later fails, consumers may process an event for an order that does not exist. These operations belong to different systems and cannot normally be rolled back together by one local transaction.
The Outbox Pattern solves this by storing the integration event in an Outbox table during the same database transaction as the business change. A background publisher later reads the stored event and publishes it to RabbitMQ. The order and the event are therefore made durable together, even when the broker is temporarily unavailable.
The dual-write problem
The following code is easy to write but is not reliable:
await db.Orders.AddAsync(order);
await db.SaveChangesAsync();
await rabbitMqPublisher.PublishAsync(new OrderCreated(order.Id));The process can terminate after SaveChangesAsync, the network can fail, or the exchange can be unavailable. The order remains in the database, but no event is available for consumers. Reversing the order creates the opposite problem: a consumer may receive an event before the database operation has committed.
With an Outbox, the request follows this sequence:
- Create the business entity and the integration event.
- Store both records in the same database transaction.
- Commit the transaction.
- Let a background publisher select pending Outbox records.
- Publish each event to RabbitMQ.
- Mark the record as published only after a successful broker confirmation.
- Retry transient failures later.
Designing the Outbox entity
We need to store the event payload, its type, its identity, and the current publication state:
public enum OutboxStatus
{
Pending = 0,
Processing = 1,
Published = 2,
Failed = 3
}
public sealed class OutboxMessage
{
public long Id { get; set; }
public Guid MessageId { get; set; }
public string EventType { get; set; } = null!;
public string Payload { get; set; } = null!;
public DateTime OccurredOnUtc { get; set; }
public DateTime? PublishedOnUtc { get; set; }
public DateTime? LockedUntilUtc { get; set; }
public int AttemptCount { get; set; }
public string? LastError { get; set; }
public OutboxStatus Status { get; set; }
}MessageId identifies the event and is also useful for consumer-side idempotency. The JSON payload can be stored as text. AttemptCount, LastError, and LockedUntilUtc support retry management and operational diagnostics.
Configure the EF Core model as follows:
public sealed class AppDbContext : DbContext
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<OutboxMessage> OutboxMessages => Set<OutboxMessage>();
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OutboxMessage>()
.HasIndex(x => new { x.Status, x.LockedUntilUtc, x.Id });
modelBuilder.Entity<OutboxMessage>()
.HasIndex(x => x.MessageId)
.IsUnique();
modelBuilder.Entity<OutboxMessage>()
.Property(x => x.Payload)
.HasColumnType("nvarchar(max)");
}
}The unique index helps prevent accidental creation of two Outbox records with the same event identifier. It does not, however, guarantee that RabbitMQ receives a message only once. A failure between broker acceptance and the database update can still cause a second publication, so consumers must remain idempotent.
Creating the order and event in one transaction
The application service can create the order and its event before calling SaveChangesAsync:
public sealed class OrderService
{
private readonly AppDbContext _db;
private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
public OrderService(AppDbContext db)
{
_db = db;
}
public async Task<Guid> CreateAsync(
decimal total,
CancellationToken cancellationToken)
{
var order = new Order
{
Id = Guid.NewGuid(),
Total = total,
CreatedOnUtc = DateTime.UtcNow
};
var messageId = Guid.NewGuid();
var payload = JsonSerializer.Serialize(new
{
MessageId = messageId,
OrderId = order.Id,
order.Total,
OccurredOnUtc = DateTime.UtcNow
}, _jsonOptions);
var outbox = new OutboxMessage
{
MessageId = messageId,
EventType = "orders.order-created.v1",
Payload = payload,
OccurredOnUtc = DateTime.UtcNow,
Status = OutboxStatus.Pending
};
_db.Orders.Add(order);
_db.OutboxMessages.Add(outbox);
await _db.SaveChangesAsync(cancellationToken);
return order.Id;
}
}For relational providers, EF Core can wrap changes made by a single SaveChangesAsync call in a transaction. If several saves or additional database commands are required, use an explicit transaction:
await using var transaction =
await _db.Database.BeginTransactionAsync(cancellationToken);
try
{
_db.Orders.Add(order);
_db.OutboxMessages.Add(outbox);
await _db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
}
catch
{
await transaction.RollbackAsync(cancellationToken);
throw;
}Do not publish to RabbitMQ while this database transaction is open. RabbitMQ does not participate in the SQL transaction, and holding database locks during a network operation increases contention and failure impact.
Implementing an Outbox BackgroundService
A publisher can periodically scan for pending messages. Each iteration should create a short-lived scope and a fresh DbContext. A hosted service is registered as a singleton, so scoped dependencies should not be captured directly in its constructor.
public sealed class OutboxPublisher : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<OutboxPublisher> _logger;
public OutboxPublisher(
IServiceScopeFactory scopeFactory,
ILogger<OutboxPublisher> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _scopeFactory.CreateScope();
var publisher = scope.ServiceProvider
.GetRequiredService<OutboxBatchPublisher>();
var published = await publisher.PublishBatchAsync(stoppingToken);
if (published == 0)
await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
_logger.LogError(exception, "Outbox batch processing failed");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
}Register it with builder.Services.AddHostedService<OutboxPublisher>(). The polling interval, batch size, worker count, and shutdown behavior should be tuned using measurements from the real workload rather than arbitrary defaults.
Batch selection, leases, and race conditions
Multiple application instances may read the same Outbox table. A worker must claim records before publishing them, otherwise two workers can process the same row simultaneously. A simple educational approach changes the status to Processing and assigns a short lease:
public async Task<int> PublishBatchAsync(CancellationToken cancellationToken)
{
const int batchSize = 50;
var now = DateTime.UtcNow;
var messages = await _db.OutboxMessages
.Where(x =>
(x.Status == OutboxStatus.Pending || x.Status == OutboxStatus.Failed) &&
(x.LockedUntilUtc == null || x.LockedUntilUtc < now))
.OrderBy(x => x.Id)
.Take(batchSize)
.ToListAsync(cancellationToken);
if (messages.Count == 0)
return 0;
foreach (var message in messages)
{
message.Status = OutboxStatus.Processing;
message.LockedUntilUtc = now.AddMinutes(2);
message.AttemptCount++;
}
await _db.SaveChangesAsync(cancellationToken);
foreach (var message in messages)
{
try
{
await _rabbitPublisher.PublishAsync(
message.EventType,
message.MessageId,
message.Payload,
cancellationToken);
message.Status = OutboxStatus.Published;
message.PublishedOnUtc = DateTime.UtcNow;
message.LockedUntilUtc = null;
}
catch (Exception exception)
{
message.Status = OutboxStatus.Failed;
message.LastError = exception.Message;
message.LockedUntilUtc = DateTime.UtcNow.AddMinutes(1);
}
}
await _db.SaveChangesAsync(cancellationToken);
return messages.Count;
}This example is intentionally simplified. In a production system, claiming rows should use an atomic update, an appropriate SQL Server locking strategy, or a carefully designed lease procedure. A plain read followed by an update can still be vulnerable to races under high concurrency.
Publisher confirms and delivery guarantees
RabbitMQ publisher confirms allow the publisher to verify that the broker accepted a message. The Outbox record should not be marked as Published until the RabbitMQ client reports a successful confirmation:
await _rabbitPublisher.PublishWithConfirmAsync(
exchange: "orders",
routingKey: "order.created",
messageId: message.MessageId,
payload: message.Payload,
cancellationToken: cancellationToken);If RabbitMQ accepts the message and the application terminates before the Outbox row is updated, the publisher may send it again after restarting. Therefore, an Outbox normally provides at-least-once publication, not guaranteed exactly-once delivery. Consumers should use the event identifier and an idempotency record to safely ignore duplicates.
Retries and permanent failures
Not every error should be retried forever. Temporary network failures, broker unavailability, and timeouts are usually retryable. Invalid JSON, an unknown event type, or a schema mismatch may be permanent failures.
| Condition | Recommended action |
|---|---|
| Transient connection failure | Retry with exponential backoff |
| Invalid payload | Move to Failed or an error store |
| Maximum attempts exceeded | Alert operators and require inspection |
| No broker confirmation | Retry without marking the row Published |
When the maximum attempt count is reached, keep the record available for manual replay or move it to an operational failure state. Always emit metrics and structured logs. Otherwise, failed events can accumulate silently in the table.
Using Hangfire as the publisher scheduler
Instead of a continuously running BackgroundService, Hangfire can trigger the batch publisher through a recurring job:
RecurringJob.AddOrUpdate<OutboxBatchPublisher>(
"outbox-publisher",
publisher => publisher.PublishBatchAsync(CancellationToken.None),
"*/1 * * * *");Hangfire provides persistent job storage, a dashboard, and built-in retry behavior, which can be useful operationally. It does not remove the need for Outbox row claiming, lease expiration, duplicate publication handling, or idempotent consumers. Treat the Hangfire method as restartable and safe to execute more than once.
Common mistakes
- Publishing before the database commit: A consumer may process an event for data that is later rolled back.
- Deleting the Outbox row immediately: Audit history, troubleshooting, and replay capabilities are lost.
- Using one DbContext inside a singleton worker: DbContext is not thread-safe and should not be retained indefinitely.
- Marking Published without confirmation: The database may report success even though the broker never accepted the message.
- Assuming exactly-once delivery: A crash can happen after publication but before the status update.
- Allowing unlimited table growth: Define retention, archiving, and cleanup policies.
Practice exercise
- Add an
OutboxMessagesentity and migration to the existing order module. - Store an order and its
OrderCreatedevent in oneSaveChangesAsyncoperation. - Implement a
BackgroundServicethat claims at most 20 records every three seconds. - Use RabbitMQ publisher confirms and set records to Published only after confirmation.
- Stop the publisher after RabbitMQ accepts a message but before the database update, then restart it.
- Verify that the consumer handles the duplicate using
MessageIdand an idempotency table.
Conclusion
The Outbox Pattern does not attempt to create one distributed transaction across SQL Server and RabbitMQ. Instead, it makes the business change and the integration event durable in one local database transaction, then uses a reliable, retryable publication process. Publisher confirms, lease-based claiming, exponential backoff, observability, and idempotent consumers together provide a robust asynchronous architecture.
In the final lesson, we will bring the course together with production observability, performance tuning, deployment considerations, and an end-to-end reliability checklist.
Sources
- https://learn.microsoft.com/en-us/ef/core/saving/transactions
- https://learn.microsoft.com/en-us/ef/core/saving/
- https://learn.microsoft.com/en-gb/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
- https://www.rabbitmq.com/client-libraries/dotnet-api-guide
- https://www.rabbitmq.com/tutorials/tutorial-seven-dotnet
- https://docs.hangfire.io/en/latest/background-processing/processing-background-jobs.html