The first thing a monolith does after it gets a message broker is this: save something to the database, then publish an event about it. It looks harmless, and it works in every demo. It is also the most common way for two services to end up disagreeing, because a database and a broker cannot be changed in one step. Something can always happen between the two writes.
This case shows the problem with running code and failing tests, and then the standard fix: the transactional outbox. The code is on GitHub: chudovo/application-modernization, case 10. It uses a real PostgreSQL and a real RabbitMQ.
At a glance
| Before | After | |
|---|---|---|
| Order service | saves the order, then publishes the event | saves order and event in one transaction |
| Publishing | inside the request | by a relay, from an outbox table |
| Broker unavailable | request fails, order stays, never shipped | request succeeds, shipment follows later |
| Delivery to the consumer | once, unless something fails | at least once |
| Consumer | one shipment per message | one shipment per message identity |
| 300 orders under failures | 53 never shipped, 10 shipped twice | 300 shipped, each once |
The setup
Two services. The order service stores orders in its own tables. The shipping service listens for an OrderPlaced event and creates a shipment. Between them is a RabbitMQ exchange. When nothing fails, both designs behave identically, and four scenarios confirm it for each: one order gets one shipment, thirty parallel orders get thirty shipments, invalid orders leave no trace.
Before: two writes
public async Task<Guid> PlaceOrderAsync(string customer, decimal total)
{
var orderId = Guid.NewGuid();
await using (var command = db.CreateCommand("INSERT INTO orders.orders (id, customer, total) VALUES ($1, $2, $3)"))
{
// ...
await command.ExecuteNonQueryAsync(); // committed
}
// Anything that goes wrong from here on leaves an order nobody will ever be told about.
await publisher.PublishAsync(Message.For(Guid.NewGuid(), new OrderPlaced(orderId, customer, total)));
return orderId;
}
The tests for this version do not check that it works. They pin down what it does when something fails:
[Fact]
public async Task Broker_unavailable_the_caller_gets_an_error_the_order_is_stored_and_never_shipped()
{
await using var shop = await ShopSystem.StartAsync(Design.DualWrite);
shop.Faults.At("publish", () => new BrokerUnavailableException());
await Assert.ThrowsAsync<BrokerUnavailableException>(() => shop.Orders.PlaceOrderAsync("anna@example.com", 100m));
shop.Faults.Clear(); // the broker is back
await ShopSystem.SettleAsync();
Assert.Equal(1, await shop.OrdersAsync()); // the customer was told it failed, and it did not
Assert.Equal(0, await shop.ShipmentsAsync()); // and nothing will ever ship it
}
- Broker unavailable. The caller gets an error. The order is stored anyway. No shipment is ever created.
- The customer retries. They were told it failed, so they order again. Now there are two orders.
- The process dies after the insert. The same loss, without even an error in a log.
- A message is delivered twice, because the consumer did its work and died before acknowledging. Two shipments for one order.
Swapping the two writes does not help. Publishing first and saving second means a failed insert leaves a shipment for an order that does not exist. Wrapping both in a try and catch does not help either: the code that would compensate can fail in exactly the same way.
After: one transaction, then a relay
The fix is to stop writing to two systems. The order service writes the order and the event into the same database, in one transaction, and does not talk to the broker at all:
await using var connection = await db.OpenConnectionAsync();
await using var transaction = await connection.BeginTransactionAsync();
// INSERT INTO orders.orders (id, customer, total) VALUES ...
// INSERT INTO orders.outbox (id, type, payload) VALUES ...
await transaction.CommitAsync(); // both or neither
return orderId;
A separate loop, the relay, reads unpublished rows from the outbox table, publishes them and marks them:
// SKIP LOCKED: a second relay takes the next rows instead of waiting for these.
"SELECT id, type, payload::text FROM orders.outbox WHERE published_at IS NULL
ORDER BY created_at LIMIT $1 FOR UPDATE SKIP LOCKED"
foreach (var message in batch)
{
await publisher.PublishAsync(message); // the outbox row's id travels as the message id
// If the process dies here, the row is still unpublished and goes out again. That is deliberate.
// UPDATE orders.outbox SET published_at = now() WHERE id = $1
}
The comment in the middle is the heart of the pattern. If the relay dies after publishing and before marking, the message is published again. The outbox does not deliver exactly once. It replaces “maybe never” with “at least once”, which is the only one of the two that can be repaired on the other side.
The consumer has to cope with repeats
So the second half of the pattern is on the receiving side. The id of the outbox row travels with the message, and the shipping service records it in the same transaction that creates the shipment:
await using var transaction = await connection.BeginTransactionAsync();
// The record that the message was handled, and the shipment, in one transaction.
await using (var seen = new NpgsqlCommand(
"INSERT INTO shipping.processed_messages (message_id) VALUES ($1) ON CONFLICT DO NOTHING", connection, transaction))
{
seen.Parameters.AddWithValue(message.Id);
if (await seen.ExecuteNonQueryAsync() == 0) return; // handled before: nothing to do, the caller acknowledges
}
// INSERT INTO shipping.shipments (order_id, customer) VALUES ...
await transaction.CommitAsync();
Without this half, the outbox trades a lost-message bug for a double-processing bug. With it, a message that arrives five times is handled once.
What the tests establish
- Broker unavailable: the order is accepted without error, waits in the outbox, and is shipped when the broker returns.
- Process dies before the commit: neither the order nor the event exists.
- Relay dies after publishing: the message is published twice, delivered twice, shipped once.
- Consumer dies before acknowledging: delivered twice, shipped once.
- Three relays at once, 100 orders: 100 shipments, and exactly 100 messages published. Skipping locked rows keeps the relays off each other’s work.
Both designs under the same failures
One test sends 300 orders while four things go wrong at random: the broker refuses 15% of publishes, the process dies after the insert in 3% of requests, the relay dies after publishing in 5%, and the consumer dies before acknowledging in 5%. Then everything is healthy again and the system gets time to catch up.
| Dual write | Outbox | |
|---|---|---|
| Requests that returned an error | 53 of 300 | 0 of 300 |
| Orders stored | 300 | 300 |
| Shipments | 258 | 300 |
| Orders never shipped | 53 | 0 |
| Orders shipped more than once | 10 | 0 |
These are the numbers of one build. For dual write they vary a little from run to run, for the outbox they do not. Note the second row: under dual write every request that returned an error had stored its order. The system told those customers that nothing happened.
What it costs
- Two more tables and a background process that must run, be monitored, and be cleaned up after. Published rows and processed ids grow without limit unless something deletes them.
- Delay. A shipment appears after the relay’s next round, not inside the request. Here the relay looks every 50 ms. Small, and no longer zero.
- Every consumer must be idempotent. The outbox makes repeats a normal event. A consumer that cannot recognise one is not ready for it.
What is verified, and what is not
| Check | Result |
|---|---|
| 4 scenarios without failures, dual write | 4 / 4 |
| The same 4 scenarios, outbox | 4 / 4 |
| 4 failure tests that show what dual write does | 4 / 4 |
| 5 failure tests that show what the outbox guarantees | 5 / 5 |
| 300 orders under mixed failures | table above |
- Crashes are simulated. A crash is an exception thrown at a named point, after which none of the following code runs. No process is killed, no connection is cut.
- The broker is never really down. “Unavailable” is the publisher refusing at a fault point. Timeouts and half-open connections are not covered. The publisher does wait for the broker’s confirmation.
- No ordering. Events of different orders may overtake each other, more so with several relays. Nothing here needs an order.
- No cleanup and no throughput figures. The relay polls. At volume, reading the database log (change data capture) usually replaces polling.
Run it yourself
You need the .NET 10 SDK and Docker for PostgreSQL and RabbitMQ:
docker run -d -e POSTGRES_PASSWORD=local_dev_only -p 54320:5432 postgres:17
docker run -d -p 56720:5672 rabbitmq:4
dotnet test tests/Shop.Tests
When this path fits
Use an outbox wherever a change in a database has to cause something in another system and losing that is not acceptable: orders, payments, anything a customer is told happened. It is usually the first pattern a team needs after extracting a service, because that is the moment a method call becomes a message. Extraction itself is shown in the Strangler Fig case, and the wider picture, including what replaces a distributed transaction, in the monolith to microservices migration guide.
If you need a team for work like this, see our comparison of modernization vendors.