Subscribe

The outbox pattern: reliable events from a database to a queue

Saving an order and then sending an event is two writes, and one of them will fail sooner or later. The outbox pattern writes the event in the same Postgres transaction and lets a relay send it to SQS, with an idempotent consumer at the end. Runnable Go code included.

The outbox pattern: reliable events from a database to a queue

Here is a bug that hides in quite a lot of services. An order is saved to the database, then the code sends an "order placed" message to a queue so other services can react. Two writes to two systems. If the process dies between them, or the queue is down for ten seconds, the order exists and nobody downstream ever hears about it. Swap the order of the writes and you get the opposite bug: an event for an order that was rolled back.

The outbox pattern fixes this with one idea. Write the event into a table in the same database transaction as the order, and let a separate relay move it to the queue later. In this blog we will build it in Go with Postgres, a relay that sends to SQS, and a consumer that is safe to run twice on the same message.

This is an advanced post. You should be comfortable with Go, SQL transactions and what a message queue does. I used Go 1.27.3, Postgres 18.7 (postgres:18-alpine), pgx v5.13.0 and aws-sdk-go-v2 with the SQS client v1.53.0. Everything except the real SQS call ran on my laptop.

Requirements

  • When an order is committed, an order.placed event must reach the queue. Eventually, but always.
  • When an order is rolled back, no event.
  • Events for one order arrive in the order they happened.
  • The order API must not fail just because the queue is slow or down.
  • Consumers must cope with the same message arriving twice. (Every real queue delivers at least once, so this was going to be true anyway.)

Estimates

Say we peak at 50 orders a second and each order makes one event of about 500 bytes. That's 4.3 million outbox rows a day, roughly 2 GB with indexes if you never delete them. So published rows need a cleanup job, I keep a week of them for debugging.

The relay reads 100 rows at a time. SQS takes at most 10 messages per SendMessageBatch call, so that's 10 API calls per relay round. At 50 events a second the relay is idle most of the time.

High-level design

  order API                         relay (1..n copies)              consumers
 +-----------+   one transaction   +------------------+   batches   +-----------+
 | INSERT    | ------------------> | SELECT ... FOR   | ----------> | SQS FIFO  |
 |  orders   |    orders + outbox  | UPDATE SKIP      |             |  queue    |
 | INSERT    |                     | LOCKED, publish, |             +-----+-----+
 |  outbox   |                     | mark published   |                   |
 +-----------+                     +------------------+                   v
                                                              +-----------------------+
                                                              | loyalty service:      |
                                                              | processed_messages +  |
                                                              | side effect, one tx   |
                                                              +-----------------------+

The order API only talks to Postgres. If SQS is down, orders keep working and the outbox just grows for a while.

The tables

CREATE TABLE IF NOT EXISTS orders (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint NOT NULL,
    total_paise bigint NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS outbox (
    id           uuid PRIMARY KEY DEFAULT uuidv7(),  -- Postgres 18+, time ordered
    aggregate_id text NOT NULL,                      -- e.g. the order id
    event_type   text NOT NULL,
    payload      jsonb NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now(),
    published_at timestamptz
);

-- The relay only ever looks at unpublished rows. Keep that index tiny.
CREATE INDEX IF NOT EXISTS outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

uuidv7() is new in Postgres 18. It makes UUIDs that sort by creation time, so ordering by id is roughly the order events were written, and the id doubles as the message id downstream. On older Postgres, generate a UUIDv7 in Go or use a bigint identity.

The partial index only holds unpublished rows. After I loaded 200,000 published rows and 20 unpublished ones, the partial index was 16 kB and the primary key was 6 MB. The relay query never touches the big one. (Partial indexes are covered properly in the Postgres index design post.)

Writing the event with the order

func Add(ctx context.Context, tx pgx.Tx, aggregateID, eventType string, payload any) error {
    b, err := json.Marshal(payload)
    if err != nil {
        return err
    }
    _, err = tx.Exec(ctx,
        `INSERT INTO outbox (aggregate_id, event_type, payload) VALUES ($1, $2, $3)`,
        aggregateID, eventType, b)
    return err
}

func PlaceOrder(ctx context.Context, db *pgxpool.Pool, customerID, totalPaise int64) (int64, error) {
    var orderID int64
    err := pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
        if err := tx.QueryRow(ctx,
            `INSERT INTO orders (customer_id, total_paise) VALUES ($1, $2) RETURNING id`,
            customerID, totalPaise).Scan(&orderID); err != nil {
            return err
        }
        return Add(ctx, tx, fmt.Sprint(orderID), "order.placed", map[string]int64{
            "order_id": orderID, "customer_id": customerID, "total_paise": totalPaise,
        })
    })
    return orderID, err
}

