›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

The Transactional Outbox in Depth: Dual Writes, Relays, Inboxes and Ordering

November 4, 2025 · 33 min read

Software Architecture, Design Patterns, Distributed Systems, Messaging, Transactional Outbox, C#, Python

Most services do some version of this: save a change, then tell the rest of the system about it. Save the invoice, publish InvoiceIssued. It looks like two lines of code. It is two different systems, a database and a message broker, and nothing makes them commit together.

The transactional outbox is the standard fix. I gave it a few paragraphs in Part 3 of the event sourcing series. This post is the long version: what goes wrong, how to design the table, how to get rows out of it, and the parts that bite later, like ordering, duplicates, poison messages and lag.

The running example is a billing service. It issues invoices and marks them paid. A ledger service downstream listens for those events and writes accounting entries.

Every snippet below was run with .NET 10 (dotnet run file.cs) or Python 3.12. The output shown is the real output. Crashes are simulated on purpose, at fixed points, so every run is the same. Snippets that need a real database or Kafka are labelled not run.

The dual-write problem, failing on purpose

There are only two orders to do the two writes in, and both are wrong:

  • Save, then publish. The process dies after the commit and before the publish. The invoice exists. Nobody downstream ever hears about it.
  • Publish, then save. The publish succeeds. Then the insert fails: a constraint, a deadlock, a timeout. Downstream now knows about an invoice that doesn't exist.

Here are both, with SQLite in memory and a list standing in for the broker.

Python

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE invoices (id TEXT PRIMARY KEY, customer TEXT, amount_cents INTEGER)")
broker: list[dict] = []  # stand-in for Kafka / Service Bus / SQS


class Crash(Exception):
    pass


def issue_invoice_save_then_publish(inv_id: str, crash_between: bool) -> None:
    with db:
        db.execute("INSERT INTO invoices VALUES (?, 'acme', 12000)", (inv_id,))
    if crash_between:
        raise Crash("process killed after COMMIT, before publish")
    broker.append({"type": "InvoiceIssued", "invoice_id": inv_id})


def issue_invoice_publish_then_save(inv_id: str, db_fails: bool) -> None:
    broker.append({"type": "InvoiceIssued", "invoice_id": inv_id})
    with db:
        if db_fails:
            raise Crash("unique constraint / deadlock / timeout on INSERT")
        db.execute("INSERT INTO invoices VALUES (?, 'acme', 12000)", (inv_id,))


for fn, inv_id in [(issue_invoice_save_then_publish, "INV-1"),
                   (issue_invoice_publish_then_save, "INV-2")]:
    try:
        fn(inv_id, True)
    except Crash as e:
        print(f"{fn.__name__}: {e}")

saved = {r[0] for r in db.execute("SELECT id FROM invoices")}
sent = {m["invoice_id"] for m in broker}
print("in database, never announced:", sorted(saved - sent))
print("announced, not in database:  ", sorted(sent - saved))
issue_invoice_save_then_publish: process killed after COMMIT, before publish
issue_invoice_publish_then_save: unique constraint / deadlock / timeout on INSERT
in database, never announced: ['INV-1']
announced, not in database:   ['INV-2']

C#

#:package Microsoft.Data.Sqlite@10.0.13
using Microsoft.Data.Sqlite;

using var db = new SqliteConnection("Data Source=:memory:");
db.Open();
Exec("CREATE TABLE invoices (id TEXT PRIMARY KEY, customer TEXT, amount_cents INTEGER)");
var broker = new List<string>(); // stand-in for Kafka / Service Bus / SQS

void SaveThenPublish(string id)
{
    using (var tx = db.BeginTransaction())
    {
        Exec("INSERT INTO invoices VALUES ($id, 'acme', 12000)", tx, id);
        tx.Commit();
    }
    throw new Exception("process killed after COMMIT, before publish");
    // broker.Add(id);  never reached
}

void PublishThenSave(string id)
{
    broker.Add(id);
    using var tx = db.BeginTransaction();
    throw new Exception("unique constraint / deadlock / timeout on INSERT");
}

foreach (var (name, step, id) in new (string, Action<string>, string)[]
         { ("SaveThenPublish", SaveThenPublish, "INV-1"), ("PublishThenSave", PublishThenSave, "INV-2") })
{
    try { step(id); }
    catch (Exception e) { Console.WriteLine($"{name}: {e.Message}"); }
}

var saved = new List<string>();
using (var cmd = db.CreateCommand())
{
    cmd.CommandText = "SELECT id FROM invoices";
    using var r = cmd.ExecuteReader();
    while (r.Read()) saved.Add(r.GetString(0));
}
Console.WriteLine($"in database, never announced: [{string.Join(", ", saved.Except(broker))}]");
Console.WriteLine($"announced, not in database:   [{string.Join(", ", broker.Except(saved))}]");

void Exec(string sql, SqliteTransaction? tx = null, string? id = null)
{
    using var cmd = db.CreateCommand();
    cmd.Transaction = tx;
    cmd.CommandText = sql;
    if (id is not null) cmd.Parameters.AddWithValue("$id", id);
    cmd.ExecuteNonQuery();
}
SaveThenPublish: process killed after COMMIT, before publish
PublishThenSave: unique constraint / deadlock / timeout on INSERT
in database, never announced: [INV-1]
announced, not in database:   [INV-2]

"Just retry the publish" doesn't help with the first case. The process that would retry is the one that died. And a distributed transaction (two-phase commit across the database and the broker) is rarely on the menu: most cloud brokers don't take part in one, and where they do, you pay for it in locks and in a coordinator that can leave both sides stuck.

The idea in one paragraph

Don't publish in the request. Write the event as a row in an outbox table, in the same local transaction as the business change. The database guarantees both rows commit or neither does. A separate process, the relay, reads committed outbox rows and publishes them. If the relay crashes, the rows are still there, so it picks up where it left off.

