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.

Two sequences of the same request. In the first the invoice is committed and the publish fails: the invoice is saved and no event exists. In the second the event is published and the commit never happens: the event exists and the invoice does not.

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:

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.

The outbox flow: the API writes the invoice and an outbox row in one transaction; a dispatcher reads unsent rows, publishes them to the broker and marks them as sent; the consumer records the message id in its inbox and sends the email in one transaction.

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:

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

  1. A save and a publish are two writes. No ordering of them is safe, because one of them can always succeed alone.
  2. Write the message in the same transaction as the data, and publish from the table. A lost message becomes a late one.
  3. 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


This article is part of Justified Complexity: Building Backends One Decision at a Time.