Add takes a pgx.Tx and never a pool. That's on purpose: you can't call it outside a transaction by mistake. One of my tests adds an event and then returns "payment declined" from the transaction function.

outbox_test.go:71: outbox rows after rollback: 0

Order and event live and die together. If you want the background on why that holds, the transactions and isolation levels post goes into it.

The relay

The relay is a loop: lock a batch of unpublished rows, send them, mark them, commit.

func RelayOnce(ctx context.Context, db *pgxpool.Pool, pub Publisher, limit int) (int, error) {
    n := 0
    err := pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
        rows, err := tx.Query(ctx, `
            SELECT id::text, aggregate_id, event_type, payload
            FROM outbox
            WHERE published_at IS NULL
            ORDER BY outbox.id -- not "id": that would sort by the ::text column above
            LIMIT $1
            FOR UPDATE SKIP LOCKED`, limit)
        if err != nil {
            return err
        }
        events, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Event, error) {
            var e Event
            err := r.Scan(&e.ID, &e.AggregateID, &e.Type, &e.Payload)
            return e, err
        })
        if err != nil || len(events) == 0 {
            return err
        }

        if err := pub.Publish(ctx, events); err != nil {
            return fmt.Errorf("publish: %w", err)
        }

        ids := make([]string, len(events))
        for i, e := range events {
            ids[i] = e.ID
        }
        _, err = tx.Exec(ctx,
            `UPDATE outbox SET published_at = now() WHERE id = ANY($1::uuid[])`, ids)
        n = len(events)
        return err
    })
    return n, err
}

FOR UPDATE SKIP LOCKED is the same trick as in Postgres job queues with SKIP LOCKED. Two relays never grab the same rows, so you can run two for availability.

That comment on ORDER BY is there because I actually got it wrong first. I wrote ORDER BY id, and when I ran EXPLAIN ANALYZE against 200,000 rows the plan had an extra step in it:

->  Sort (actual rows=20.00 loops=1)
      Sort Key: ((id)::text)
      ->  Index Scan using outbox_unpublished on outbox (actual rows=20.00 loops=1)

In ORDER BY, a bare name matches an output column first, and my output column id::text is also called id. So Postgres sorted by the text form. For UUIDs the text order happens to match, so the results were right, which is why the tests never caught it. But it sorted every candidate row instead of walking the index. With ORDER BY outbox.id the sort is gone and it's a plain index scan. Small thing. On a big backlog it isn't.

I tested three relays draining 1,000 events together, using in-memory queue in place of SQS:

outbox_test.go:118: published=1000 unique=1000 duplicates=0 unpublished_left=0

And a queue that fails the first batch:

outbox_test.go:133: first relay: publish: queue unavailable
outbox_test.go:135: second relay: published 5, err=<nil>

Nothing lost. The transaction rolled back, the rows stayed unpublished, the next round sent them.

At-least-once, and why the consumer must care

Look at the order of steps again: publish, then UPDATE, then commit. If the relay is killed after SQS accepted the batch but before the commit, those rows are still unpublished and they go out again. You can't close that gap, it's two systems again. The outbox moves the problem from "lost events" to "duplicate events", and duplicates are the easy one to handle.

I simulated it with a publisher that sends the batch and then returns an error, as if the process died.

outbox_test.go:159: messages on the queue: 2
outbox_test.go:166: deliver 01a1f28e-78e6-7c51-9bc6-c3ddecaefe4f applied=true
outbox_test.go:166: deliver 01a1f28e-78e6-7c51-9bc6-c3ddecaefe4f applied=false
outbox_test.go:170: customer 7 points: 125