That trade is the whole pattern: you swap "might lose the event" for "might send the event twice". Duplicates are a much easier problem, and the consumer section below handles them.

Designing the outbox table

A minimal outbox has an id, a type and a payload. A production one usually needs a few more columns. This is the table the runnable relay below uses:

ColumnWhy it's there
seqInsert order. The relay publishes in this order. An auto-increment key also keeps the index small and append-only.
message_idA unique id that becomes the broker message id. Consumers dedupe on it. Some brokers (Azure Service Bus duplicate detection, for example) can drop a re-send at the broker too.
aggregate_idWhat the event is about (the invoice). Becomes the partition key, so all events for one invoice land in order on one partition.
aggregate_seq1, 2, 3 per invoice. Lets the consumer spot a gap or a stale event. UNIQUE (aggregate_id, aggregate_seq) stops two writers taking the same number.
type, payloadThe event. Include a schema version in the type or the payload; the consumer may be older or newer than you.
created_atFor lag monitoring and cleanup.
claimed_by, lease_untilWhich relay owns the row right now, and until when. More on this below.
attempts, last_error, dead_atPoison handling. A message that can't be sent must not block the table forever.
published_atNull until sent. The relay's main filter is WHERE published_at IS NULL.

Two more things worth storing that the demo skips: headers (the trace context, the correlation id, the tenant), so the consumer's trace joins up with the producer's, and the destination if one relay serves several topics.

Index the pending rows only. In Postgres and SQLite that's a partial index (WHERE published_at IS NULL); in SQL Server, a filtered index. The relay asks "what's pending?" constantly, and the pending set should be tiny compared with the whole table.

Getting rows out: polling vs log tailing

There are two ways to move rows from the table to the broker.

Polling publisher. The relay runs a query every so often: give me pending rows, oldest first. It publishes them and marks them sent. It's simple, it works on any database, and you own all of it.

Transaction log tailing (change data capture). Instead of querying the table, a connector reads the database's own transaction log and turns each committed outbox insert into a message. The application still writes the outbox row in its transaction. The difference is who reads it.

Polling publisherLog tailing / CDC
Moving partsYour relay process and a queryA connector (often Debezium on Kafka Connect) plus log access
LatencyYour poll intervalUsually lower; events stream as they commit
Load on the databaseA query every interval, even when idleReads the log; no extra queries on the table
Marking rows sentYou update published_atNothing to mark; the log position tracks progress
OrderingYour query's ORDER BYCommit order from the log
Operational riskLow; it's your codeThe connector and its log position are now critical infrastructure

