The invoice that was never sent
On Monday a customer asks where their invoice is. Finance looks it up: INV-1001, issued on Friday at 16:42, 49.90, due in thirty days. It is in the database and on the dashboard, and it is counted in Friday's revenue. The customer never received it.
On Friday at 16:42 the message broker was restarting. It was down for under a minute. The API saved the invoice, tried to announce it, got an error and returned 503. Nobody retried. The service that emails invoices was never told that this one exists.
The logs show one failed request among thousands. Nothing crashed and no data was corrupted. The system simply holds a fact that it never passed on.
This article shows why saving a row and publishing a message can't be made to succeed or fail together, what goes wrong in each order you try, and how an outbox table closes the gap in about sixty lines without a messaging library. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any database with transactions and any broker.
The whole argument in 40 seconds.
The version everyone writes first
Save the invoice, then tell everyone else:
app.MapPost("/invoices", async (IssueInvoiceRequest request, IBroker broker, AppDb db, CancellationToken ct) =>
{
var invoice = Invoice.From(request);
db.Invoices.Add(invoice);
await db.SaveChangesAsync(ct); // committed
await broker.PublishAsync(invoice.ToEvent(), ct);
return Results.Created($"/invoices/{invoice.Id}", invoice.ToResponse());
});
It reads the way the business describes it: issue the invoice, then announce it. It passes every test, because in a test the broker is always there.
Why it fails
The handler writes to two systems, the database and the broker, and there is no transaction that covers both. Between the two lines the process can be stopped by a deployment, the broker can be restarting, or the network can drop the call. The first write then stands alone.
The usual reaction is to swap the order: open a transaction, save, publish, and commit last, so that a failed publish rolls the invoice back.
await using var transaction = await db.Database.BeginTransactionAsync(ct);
db.Invoices.Add(invoice);
await db.SaveChangesAsync(ct); // not committed yet
await broker.PublishAsync(invoice.ToEvent(), ct);
await transaction.CommitAsync(ct); // and if this line never runs?
This fixes the Friday incident and creates its mirror image. If the request dies after the publish and before the commit, the invoice is rolled back and the event is already out. The mailing service emails the customer an invoice that does not exist.
Theophrastus has a character for this in his Characters, the newsmaker: a man who reports a victory that never happened, on the word of a soldier fresh from the battlefield whom nobody can find. Publishing before the commit makes your API that man. It announces something that has not happened yet and may never happen.
| Order | Fails between the two steps | What is left |
|---|---|---|
| Commit, then publish | The publish fails or never runs | An invoice nobody was told about |
| Publish, then commit | The commit fails or never runs | An event for an invoice that does not exist |
Four other fixes come up in every review of this problem, and none of them closes the gap:
- Catch the error and retry the publish. The retry lives in the memory of a process that can be stopped at any moment. It also keeps the customer's request open while the broker is away.
- Return an error and let the client retry. The invoice is already committed, so the retry creates a second one unless the endpoint is idempotent. The first event is still missing.
- Use a distributed transaction. Two-phase commit needs both sides to take part. Most brokers a team is likely to use can't join a transaction with your database.
- Trust the broker's uptime. The broker is one of three things that can fail here. The other two are the network and your own process, and you restart that one on every deployment.
Whichever order you choose, there is a point where one write has happened and the other has not. The only way out is to stop doing two writes.
The fix: write the message down next to the invoice
After its laws were revised, Athens added a rule that Andocides quotes in court: in no circumstances may the magistrates enforce a law that has not been inscribed. The outbox applies the same rule to events. An event that is not written in your database does not exist yet, and only written events are published.
It has three parts.
1. Save the message in the same transaction as the invoice
The message goes into a table in the same database, with the same SaveChangesAsync:
app.MapPost("/invoices", async (IssueInvoiceRequest request, AppDb db, CancellationToken ct) =>
{
var invoice = Invoice.From(request);
db.Invoices.Add(invoice);
db.OutboxMessages.Add(OutboxMessage.From(invoice.ToEvent()));
await db.SaveChangesAsync(ct); // one transaction: both rows or neither
return Results.Created($"/invoices/{invoice.Id}", invoice.ToResponse());
});
The row holds what the broker will need later:
public sealed class OutboxMessage
{
public Guid Id { get; set; } // also the message id the consumer deduplicates on
public required string Type { get; set; }
public required string Payload { get; set; }
public DateTime OccurredAt { get; set; }
public DateTime? ProcessedAt { get; set; } // null until the broker has it
public int Attempts { get; set; }
public string? LastError { get; set; }
}
The request no longer talks to the broker at all. It can't lose an event, because the event is a row that commits with the invoice. It can't announce an invoice that does not exist, because a rollback removes the row too. And it answers 201 while the broker is down, which the first version could not do.
2. A dispatcher moves the rows to the broker
A background service polls the table, publishes what it finds and marks it as sent:
private async Task<int> DispatchBatchAsync(CancellationToken ct)
{
await using var db = await factory.CreateDbContextAsync(ct);
await using var transaction = await db.Database.BeginTransactionAsync(ct);
var batch = await db.OutboxMessages.FromSql($"""
SELECT * FROM outbox_messages
WHERE processed_at IS NULL
ORDER BY id
LIMIT {BatchSize}
FOR UPDATE SKIP LOCKED
""").ToListAsync(ct);
var sent = 0;
foreach (var message in batch)
{
try
{
await broker.PublishAsync(message.Id, message.Type, message.Payload, ct);
}
catch (BrokerUnavailableException ex)
{
message.Attempts++;
message.LastError = ex.Message;
break; // the rows after it would fail too; the next tick tries again
}
message.ProcessedAt = DateTime.UtcNow;
sent++;
}
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return sent;
}
FOR UPDATE locks the rows the query returns until the transaction ends. SKIP LOCKED tells a second dispatcher to pass over rows that are already locked, without waiting for them. That is what lets you run the dispatcher in every instance of the API: each one takes different rows.
A partial index keeps the query cheap however many sent rows the table holds:
CREATE INDEX ix_outbox_messages_unsent ON outbox_messages (id) WHERE processed_at IS NULL;
The dispatcher has the same two writes the endpoint had: publish to the broker, then mark the row. It can fail between them too. The difference is in what the failure costs. The row is still unsent, so the next pass publishes it again. A lost event has become a repeated one.
In Euripides' Iphigenia among the Taurians, Iphigenia hands Pylades a letter, and he asks what becomes of his oath if the ship goes down and the letter with it. She answers by telling him the contents as well: if the tablet survives, it will speak for itself, and if it is lost, he carries the message. The outbox row plays that part. Whatever happens to one attempt at delivery, the message is still there to be sent again.
3. The consumer expects every message twice
Delivery is now at least once, so the consumer has to recognise a message it has already handled. It records the message id in an inbox table, in the same transaction as its own work:
db.InboxMessages.Add(new InboxMessage { MessageId = messageId, ProcessedAt = DateTime.UtcNow });
db.Emails.Add(new SentEmail { Id = Guid.CreateVersion7(), InvoiceId = issued.InvoiceId, Number = issued.Number });
try
{
await db.SaveChangesAsync(ct); // one transaction: the inbox row and the work
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException
{
SqlState: PostgresErrorCodes.UniqueViolation,
ConstraintName: AppDb.InboxKey
})
{
// Already handled. The second delivery is a no-op.
}
The primary key on the message id does the deduplication, for the reason given in A database constraint beats an async validator: a lookup before the insert would let two deliveries through at the same moment.
This is the server side of The duplicate charge seen from a consumer. There the client named the payment with an idempotency key. Here the outbox names the message with its row id, and the id travels with the message so that every delivery of it carries the same name. If the consumer's work is a call to another system, such as a real email provider, that call needs the id as well.
What the outbox asks of you
The table is small, but it comes with decisions:
- Duplicates are part of the contract. Every consumer of an outbox has to be idempotent. Say so in the event's documentation.
- Order is not guaranteed with more than one dispatcher. One dispatcher holds rows 1 to 20 while another publishes rows 21 to 40. In the sample, 19 of 60 events reached the broker after an event that was written later. If consumers need order, run one dispatcher, or split the rows by a key and keep one dispatcher per key.
- Latency. An event waits up to one polling interval, 500 ms in the sample. When that is too slow, PostgreSQL's
LISTENandNOTIFYcan wake the dispatcher early, and change data capture can read the rows from the write-ahead log. Both add moving parts; start with polling. - The dispatcher holds a transaction open while it publishes. The transaction is what keeps the rows locked. It costs one connection per dispatcher, not one per request, but the publish needs a timeout so a stuck broker can't hold the rows indefinitely.
- A message that can never be published blocks the ones behind it. Count the attempts, move the row aside after a limit, and alert.
- Sent rows pile up. Delete or archive them on a schedule. The partial index hides the cost for a while, but the cost is still there.
- The payload is a contract. It is serialised when the invoice is saved and read by another system later, possibly after a deployment. Version it as you would an API.
- One number to watch. The age of the oldest unsent row tells you whether events are flowing. Alert on it.
When you don't need an outbox
The outbox is the general answer. Often a smaller one is enough:
| Situation | Smaller answer |
|---|---|
| The consumer lives in the same database, as in a modular monolith | Write its row in the same transaction, or give it a job table. No broker is involved |
| Losing a message now and then is acceptable, such as a cache invalidation or a metric | Publish after the commit |
| The second write is one call to a system that deduplicates on a key | Pass an idempotency key and retry, as in The duplicate charge |
| A scheduled reconciliation already finds invoices without emails | Let it do the work, if its delay is acceptable |
| You already use a messaging library that ships an outbox, such as MassTransit, Wolverine or NServiceBus | Use theirs, and read what it guarantees |
Reach for the outbox when a state change in your database must reach another system, and a missing or invented message costs real money or trust.
The rule
- A save and a publish are two writes. No ordering of them is safe, because one of them can always succeed alone.
- Write the message in the same transaction as the data, and publish from the table. A lost message becomes a late one.
- Expect every message twice and out of order. At-least-once delivery only works when the consumer deduplicates.
Run it yourself
The companion sample is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It issues the same invoice in three ways: publish after the commit, publish before the commit, and the outbox. The broker is faked inside the sample and keeps its own record of every message it accepted. The consumer writes a row for every email it would send. A small client makes each option fail and counts what is left.
docker compose up -d --build
docker compose run --rm demo
The output on my machine:
1. Publish after commit. The broker is down.
POST /publish-after-commit/invoices 503
INV-1001: invoices 1, outbox 0, events 0, emails 0 <- saved, and the customer never gets it
2. Publish before commit. The request fails between the publish and the commit.
POST /publish-before-commit/invoices 500
INV-1002: invoices 0, outbox 0, events 1, emails 1 <- emailed, and the invoice does not exist
3. Outbox. The broker is down.
POST /invoices 201
INV-1003: invoices 1, outbox 1, events 0, emails 0 <- the invoice is issued; the event waits
the broker comes back
INV-1003: invoices 1, outbox 0, events 1, emails 1 <- delivered
4. Outbox. The dispatcher fails after publishing, before it marks the row as sent.
POST /invoices 201
INV-1004: invoices 1, outbox 0, events 2, emails 1 <- published twice, emailed once
5. Outbox. 60 invoices pile up while the broker is down, then two dispatchers drain them.
POST /invoices 60 x 201
invoices 60, outbox 0, events 60, emails 60, published twice 0
events that reached the broker after a later one: 19 of 60
Steps 1 and 2 are the two failures from the table. Step 3 is the Friday incident with the outbox in place: the customer's request succeeds while the broker is down, and the event leaves when the broker returns. Step 4 is the one to study: the event is published twice and the customer gets one email, because the inbox refused the second delivery. Step 5 shows two dispatchers sharing a backlog without publishing anything twice, and what that costs in ordering. The last number changes from run to run.
The demo has limits. Steps 2 and 4 fail one request or one dispatcher pass; they don't kill the process. The fake broker hands each message to the consumer immediately and never redelivers by itself, and the consumer shares the API's database. A real consumer has its own database, with the inbox in it.
The client checks its own output and exits with code 1 if anything differs. The README explains the switches.
Further reading
- Pattern: Transactional outbox
- PostgreSQL: the locking clause, FOR UPDATE and SKIP LOCKED
- PostgreSQL: partial indexes
- PostgreSQL: NOTIFY
- Debezium: outbox event router
- EF Core: using transactions
This article is part of Justified Complexity: Building Backends One Decision at a Time.