Same message id twice, points given once. The consumer records the message id in the same transaction as its side effect.

err = pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
    tag, err := tx.Exec(ctx,
        `INSERT INTO processed_messages (message_id) VALUES ($1) ON CONFLICT DO NOTHING`, e.ID)
    if err != nil {
        return err
    }
    if tag.RowsAffected() == 0 {
        return nil // seen before
    }
    applied = true
    _, err = tx.Exec(ctx, `
        INSERT INTO loyalty_points (customer_id, points) VALUES ($1, $2)
        ON CONFLICT (customer_id) DO UPDATE SET points = loyalty_points.points + EXCLUDED.points`,
        p.CustomerID, p.TotalPaise/10000) // 1 point per 100 rupees
    return err
})

If the side effect is a HTTP call to someone else instead of a row in your own database, you can't share a transaction with it. Then pass the message id as their idempotency key. The idempotent payment webhooks post is the same idea from the receiving side.

Sending to SQS

The real publisher uses a FIFO queue. MessageGroupId is the order id, so events for one order stay in order while different orders go in parallel. MessageDeduplicationId is the outbox id, so SQS itself drops a resend of the same event inside its five minute dedupe window. The consumer check above still matters, a relay could be down for longer than five minutes.

for start := 0; start < len(events); start += 10 { // SQS batch limit is 10
    end := min(start+10, len(events))
    var entries []types.SendMessageBatchRequestEntry
    for i, e := range events[start:end] {
        body, err := json.Marshal(e)
        if err != nil {
            return err
        }
        entries = append(entries, types.SendMessageBatchRequestEntry{
            Id:                     aws.String(fmt.Sprint(i)),
            MessageBody:            aws.String(string(body)),
            MessageGroupId:         aws.String(e.AggregateID),
            MessageDeduplicationId: aws.String(e.ID),
        })
    }
    out, err := p.Client.SendMessageBatch(ctx, &sqs.SendMessageBatchInput{
        QueueUrl: aws.String(p.QueueURL),
        Entries:  entries,
    })
    if err != nil {
        return err
    }
    if len(out.Failed) > 0 {
        return fmt.Errorf("%d of %d messages failed, first: %s",
            len(out.Failed), len(entries), aws.ToString(out.Failed[0].Message))
    }
}

SendMessageBatch can partly succeed, and that trips people up: err is nil but out.Failed has entries. I fail the whole batch in that case and let the resend plus dedupe sort it out. To be clear, I built and vetted this part and the relay command, but did not run it against a real AWS account. Queue URL in the example is a placeholder like https://sqs.ap-south-1.amazonaws.com/111122223333/orders.fifo.

Running it

docker run -d --name outbox-pg -e POSTGRES_PASSWORD=dev -p 127.0.0.1:5432:5432 postgres:18-alpine
docker exec outbox-pg createdb -U postgres outbox
DATABASE_URL=postgres://postgres:dev@127.0.0.1:5432/outbox go test -v -count=1 ./outbox

All four tests passed in under two seconds. For cleanup, run this once a day:

DELETE FROM outbox WHERE published_at < now() - interval '7 days';

Trade-offs

See, ordering across relays is the soft spot. With two relays, relay A can take events 1 to 100 and relay B 101 to 200, and B may send first. FIFO message groups keep each order's events in sequence only if the relay sends them in sequence. If strict per-order order matters, run one active relay (an advisory lock is a simple way to elect it) or partition rows by aggregate_id between relays.

Never page through the outbox with WHERE id > last_seen_id. A transaction that started earlier can commit a smaller id after you passed it, and that event is skipped forever. published_at IS NULL doesn't have that problem.

Polling adds latency, up to 500 ms in my loop when the outbox is idle. Postgres LISTEN/NOTIFY can wake the relay sooner. The other route is change data capture, reading the WAL with logical replication (Debezium does this). No polling, but one more system to run, and for a single service I'd start with the table itself.

The outbox also writes every event twice to Postgres (insert, then update) plus the delete later. At 50 a second that is nothing. At 5,000 a second, watch autovacuum on that table, the pg_stat_statements post shows how to spot it.

There we have it: one extra table, a short relay loop, and a consumer that checks a message id before it acts.