The common CDC options:

  • Debezium reads Postgres, MySQL, SQL Server and others, and has an outbox event router built for this pattern. You give it an outbox table with aggregatetype, aggregateid, type and payload columns. It routes each row to a topic per aggregate type and uses the aggregate id as the Kafka message key, which gives you per-aggregate ordering for free.
  • SQL Server CDC captures changes from the log into change tables, which a reader (Debezium's SQL Server connector, or your own job) then polls. It's log-based, but there is a capture job in between, so expect some delay.
  • Postgres logical replication is what Debezium uses on Postgres. A replication slot remembers how far the connector has read. Watch it: if the connector stops, the slot keeps write-ahead log (WAL) on disk until it comes back, and the disk fills.
  • Azure Cosmos DB change feed is the natural fit on Cosmos. There are no multi-document transactions across partitions, so you write the business document and the outbox document in a transactional batch inside the same logical partition, then let a change feed processor publish. The Azure Architecture Center has a full write-up of this (linked at the end).

My default: start with a polling publisher. It's a few dozen lines, you can read all of it, and a one-second poll is fine for most workflows. Move to CDC when the poll load or the latency starts to matter, or when you already run Kafka Connect.

Claiming rows when there's more than one relay

One relay is a single point of failure, so you'll want two or more. Now two relays can read the same pending row and both send it. You need each row claimed by exactly one relay at a time.

On real databases, the tool is a row lock that other readers skip instead of waiting on:

-- Postgres (MySQL 8 has SKIP LOCKED too). Not run.
WITH batch AS (
    SELECT seq FROM outbox
    WHERE published_at IS NULL
      AND (lease_until IS NULL OR lease_until < now())
    ORDER BY seq
    LIMIT 100
    FOR UPDATE SKIP LOCKED      -- rows another relay is claiming are skipped, not waited on
)
UPDATE outbox o
SET claimed_by = 'relay-A', lease_until = now() + interval '30 seconds', attempts = attempts + 1
FROM batch
WHERE o.seq = batch.seq
RETURNING o.seq, o.message_id, o.aggregate_id, o.aggregate_seq, o.type, o.payload;
-- SQL Server. Not run.
WITH batch AS (
    SELECT TOP (100) *
    FROM outbox WITH (UPDLOCK, READPAST, ROWLOCK)   -- READPAST skips locked rows
    WHERE published_at IS NULL
      AND (lease_until IS NULL OR lease_until < SYSUTCDATETIME())
    ORDER BY seq
)
UPDATE batch
SET claimed_by = 'relay-A', lease_until = DATEADD(second, 30, SYSUTCDATETIME()), attempts = attempts + 1
OUTPUT inserted.seq, inserted.message_id, inserted.aggregate_id, inserted.aggregate_seq,
       inserted.type, inserted.payload;

Notice these don't hold the lock while publishing. They claim the rows with a lease, commit, and then publish outside any transaction. The alternative, holding a transaction open across network calls to the broker, ties up a connection and a lock for as long as the broker is slow. With a lease, a relay that dies simply lets its lease expire, and another relay takes the rows.

SQLite has no SKIP LOCKED, but it allows only one writer at a time, so a single UPDATE ... RETURNING is an atomic claim. That's what the runnable version uses. The scenario:

  1. Three invoices are issued, and INV-1 is paid. So INV-1 has two events that must go out in order.
  2. INV-3 carries a payload too big for the broker. That's our poison message.
  3. relay-A claims a batch, sends INV-1#1, and crashes before marking it sent.
  4. relay-B tries to help, but everything is leased by A.
  5. A's lease expires. B takes over, re-sends INV-1#1 (the duplicate), and works through the rest.

Python

import json
import sqlite3
import uuid

db = sqlite3.connect(":memory:", isolation_level=None)  # explicit BEGIN/COMMIT below
db.executescript("""
CREATE TABLE invoices (id TEXT PRIMARY KEY, customer TEXT, amount_cents INTEGER, status TEXT);
CREATE TABLE outbox (
    seq           INTEGER PRIMARY KEY AUTOINCREMENT,  -- global insert order
    message_id    TEXT    NOT NULL UNIQUE,            -- becomes the broker message id
    aggregate_id  TEXT    NOT NULL,                   -- partition key
    aggregate_seq INTEGER NOT NULL,                   -- order within one invoice
    type          TEXT    NOT NULL,
    payload       TEXT    NOT NULL,
    created_at    REAL    NOT NULL,
    claimed_by    TEXT,
    lease_until   REAL,
    attempts      INTEGER NOT NULL DEFAULT 0,
    published_at  REAL,
    dead_at       REAL,
    last_error    TEXT,
    UNIQUE (aggregate_id, aggregate_seq)
);
CREATE INDEX outbox_pending ON outbox (seq) WHERE published_at IS NULL AND dead_at IS NULL;
""")
now = 0.0  # fake clock, in seconds, so every run is identical
LEASE, MAX_ATTEMPTS, MAX_BYTES = 30, 3, 200


def add_event(aggregate_id: str, type_: str, body: dict) -> None:
    # Called INSIDE the caller's transaction. Next per-aggregate sequence number.
    (next_seq,) = db.execute(
        "SELECT COALESCE(MAX(aggregate_seq), 0) + 1 FROM outbox WHERE aggregate_id = ?",
        (aggregate_id,)).fetchone()
    db.execute(
        "INSERT INTO outbox (message_id, aggregate_id, aggregate_seq, type, payload, created_at)"
        " VALUES (?, ?, ?, ?, ?, ?)",
        (str(uuid.uuid4()), aggregate_id, next_seq, type_, json.dumps(body), now))


def issue_invoice(inv_id: str, amount: int, note: str = "") -> None:
    db.execute("BEGIN IMMEDIATE")
    db.execute("INSERT INTO invoices VALUES (?, 'acme', ?, 'issued')", (inv_id, amount))
    add_event(inv_id, "InvoiceIssued", {"invoice_id": inv_id, "amount": amount, "note": note})
    db.execute("COMMIT")  # the invoice and its event commit together, or not at all


def pay_invoice(inv_id: str) -> None:
    db.execute("BEGIN IMMEDIATE")
    db.execute("UPDATE invoices SET status = 'paid' WHERE id = ?", (inv_id,))
    add_event(inv_id, "InvoicePaid", {"invoice_id": inv_id})
    db.execute("COMMIT")


def claim(worker: str, batch: int) -> list[tuple]:
    # One atomic UPDATE: SQLite's stand-in for SELECT ... FOR UPDATE SKIP LOCKED.
    # Only the HEAD unpublished message of each invoice is claimable, so
    # InvoicePaid can never overtake InvoiceIssued for the same invoice.
    rows = db.execute("""
        UPDATE outbox SET claimed_by = ?, lease_until = ?, attempts = attempts + 1
        WHERE seq IN (
            SELECT o.seq FROM outbox o
            WHERE o.published_at IS NULL AND o.dead_at IS NULL
              AND (o.lease_until IS NULL OR o.lease_until < ?)
              AND NOT EXISTS (SELECT 1 FROM outbox e
                              WHERE e.aggregate_id = o.aggregate_id AND e.seq < o.seq
                                AND e.published_at IS NULL AND e.dead_at IS NULL)
            ORDER BY o.seq LIMIT ?)
        RETURNING seq, message_id, aggregate_id, aggregate_seq, type, payload, attempts
        """, (worker, now + LEASE, now, batch)).fetchall()
    return sorted(rows)


broker: list[dict] = []


def publish(msg: dict) -> None:
    if len(msg["body"]) > MAX_BYTES:
        raise ValueError(f"message too large ({len(msg['body'])} bytes)")
    broker.append(msg)


def relay_tick(worker: str, crash_after_publish: bool = False) -> None:
    rows = claim(worker, batch=10)
    print(f"t={now:>4.0f} {worker} claimed {[f'{r[2]}#{r[3]}' for r in rows]}")
    for seq, msg_id, agg, agg_seq, type_, payload, attempts in rows:
        try:
            publish({"message_id": msg_id, "key": agg, "seq": agg_seq, "type": type_, "body": payload})
            if crash_after_publish:  # sent, but the row is not marked yet
                print(f"       {worker} CRASHED after sending {agg}#{agg_seq}; leases held until t={now + LEASE:.0f}")
                return
            db.execute("UPDATE outbox SET published_at = ? WHERE seq = ? AND claimed_by = ?",
                       (now, seq, worker))
        except ValueError as err:
            if attempts >= MAX_ATTEMPTS:  # poison: park it, don't block the table forever
                db.execute("UPDATE outbox SET dead_at = ?, last_error = ? WHERE seq = ?",
                           (now, str(err), seq))
                print(f"       {agg}#{agg_seq} dead-lettered after {attempts} attempts: {err}")
            else:  # back off: retry after 2^attempts seconds instead of the full lease
                db.execute("UPDATE outbox SET lease_until = ?, last_error = ? WHERE seq = ?",
                           (now + 2 ** attempts, str(err), seq))


def lag() -> str:
    pending, oldest = db.execute(
        "SELECT COUNT(*), MIN(created_at) FROM outbox"
        " WHERE published_at IS NULL AND dead_at IS NULL").fetchone()
    dead = db.execute("SELECT COUNT(*) FROM outbox WHERE dead_at IS NOT NULL").fetchone()[0]
    age = 0 if oldest is None else now - oldest
    return f"pending={pending} oldest_age={age:.0f}s dead={dead}"


issue_invoice("INV-1", 12000)
issue_invoice("INV-2", 4500)
pay_invoice("INV-1")                       # INV-1#2 must go out after INV-1#1
issue_invoice("INV-3", 990, note="x" * 300)  # too big for the broker: poison

now = 1
relay_tick("relay-A", crash_after_publish=True)  # sends INV-1#1, dies before marking it
now = 5
relay_tick("relay-B")                      # A's leases block everything; INV-1#2 isn't a head
print("       lag:", lag())
for now in (32, 34, 38):                   # A's leases expire at t=31
    relay_tick("relay-B")
print("       lag:", lag())

now = 7 * 24 * 3600 + 38                   # a week later: retention cleanup
deleted = db.execute("DELETE FROM outbox WHERE published_at < ?", (now - 7 * 24 * 3600,)).rowcount
print(f"cleanup deleted {deleted} published rows; dead letters kept for a human")

ids = [m["message_id"] for m in broker]
print(f"broker got {len(ids)} messages, {len(set(ids))} unique:",
      [f"{m['key']}#{m['seq']}" for m in broker])
t=   1 relay-A claimed ['INV-1#1', 'INV-2#1', 'INV-3#1']
       relay-A CRASHED after sending INV-1#1; leases held until t=31
t=   5 relay-B claimed []
       lag: pending=4 oldest_age=5s dead=0
t=  32 relay-B claimed ['INV-1#1', 'INV-2#1', 'INV-3#1']
t=  34 relay-B claimed ['INV-1#2']
t=  38 relay-B claimed ['INV-3#1']
       INV-3#1 dead-lettered after 3 attempts: message too large (350 bytes)
       lag: pending=0 oldest_age=0s dead=1
cleanup deleted 3 published rows; dead letters kept for a human
broker got 4 messages, 3 unique: ['INV-1#1', 'INV-1#1', 'INV-2#1', 'INV-1#2']

C#

#:package Microsoft.Data.Sqlite@10.0.13
using System.Text.Json.Nodes;
using Microsoft.Data.Sqlite;

using var db = new SqliteConnection("Data Source=:memory:");
db.Open();
Exec("""
    CREATE TABLE invoices (id TEXT PRIMARY KEY, customer TEXT, amount_cents INTEGER, status TEXT);
    CREATE TABLE outbox (
        seq           INTEGER PRIMARY KEY AUTOINCREMENT,
        message_id    TEXT    NOT NULL UNIQUE,
        aggregate_id  TEXT    NOT NULL,
        aggregate_seq INTEGER NOT NULL,
        type          TEXT    NOT NULL,
        payload       TEXT    NOT NULL,
        created_at    REAL    NOT NULL,
        claimed_by    TEXT,
        lease_until   REAL,
        attempts      INTEGER NOT NULL DEFAULT 0,
        published_at  REAL,
        dead_at       REAL,
        last_error    TEXT,
        UNIQUE (aggregate_id, aggregate_seq)
    );
    CREATE INDEX outbox_pending ON outbox (seq) WHERE published_at IS NULL AND dead_at IS NULL;
    """);

double now = 0;  // fake clock
const int Lease = 30, MaxAttempts = 3, MaxBytes = 200;
var broker = new List<Msg>();

IssueInvoice("INV-1", 12000);
IssueInvoice("INV-2", 4500);
PayInvoice("INV-1");
IssueInvoice("INV-3", 990, note: new string('x', 300));  // poison

now = 1; RelayTick("relay-A", crashAfterPublish: true);
now = 5; RelayTick("relay-B");
Console.WriteLine($"       lag: {Lag()}");
foreach (var t in new double[] { 32, 34, 38 }) { now = t; RelayTick("relay-B"); }
Console.WriteLine($"       lag: {Lag()}");

now = 7 * 24 * 3600 + 38;
var deleted = Exec("DELETE FROM outbox WHERE published_at < $cutoff", null, ("$cutoff", now - 7 * 24 * 3600));
Console.WriteLine($"cleanup deleted {deleted} published rows; dead letters kept for a human");
Console.WriteLine($"broker got {broker.Count} messages, {broker.Select(m => m.MessageId).Distinct().Count()} unique: " +
                  $"[{string.Join(", ", broker.Select(m => $"{m.Key}#{m.Seq}"))}]");

void IssueInvoice(string id, int amount, string note = "")
{
    using var tx = db.BeginTransaction();
    Exec("INSERT INTO invoices VALUES ($id, 'acme', $amt, 'issued')", tx, ("$id", id), ("$amt", amount));
    AddEvent(tx, id, "InvoiceIssued", new() { ["invoiceId"] = id, ["amount"] = amount, ["note"] = note });
    tx.Commit();  // invoice and event commit together, or not at all
}

void PayInvoice(string id)
{
    using var tx = db.BeginTransaction();
    Exec("UPDATE invoices SET status = 'paid' WHERE id = $id", tx, ("$id", id));
    AddEvent(tx, id, "InvoicePaid", new() { ["invoiceId"] = id });
    tx.Commit();
}

void AddEvent(SqliteTransaction tx, string aggregateId, string type, JsonObject body) =>
    Exec("""
        INSERT INTO outbox (message_id, aggregate_id, aggregate_seq, type, payload, created_at)
        VALUES ($mid, $agg,
                (SELECT COALESCE(MAX(aggregate_seq), 0) + 1 FROM outbox WHERE aggregate_id = $agg),
                $type, $payload, $now)
        """, tx, ("$mid", Guid.NewGuid().ToString()), ("$agg", aggregateId), ("$type", type),
        ("$payload", body.ToJsonString()), ("$now", now));

List<Claimed> Claim(string worker, int batch)
{
    // One atomic UPDATE: the SQLite stand-in for SELECT ... FOR UPDATE SKIP LOCKED.
    // Only the head unpublished message per invoice is claimable (per-aggregate order).
    using var cmd = db.CreateCommand();
    cmd.CommandText = """
        UPDATE outbox SET claimed_by = $w, lease_until = $until, attempts = attempts + 1
        WHERE seq IN (
            SELECT o.seq FROM outbox o
            WHERE o.published_at IS NULL AND o.dead_at IS NULL
              AND (o.lease_until IS NULL OR o.lease_until < $now)
              AND NOT EXISTS (SELECT 1 FROM outbox e
                              WHERE e.aggregate_id = o.aggregate_id AND e.seq < o.seq
                                AND e.published_at IS NULL AND e.dead_at IS NULL)
            ORDER BY o.seq LIMIT $batch)
        RETURNING seq, message_id, aggregate_id, aggregate_seq, type, payload, attempts
        """;
    cmd.Parameters.AddWithValue("$w", worker);
    cmd.Parameters.AddWithValue("$until", now + Lease);
    cmd.Parameters.AddWithValue("$now", now);
    cmd.Parameters.AddWithValue("$batch", batch);
    var rows = new List<Claimed>();
    using var r = cmd.ExecuteReader();
    while (r.Read())
        rows.Add(new(r.GetInt64(0), r.GetString(1), r.GetString(2), r.GetInt32(3), r.GetString(4), r.GetString(5), r.GetInt32(6)));
    return rows.OrderBy(x => x.Seq).ToList();
}

void Publish(Msg m)
{
    if (m.Body.Length > MaxBytes) throw new InvalidOperationException($"message too large ({m.Body.Length} bytes)");
    broker.Add(m);
}

void RelayTick(string worker, bool crashAfterPublish = false)
{
    var rows = Claim(worker, 10);
    Console.WriteLine($"t={now,4} {worker} claimed [{string.Join(", ", rows.Select(x => $"{x.Agg}#{x.AggSeq}"))}]");
    foreach (var c in rows)
    {
        try
        {
            Publish(new Msg(c.MessageId, c.Agg, c.AggSeq, c.Type, c.Payload));
            if (crashAfterPublish)
            {
                Console.WriteLine($"       {worker} CRASHED after sending {c.Agg}#{c.AggSeq}; leases held until t={now + Lease}");
                return;
            }
            Exec("UPDATE outbox SET published_at = $now WHERE seq = $seq AND claimed_by = $w", null,
                 ("$now", now), ("$seq", c.Seq), ("$w", worker));
        }
        catch (InvalidOperationException e) when (c.Attempts >= MaxAttempts)
        {
            Exec("UPDATE outbox SET dead_at = $now, last_error = $err WHERE seq = $seq", null,
                 ("$now", now), ("$err", e.Message), ("$seq", c.Seq));
            Console.WriteLine($"       {c.Agg}#{c.AggSeq} dead-lettered after {c.Attempts} attempts: {e.Message}");
        }
        catch (InvalidOperationException e)
        {
            Exec("UPDATE outbox SET lease_until = $retry, last_error = $err WHERE seq = $seq", null,
                 ("$retry", now + Math.Pow(2, c.Attempts)), ("$err", e.Message), ("$seq", c.Seq));
        }
    }
}

string Lag()
{
    using var cmd = db.CreateCommand();
    cmd.CommandText = """
        SELECT (SELECT COUNT(*) FROM outbox WHERE published_at IS NULL AND dead_at IS NULL),
               (SELECT MIN(created_at) FROM outbox WHERE published_at IS NULL AND dead_at IS NULL),
               (SELECT COUNT(*) FROM outbox WHERE dead_at IS NOT NULL)
        """;
    using var r = cmd.ExecuteReader();
    r.Read();
    var age = r.IsDBNull(1) ? 0 : now - r.GetDouble(1);
    return $"pending={r.GetInt64(0)} oldest_age={age}s dead={r.GetInt64(2)}";
}

int Exec(string sql, SqliteTransaction? tx = null, params (string Name, object Value)[] args)
{
    using var cmd = db.CreateCommand();
    cmd.Transaction = tx;
    cmd.CommandText = sql;
    foreach (var (name, value) in args) cmd.Parameters.AddWithValue(name, value);
    return cmd.ExecuteNonQuery();
}

record Claimed(long Seq, string MessageId, string Agg, int AggSeq, string Type, string Payload, int Attempts);
record Msg(string MessageId, string Key, int Seq, string Type, string Body);
t=   1 relay-A claimed [INV-1#1, INV-2#1, INV-3#1]
       relay-A CRASHED after sending INV-1#1; leases held until t=31
t=   5 relay-B claimed []
       lag: pending=4 oldest_age=5s dead=0
t=  32 relay-B claimed [INV-1#1, INV-2#1, INV-3#1]
t=  34 relay-B claimed [INV-1#2]
t=  38 relay-B claimed [INV-3#1]
       INV-3#1 dead-lettered after 3 attempts: message too large (344 bytes)
       lag: pending=0 oldest_age=0s dead=1
cleanup deleted 3 published rows; dead letters kept for a human
broker got 4 messages, 3 unique: [INV-1#1, INV-1#1, INV-2#1, INV-1#2]

(The C# payload is 344 bytes and the Python one 350 because json.dumps puts a space after each colon and comma. The point is the same.)

Read the output from the top:

  • t=1. A claims three rows. It doesn't claim INV-1#2, because INV-1#1 is still pending. More on that in the next section.
  • t=5. B claims nothing. A's leases are still valid, even though A is dead. That's the cost of leases: a crashed relay delays its rows by up to the lease length. Keep leases short (tens of seconds) and publishing fast.
  • t=32. B takes over and sends INV-1#1 again. The broker now has it twice, with the same message_id.
  • t=34. Only now is INV-1#2 claimable.
  • t=38. INV-3 fails its third attempt and is dead-lettered instead of blocking the table.

Ordering

A single relay that publishes in seq order preserves order. Several relays, retries and backoff all break it: a retried message can land after a newer one. If consumers care about order (and "paid before issued" is a real bug), you need three things:

  1. A per-aggregate sequence number in the event, so the consumer can tell if something is missing or stale. That's aggregate_seq.
  2. Only publish the head of each aggregate. The claim query above has a NOT EXISTS that makes a message claimable only when no earlier message for the same invoice is still pending. It costs some throughput (one in-flight message per invoice), and buys strict per-invoice order. Different invoices still go out in parallel.
  3. A partition key on the broker, so the broker keeps order too: the Kafka message key, a Service Bus session id, an SQS FIFO message group id. Use the aggregate id. The consumer must then process one key at a time; most clients do this per partition or session for you.

Note what you don't get: a global order across all invoices. You almost never need it, and it would force a single relay and a single consumer.

Poison messages and backoff

Some messages will never send. The payload is too large, the topic doesn't exist, or the message crashes the serializer every time. Without a limit, the relay retries it forever, and with head-of-line ordering it also blocks every later event for that aggregate.

The relay above does three things:

  • It counts attempts at claim time. So a message that crashes the relay itself still burns an attempt, which is exactly the message you most want to stop retrying.
  • It backs off with lease_until = now + 2^attempts instead of retrying on the next poll.
  • It parks the message after MAX_ATTEMPTS: sets dead_at, keeps last_error, and moves on.

Dead rows need a human. Alert on any dead row, show them on a dashboard, and give someone a way to fix and requeue (clear dead_at, reset attempts). And decide up front what happens to later events for that aggregate. Here they stop being blocked, because the NOT EXISTS ignores dead rows. That's the right choice for some domains and the wrong one for others.

At-least-once means the consumer needs an inbox

The broker got INV-1#1 twice. That's the normal behaviour of this pattern, not a bug, and brokers redeliver on their own too (a consumer that processes a message and dies before acking gets it again). So the consumer has to be idempotent: processing a message twice must have the same effect as processing it once.

Some operations are naturally idempotent ("set status to paid"). Most aren't ("add a ledger entry"). For those, use an inbox: a table of message ids you've already handled, written in the same transaction as the side effect. If the side effect commits, so does the inbox row. If you crash before the commit, neither exists and the redelivery is processed normally.

The ledger consumer below gets what an at-least-once broker might actually deliver: INV-1's events out of order, the relay's duplicate of m-1, and one message whose ack is lost after the commit.

Python

import sqlite3
from collections import deque

db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""
CREATE TABLE inbox (message_id TEXT PRIMARY KEY, handled_at TEXT DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE positions (aggregate_id TEXT PRIMARY KEY, last_seq INTEGER NOT NULL);
CREATE TABLE ledger (invoice_id TEXT, entry TEXT);
""")


class NotYet(Exception):
    """A gap in the sequence: don't ack, let the broker redeliver later."""


def handle(msg: dict, crash_before_ack: bool = False) -> str:
    db.execute("BEGIN IMMEDIATE")
    try:
        # 1. Inbox: the message id is the primary key, so a duplicate inserts nothing.
        if db.execute("INSERT OR IGNORE INTO inbox (message_id) VALUES (?)",
                      (msg["id"],)).rowcount == 0:
            db.execute("ROLLBACK")
            return "duplicate, skipped"
        # 2. Order: the outbox stamped a per-invoice sequence number.
        row = db.execute("SELECT last_seq FROM positions WHERE aggregate_id = ?",
                         (msg["key"],)).fetchone()
        last = row[0] if row else 0
        if msg["seq"] > last + 1:
            raise NotYet(f"have #{last}, got #{msg['seq']}")
        # 3. The side effect, in the SAME transaction as the inbox row.
        db.execute("INSERT INTO ledger VALUES (?, ?)", (msg["key"], msg["type"]))
        db.execute("INSERT INTO positions VALUES (?, ?) ON CONFLICT (aggregate_id)"
                   " DO UPDATE SET last_seq = excluded.last_seq", (msg["key"], msg["seq"]))
        db.execute("COMMIT")
    except NotYet:
        db.execute("ROLLBACK")  # removes the inbox row too, so the retry isn't a "duplicate"
        raise
    if crash_before_ack:
        raise ConnectionError("committed, but the ack never reached the broker")
    return "applied"


issued = {"id": "m-1", "key": "INV-1", "seq": 1, "type": "InvoiceIssued"}
paid = {"id": "m-2", "key": "INV-1", "seq": 2, "type": "InvoicePaid"}
other = {"id": "m-3", "key": "INV-2", "seq": 1, "type": "InvoiceIssued"}

# What an at-least-once broker might actually hand us: out of order, plus the
# relay's duplicate of m-1 (same message id, because the outbox row id was reused).
queue = deque([paid, issued, other, dict(issued)])
crash_once = {"m-3"}
while queue:
    msg = queue.popleft()
    try:
        result = handle(msg, crash_before_ack=msg["id"] in crash_once)
    except (NotYet, ConnectionError) as err:
        crash_once.discard(msg["id"])
        queue.append(msg)  # not acked: the broker redelivers it later
        result = f"not acked ({err}), redelivered later"
    print(f"{msg['id']} {msg['key']}#{msg['seq']} {msg['type']:<14} -> {result}")

print("ledger:", db.execute("SELECT invoice_id, entry FROM ledger ORDER BY rowid").fetchall())
m-2 INV-1#2 InvoicePaid    -> not acked (have #0, got #2), redelivered later
m-1 INV-1#1 InvoiceIssued  -> applied
m-3 INV-2#1 InvoiceIssued  -> not acked (committed, but the ack never reached the broker), redelivered later
m-1 INV-1#1 InvoiceIssued  -> duplicate, skipped
m-2 INV-1#2 InvoicePaid    -> applied
m-3 INV-2#1 InvoiceIssued  -> duplicate, skipped
ledger: [('INV-1', 'InvoiceIssued'), ('INV-2', 'InvoiceIssued'), ('INV-1', 'InvoicePaid')]

C#

#:package Microsoft.Data.Sqlite@10.0.13
using Microsoft.Data.Sqlite;

using var db = new SqliteConnection("Data Source=:memory:");
db.Open();
Exec(null, """
    CREATE TABLE inbox (message_id TEXT PRIMARY KEY, handled_at TEXT DEFAULT CURRENT_TIMESTAMP);
    CREATE TABLE positions (aggregate_id TEXT PRIMARY KEY, last_seq INTEGER NOT NULL);
    CREATE TABLE ledger (invoice_id TEXT, entry TEXT);
    """);

var issued = new Msg("m-1", "INV-1", 1, "InvoiceIssued");
var paid   = new Msg("m-2", "INV-1", 2, "InvoicePaid");
var other  = new Msg("m-3", "INV-2", 1, "InvoiceIssued");

// Out of order, plus the relay's duplicate of m-1 (same message id).
var queue = new Queue<Msg>([paid, issued, other, issued with { }]);
var crashOnce = new HashSet<string> { "m-3" };
while (queue.TryDequeue(out var msg))
{
    string result;
    try { result = Handle(msg, crashBeforeAck: crashOnce.Contains(msg.Id)); }
    catch (Exception e) when (e is NotYetException or IOException)
    {
        crashOnce.Remove(msg.Id);
        queue.Enqueue(msg);  // not acked: the broker redelivers it later
        result = $"not acked ({e.Message}), redelivered later";
    }
    Console.WriteLine($"{msg.Id} {msg.Key}#{msg.Seq} {msg.Type,-14} -> {result}");
}

using (var cmd = db.CreateCommand())
{
    cmd.CommandText = "SELECT invoice_id, entry FROM ledger ORDER BY rowid";
    using var r = cmd.ExecuteReader();
    var rows = new List<string>();
    while (r.Read()) rows.Add($"({r.GetString(0)}, {r.GetString(1)})");
    Console.WriteLine($"ledger: [{string.Join(", ", rows)}]");
}

string Handle(Msg msg, bool crashBeforeAck)
{
    using (var tx = db.BeginTransaction())
    {
        // 1. Inbox: a duplicate message id inserts nothing.
        if (Exec(tx, "INSERT OR IGNORE INTO inbox (message_id) VALUES ($id)", ("$id", msg.Id)) == 0)
            return "duplicate, skipped";  // disposing tx rolls it back

        // 2. Order: per-invoice sequence stamped by the outbox.
        using var q = db.CreateCommand();
        q.Transaction = tx;
        q.CommandText = "SELECT last_seq FROM positions WHERE aggregate_id = $k";
        q.Parameters.AddWithValue("$k", msg.Key);
        var last = Convert.ToInt32(q.ExecuteScalar() ?? 0);
        if (msg.Seq > last + 1)
            throw new NotYetException($"have #{last}, got #{msg.Seq}");  // rollback drops the inbox row

        // 3. Side effect in the SAME transaction as the inbox row.
        Exec(tx, "INSERT INTO ledger VALUES ($k, $t)", ("$k", msg.Key), ("$t", msg.Type));
        Exec(tx, """
            INSERT INTO positions VALUES ($k, $s)
            ON CONFLICT (aggregate_id) DO UPDATE SET last_seq = excluded.last_seq
            """, ("$k", msg.Key), ("$s", msg.Seq));
        tx.Commit();
    }
    if (crashBeforeAck) throw new IOException("committed, but the ack never reached the broker");
    return "applied";
}

int Exec(SqliteTransaction? tx, string sql, params (string Name, object Value)[] args)
{
    using var cmd = db.CreateCommand();
    cmd.Transaction = tx;
    cmd.CommandText = sql;
    foreach (var (name, value) in args) cmd.Parameters.AddWithValue(name, value);
    return cmd.ExecuteNonQuery();
}

record Msg(string Id, string Key, int Seq, string Type);
class NotYetException(string message) : Exception(message);
m-2 INV-1#2 InvoicePaid    -> not acked (have #0, got #2), redelivered later
m-1 INV-1#1 InvoiceIssued  -> applied
m-3 INV-2#1 InvoiceIssued  -> not acked (committed, but the ack never reached the broker), redelivered later
m-1 INV-1#1 InvoiceIssued  -> duplicate, skipped
m-2 INV-1#2 InvoicePaid    -> applied
m-3 INV-2#1 InvoiceIssued  -> duplicate, skipped
ledger: [(INV-1, InvoiceIssued), (INV-2, InvoiceIssued), (INV-1, InvoicePaid)]

Each line in the output is one rule:

  • m-2 first. The sequence check sees a gap (have #0, got #2) and refuses to ack. The rollback removes the inbox row as well, so the redelivery isn't mistaken for a duplicate.
  • m-3. Committed, then the ack was lost. The broker redelivers it, and the inbox says "already done".
  • The second m-1 is the relay's duplicate, same message id, skipped.
  • The ledger has exactly three entries, and INV-1's are in order.

Two practical notes. First, keep inbox rows longer than the longest time a duplicate can arrive: the broker's redelivery window plus the outbox lease plus any manual replay you might do. Days, not minutes. Second, the inbox only works if the side effect lives in the same database as the inbox. If the consumer calls an external API, pass the message id as that API's idempotency key instead.

Cleanup and retention

The outbox grows forever unless you trim it. A published row has done its job.

  • Delete published rows on a schedule, in small batches (DELETE ... WHERE published_at < cutoff with a limit), so one big delete doesn't lock the table. The relay demo keeps a week.
  • On Postgres at high volume, partition the outbox by day and drop old partitions. Dropping a partition is instant; deleting millions of rows is not.
  • With CDC, the connector reads inserts from the log, not the table, so you can delete rows soon after they're written. Debezium's outbox router ignores DELETE operations on the outbox table, so the cleanup doesn't produce extra messages.
  • Keep dead rows until a person resolves them.

Monitoring outbox lag

The outbox fails quietly. The relay stops, the API keeps returning 200, and events pile up. Watch these:

  • Age of the oldest pending row. The single best alert. "Oldest unpublished event is 5 minutes old" means something is broken, whatever the cause. The demo's lag() prints it.
  • Pending count, and insert rate vs publish rate. A growing gap means the relay can't keep up.
  • Dead-lettered count. Alert on anything above zero.
  • Relay heartbeat. Each relay logs or reports each tick, so you can tell "idle" from "dead".
  • For CDC: connector lag, and on Postgres the WAL retained by the replication slot.

Put the outbox message_id and the trace id in your logs on both sides, so you can follow one event from the API call to the consumer.

Libraries: don't hand-roll this in C#

Writing your own relay is a good way to understand the pattern. In .NET you rarely need to ship your own, because the main messaging libraries include an outbox:

  • MassTransit has a transactional outbox for Entity Framework Core and MongoDB. The bus outbox stores messages you publish from a controller in your DbContext and delivers them after SaveChanges. The consumer outbox adds an inbox (InboxState) that dedupes incoming messages.
  • NServiceBus has the Outbox feature. Turn it on per endpoint and it stores outgoing messages and handled message ids in the same transaction as your handler's data, giving you outbox and inbox together.
  • Wolverine has a durable inbox and outbox backed by Postgres, SQL Server, Marten or EF Core.

In Python there isn't one dominant library. The common choices are:

  • Hand-rolled with SQLAlchemy. The pattern is small: add the outbox row in the same session as the business change, and run a relay like the one above. Not run, but this is the shape:
# Not run: needs SQLAlchemy and a database.
with Session(engine) as session, session.begin():
    session.add(Invoice(id=inv_id, customer=customer, amount_cents=amount))
    session.add(OutboxMessage(message_id=str(uuid4()), aggregate_id=inv_id, aggregate_seq=1,
                              type="InvoiceIssued", payload=json.dumps(body)))
# session.begin() commits both rows together, or rolls both back.
  • Debezium reading the outbox table. Your Python service only writes rows; the connector publishes. This is language-neutral, which is handy when services in several languages share the same pattern.

When not to use it

The outbox adds a table, a background process and a duplicate-handling consumer. Skip it when:

  • Losing the event is acceptable. Cache warming, "someone viewed this page" analytics. Fire and forget.
  • You already store events as the source of truth. With event sourcing, the event store is the outbox: subscribe to it and publish from it.
  • The "message" never leaves your database. If the consumer is a background job in the same service, a jobs table is enough. (That's an outbox with one reader, so you're half-way there anyway.)
  • The queue lives in the same database. If the queue is a table in the same database as your data, one transaction already covers both writes.
  • The caller needs an answer now. The outbox is asynchronous by design. If the user must see the downstream result in the same request, you need a synchronous call (and its failure modes) instead.

Check yourself: questions and answers

1. Why not just publish after the commit and retry if the publish fails?

Because the failure that matters is the process dying between the commit and the publish. There's nobody left to retry, and nothing durable that says a publish was owed. The outbox row is that durable record.

2. Does the outbox give exactly-once delivery?

No. It gives at-least-once delivery: a relay can always crash after sending and before marking. Combine it with an idempotent consumer (an inbox) and you get exactly-once effects, which is what you actually wanted.

3. Polling publisher or change data capture?

Polling is simpler and runs on any database; you pay with poll queries and poll-interval latency. CDC streams from the transaction log with low latency and no table queries, but the connector and its log position become infrastructure you must run and watch. I'd start with polling.

4. Why must the inbox row be written in the same transaction as the side effect?

If they're separate, a crash between them either applies the effect without recording it (so the redelivery applies it again) or records it without applying it (so the effect is lost). One transaction makes them succeed or fail together.

5. Two relays are running. How do you stop them sending the same row at the same time, and how do you keep order?

Claim rows atomically with a short lease: FOR UPDATE SKIP LOCKED on Postgres, UPDLOCK, READPAST on SQL Server. For order, stamp a per-aggregate sequence, only claim the earliest pending message per aggregate, and use the aggregate id as the broker's partition key.

6. What's the first metric you'd alert on?

The age of the oldest unpublished row. It catches a dead relay, a broker outage and a stuck poison message with one number.

7. What happens on Postgres if your Debezium connector is down for a day?

The replication slot holds on to every WAL segment since the connector's last position, so disk usage grows until it comes back or the slot is dropped. Monitor slot lag, and cap retained WAL (max_slot_wal_keep_size) if losing the slot is better than filling the disk.

8. When would you not use an outbox?

When the event can be lost, when you already have an event store, when the queue lives in the same database as the data, or when the caller needs a synchronous answer.

Further reading

  • Chris Richardson, microservices.io: Transactional outbox, Polling publisher, Transaction log tailing and Idempotent consumer
  • Debezium documentation: Outbox event router
  • Azure Architecture Center: Transactional Outbox pattern with Azure Cosmos DB
  • Microsoft Learn: Change feed in Azure Cosmos DB, About change data capture (SQL Server) and Service Bus duplicate detection
  • PostgreSQL documentation: SELECT, the locking clause and SKIP LOCKED and Logical replication
  • Library docs: MassTransit transactional outbox, NServiceBus Outbox and Wolverine durable messaging
  • My 2025 series: Part 3, saga orchestration, where the outbox first appears, and Part 5, key concepts
← Previous

Sagas in Depth: Pivots, Compensations, Isolation and the Failure Modes Nobody Draws

Next →

Android Testing Essentials

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.