The transactional outbox pattern: keeping your database and message queue consistent
Picture an order service: it saves the order to the database, then publishes an "order placed" event to the message queue. The inventory, invoicing and notification services listen for that event. The code is two lines long and works flawlessly in tests. In production, strange things happen now and then: an order that was saved but never deducted from stock, or an email sent for an order that does not exist.
The source of the problem is not the code itself but the assumption that you can write to two separate systems and both will succeed. In this post I explain why that problem is unavoidable and how the transactional outbox pattern solves it, with a concrete example on EF Core and PostgreSQL.
The dual-write problem
The database and the message queue are separate systems; there is no shared transaction spanning both. So there is always a gap between the two writes, and the process can crash in exactly that gap, the network can drop, or the queue can be temporarily unreachable.
Changing the order does not solve the problem, it only changes the kind of failure. If you write to the database first and publish afterwards, a failed publish leaves you with an order nobody knows about. If you publish first and save afterwards, a rolled-back transaction means other services have acted on an order that does not exist. Wrapping the publish in a try/catch and retrying is not enough either: if the process shuts down during the retry, the in-memory message is gone.
Distributed transaction protocols are a solution on paper, but most messaging infrastructure does not support them, and where it does, the operational cost and performance penalty are high. In practice a simpler idea works: instead of writing to two systems, write to only one.
The outbox idea
With the outbox pattern, the service does not send the message to the queue. Instead it writes the message to a table in the same database as the business data, inside the same transaction. The order row and the "order placed" message either become durable together or roll back together. No inconsistent state can exist in between, because the thing guaranteeing it is the database's own transaction mechanism.
Moving the message to the queue is left to a separate component, the relay. The relay reads the table, publishes the unsent messages and marks the successful ones. If the queue is unreachable at that moment, the messages wait in the table; when the connection comes back, the relay picks up where it left off.
The table itself is plain:
public sealed class OutboxMessage
{
public Guid Id { get; init; }
public string Type { get; init; } = "";
public string Payload { get; init; } = "";
public DateTimeOffset OccurredAt { get; init; }
public DateTimeOffset? ProcessedAt { get; set; }
}
It matters that Type holds a stable contract name such as order.placed.v1 rather than a class name. Renaming the class must not break messages that are waiting in the table or that consumers already recognise.
Writing the message in the same transaction
In EF Core, a single SaveChangesAsync call writes all tracked changes inside one transaction. That makes the write side of the outbox quite short:
public async Task PlaceOrderAsync(PlaceOrder command, CancellationToken ct)
{
var order = Order.Create(command.CustomerId, command.Lines);
db.Orders.Add(order);
db.OutboxMessages.Add(new OutboxMessage
{
Id = Guid.NewGuid(),
Type = "order.placed.v1",
Payload = JsonSerializer.Serialize(
new OrderPlaced(order.Id, order.CustomerId, order.Total)),
OccurredAt = timeProvider.GetUtcNow()
});
await db.SaveChangesAsync(ct);
}
Two things deserve attention here. First, the message content is serialised at write time; the relay does not re-read the order later to build the message. That way the message carries the state as it was when the event happened. Second, the outbox row must be added through the same DbContext as the business data. If you use a separate connection or a separate SaveChanges call, you have simply moved the dual-write problem inside the database.
As the number of events grows, rather than adding the row by hand in every command handler, you can write an interceptor that turns the domain events raised by your entities into outbox rows just before SaveChanges. That reduces repetition, but the essence of the pattern does not change: same transaction, same database.
The relay: from table to queue
The simplest form of the relay is a background service that polls the table at short intervals. The real concern is preventing two instances of the service from picking up the same message at the same time. In PostgreSQL, FOR UPDATE SKIP LOCKED solves this directly: rows locked by one instance are skipped by the other without waiting.
private async Task<int> PublishBatchAsync(CancellationToken ct)
{
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await using var tx = await db.Database.BeginTransactionAsync(ct);
var batch = await db.OutboxMessages
.FromSqlRaw("""
SELECT * FROM outbox_messages
WHERE processed_at IS NULL
ORDER BY occurred_at
LIMIT 50
FOR UPDATE SKIP LOCKED
""")
.ToListAsync(ct);
foreach (var message in batch)
{
await publisher.PublishAsync(message.Type, message.Id, message.Payload, ct);
message.ProcessedAt = timeProvider.GetUtcNow();
}
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
return batch.Count;
}
This method is called from a BackgroundService every few seconds using a PeriodicTimer; calling it again without waiting for as long as it returns more than zero drains a backlog quickly. The table and column names in the query depend on your mapping; the example assumes snake_case naming.
Polling adds a delay of up to one interval before a message is published. For most workflows a few seconds is acceptable. If you need lower latency, you can wake the relay with the database's notification mechanism, or replace polling with a change data capture tool that reads the database's change log. Both mean more infrastructure; it is healthier to start with polling and move on when the need arises.
At-least-once delivery and idempotent consumers
Look closely at the code above and you will see the dual-write problem reappear in the relay: the message is published, then ProcessedAt is written. If the publish succeeds and the commit fails, the message is sent again on the next round.
The difference is that this time the failure can only go one way. A message is never lost, but it may be delivered more than once. The outbox pattern does not provide "exactly once" delivery; it provides "at least once" delivery. That is a deliberate trade, because coping with a duplicate message is far easier than coping with a lost one.
Making duplicates harmless is the consumer's job. The most common approach is a table on the consumer side that stores the ids of processed messages. The consumer inserts the message Id into that table in the same transaction as its own business change; if the unique constraint on the id is violated, the message has been handled before and is silently skipped. Some operations are idempotent by nature: applying "mark the order as paid" twice does not change the outcome, whereas "deduct one unit from stock" does. For the second kind, the id check is mandatory.
Ordering, poison messages and cleanup
Once the pattern is up and running, three operational topics come to the fore.
Ordering. A single relay instance publishes messages in occurred_at order. With multiple instances and SKIP LOCKED, global order is not guaranteed; two events for the same order can be published in reverse by different instances. If order matters, you either run a single instance or make the consumer resilient to it: including the entity's version number in the message and ignoring messages with an older version is a simple and effective technique.
Poison messages. In the example loop, a single message that cannot be published causes the whole batch to roll back and the same message to be retried forever. For transient failures such as an unreachable queue, that is the right behaviour. But if the message itself is broken, it blocks everything behind it. Adding an attempt counter and a last-error field to the row, then moving the message to a separate state and raising an alert past a certain threshold, keeps the queue from stalling because of one row.
Cleanup and monitoring. If processed rows are never deleted, the table grows without bound. Periodically deleting processed rows older than a given age, and using a partial index that covers only unprocessed rows, keeps the relay's query independent of table size. On the monitoring side, the two most valuable metrics are the number of pending messages and the age of the oldest pending message. If the latter keeps growing, the relay has stopped or the queue is unreachable, and that is something you want to know before your users notice.
When is it needed, and when is it too much?
The outbox makes sense wherever a data change absolutely must be communicated to another system: events between services, webhook deliveries, search index updates, emails sent after an operation. If the price of a lost message is inconsistent data or manual fixes, an extra table and a background service are a small cost.
It is unnecessary for messages whose loss can be tolerated. If a cache invalidation notice or a live UI update goes missing and the system recovers shortly afterwards anyway, publishing directly is enough. Likewise, in a modular monolith with a single database you may not need a message queue for communication between modules at all; handlers in the same process can consume the outbox table directly.
Writing the pattern yourself is not hard, but if the messaging library you use has built-in outbox support, preferring it saves you from rediscovering details such as retries and cleanup. Whichever you choose, you need to understand the guarantee behind it.
Closing
The transactional outbox reduces a hard distributed systems problem to a well-known tool, the local database transaction. It writes the message together with the business data, defers publishing until later and trades loss for duplication. The remaining work is to complete the other half of that trade: consumers that make duplicates harmless, metrics that reveal a stall and a cleanup job that keeps the table small. Once those pieces are in place, failures of the "saved but nobody was told" kind stop being a matter of chance and become impossible by design.