Database and broker behaviour is from the PostgreSQL 18, Debezium and Apache Kafka 4.2 documentation, checked on 14 November 2026. The code is a sketch for PostgreSQL with psycopg 3; adapt the locking clause for other databases.
The outbox pattern (or transactional outbox) makes "save the payment" and "announce the payment" a single atomic step. Instead of writing to your database and then publishing to a queue, you write the event into an outbox table in the same database transaction as the payment change. A separate relay reads the table and publishes to the broker. If the transaction commits, the event exists and will be sent; if it rolls back, neither happened (microservices.io).
The bug it fixes: the dual write
Every payment system has code shaped like this: update the payments row, commit, then publish("payment.succeeded"). That's two writes to two systems with no transaction spanning them, and each ordering has its own way to fail:
| Order | Crash or error between the two writes | What you get |
|---|---|---|
| Commit, then publish | Process dies, broker is down, publish times out | Payment succeeded, nobody downstream knows: no fulfilment, no ledger entry, no receipt |
| Publish, then commit | Commit fails, deadlock, constraint violation | Downstream ships an order for a payment your database never recorded |
| Publish inside the open transaction | Transaction rolls back after the publish | Same as above: a message about a payment that doesn't exist |
Retrying the publish doesn't fix the first row, because the process that would retry is the one that died. Two-phase commit across the database and the broker would, but plenty of brokers don't support it and you don't want your checkout coupled to both being up (microservices.io).
The outbox table
CREATE TABLE outbox (
id uuid PRIMARY KEY, -- the event ID consumers dedupe on
aggregate_id uuid NOT NULL, -- the payment it belongs to
event_type text NOT NULL, -- e.g. payment.succeeded
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz -- NULL until the relay sends it
);
-- The relay only ever looks for unpublished rows, oldest first.
CREATE INDEX outbox_unpublished ON outbox (created_at) WHERE published_at IS NULL;
Writing the event with the payment
The whole trick is that the second INSERT is inside the same conn.transaction() as the UPDATE. This uses psycopg 3 against PostgreSQL:
import uuid
import psycopg
from psycopg.types.json import Jsonb
def record_payment_succeeded(conn, payment_id, amount_minor, currency, psp_ref):
"""Update the payment and write its event in ONE transaction.
Both rows commit or neither does. There is no moment where the payment
says succeeded and the event doesn't exist, or the other way round.
"""
event_id = uuid.uuid4()
with conn.transaction():
updated = conn.execute(
"UPDATE payments SET status = 'succeeded', psp_ref = %s"
" WHERE id = %s AND status = 'processing'",
(psp_ref, payment_id),
).rowcount
if updated == 0:
return None # already succeeded (or not ours): no second event
conn.execute(
"INSERT INTO outbox (id, aggregate_id, event_type, payload)"
" VALUES (%s, %s, %s, %s)",
(event_id, payment_id, "payment.succeeded", Jsonb({
"event_id": str(event_id),
"payment_id": str(payment_id),
"amount_minor": amount_minor, # integer cents, never a float
"currency": currency,
})),
)
return event_id
The AND status = 'processing' guard matters too: a duplicate webhook that tries to mark the payment succeeded a second time updates no row, so it writes no second event.
The relay: polling with SKIP LOCKED
A loop that claims a batch of unpublished rows, publishes them and marks them sent. FOR UPDATE SKIP LOCKED lets you run several relay workers without them fighting over the same rows. PostgreSQL's docs describe exactly this use: skipping locked rows "provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table" (PostgreSQL).
import time
BATCH_SIZE = 100 # tune under load; nothing magic about 100
def relay_once(conn, publish):
"""Publish one batch of unsent events. Returns how many it sent.
publish(key, event_type, payload) must not return until the broker has
acknowledged the message. If it raises, the transaction rolls back and
the whole batch is retried, including rows already sent: at-least-once.
"""
with conn.transaction():
rows = conn.execute(
"SELECT id, event_type, payload FROM outbox"
" WHERE published_at IS NULL"
" ORDER BY created_at"
" LIMIT %s"
" FOR UPDATE SKIP LOCKED", # other relay workers skip these rows
(BATCH_SIZE,),
).fetchall()
for event_id, event_type, payload in rows:
publish(key=str(event_id), event_type=event_type, payload=payload)
if rows:
conn.execute(
"UPDATE outbox SET published_at = now() WHERE id = ANY(%s)",
([row[0] for row in rows],),
)
return len(rows)
def run_relay(conn, publish, idle_sleep=0.5):
while True:
if relay_once(conn, publish) == 0:
time.sleep(idle_sleep)
Three things to know about this loop:
- It sends duplicates. If the broker accepts the message and the relay dies before its
UPDATEcommits, the next run sends it again. That's not a bug in the code; it's the guarantee. Microservices.io says it plainly: the relay might publish a message more than once, so "a message consumer must be idempotent" (microservices.io). - Several workers trade away ordering. With
SKIP LOCKEDand two workers, event 2 can be published before event 1. If consumers need the events for one payment in order, run one relay, or partition byaggregate_idso each payment's events go through one worker and one broker partition. - Rows stay locked while you publish. Keep batches small and give
publisha timeout, so one slow broker call doesn't hold a batch hostage. - The table grows. Delete or archive published rows on a schedule. Keep them long enough to answer "did we ever send that?"
The alternative relay: change data capture
Instead of polling, tail the database's transaction log. Debezium's Outbox Event Router reads inserts into an outbox table (id, aggregatetype, aggregateid, type, payload), routes each to a topic named from aggregatetype, keys it by aggregateid, and passes the id along, which you "can use ... to remove duplicate messages" (Debezium). No polling load and no published_at column, at the cost of running Kafka Connect and Debezium. Polling is the right first version; CDC is what you move to when the poll query shows up in your database metrics.
"Exactly once" is at-least-once plus a dedupe
Nobody delivers exactly once across a network to a system they don't control. Kafka's own design docs say it guarantees at-least-once delivery by default, and that exactly-once delivery to other destination systems "generally requires cooperation with such systems" (Kafka). Stripe's webhook docs say the same thing from the other side: your endpoint "might occasionally receive the same event more than once" (Stripe).
What you can build is effectively once: deliver at least once, and make the consumer's effect happen once. The consumer records the event ID and does its work in one transaction, so a second delivery finds the ID and stops:
def handle_payment_succeeded(conn, event):
"""Idempotent consumer: the dedupe row and the side effect commit together."""
with conn.transaction():
claimed = conn.execute(
"INSERT INTO processed_events (event_id) VALUES (%s)"
" ON CONFLICT (event_id) DO NOTHING",
(event["event_id"],),
).rowcount
if claimed == 0:
return # seen it: the relay or the broker delivered it twice
conn.execute(
"UPDATE orders SET status = 'paid' WHERE payment_id = %s",
(event["payment_id"],),
)
That's the same idempotency-store idea as for incoming webhooks (webhook idempotency) and the same reason outgoing API calls carry an idempotency key. The outbox guarantees the event isn't lost. The consumer guarantees it isn't applied twice. You need both.
What the queue on the other side of the relay needs: separate queues, dead letters, backpressure, and an idempotency check on the job ID. From chapter 21.
Queue Best Practices
| Practice | Value | Implementation |
|---|---|---|
| Separate queues | Prevent blocking between job types | One queue per job category |
| Priority levels | Critical payments before analytics | 4 priority tiers |
| Dead letter queues | Capture jobs that keep failing | Auto-move once the job's retry budget is spent |
| Concurrency tuning | Match workload type | CPU-bound: about one worker per core; I/O-bound: more, tuned under load |
| Idempotency | Handle duplicate deliveries | Check job ID before processing |
| Backpressure | Prevent overload | Prefetch count limits |
The tests that prove a consumer is effectively-once: deliver twice, deliver backwards, deliver late. Written for webhooks, and they apply unchanged to outbox consumers. From chapter 39.
Testing Duplicates, Reordering, and Late Delivery
Test the store, not the response. Every provider will happily tell you your endpoint returned 200; the question is whether the payments table changed once. Deliver the same signed payload twice and assert one row updated and one email sent. Then flush Redis and deliver it a third time, and assert the database layer caught it. That third delivery is the TTL-expiry test most suites never run.
Capture fixtures from the real thing. Run a tunnel, fire events with the tools in the table (stripe trigger, Paddle's simulator, Square's Send test event, Adyen's Test configuration, PayPal's simulator), and save the raw bytes and headers to disk. For the HMAC providers you can also sign your own fixtures with a test secret, which lets you build cases the simulators won't, like a valid signature over a tampered body. PayPal you can't sign locally, so mock the verify endpoint and test both SUCCESS and a failure response.
Reordering tests take a captured sequence and deliver it backwards. If you use fetch-current-state, mock the provider's read API to return the final object and assert the final row matches it regardless of order. If you use sequence numbers, deliver the second event first, assert it's queued and nothing changed, deliver the first, and assert both applied in order. Then test the timeout: deliver the second event alone, advance the clock past an hour, and assert whatever you decided abandoned events should do.
Late delivery has two flavors. For Stripe and Paddle, deliver a fixture with a signature timestamp older than the tolerance and assert rejection before any parsing. For every provider, deliver a fixture whose event ID you recorded longer ago than your retention and assert your chosen behavior, because the code will process it as new. Sandbox retry schedules are shorter than live ones, three tries over a few hours for Stripe and 15 minutes for Paddle, so the three-day tail is something you have to simulate, not wait for.
When you don't need an outbox
If nothing outside the database cares about the event, or the "event" is a job that the same database runs (a job table polled by workers is already an outbox in all but name), skip the extra machinery. The outbox earns its keep when a message broker, another service, or a third party has to hear about every payment state change and silence would cost money: unfulfilled orders, a ledger that's missing a charge, a receipt that never went out.
Questions
What is the outbox pattern?
The outbox pattern writes an event into an outbox table in the same database transaction as the business change, such as a payment succeeding. A separate relay reads the table and publishes the events to a message broker, so the event is published if and only if the change committed.
What problem does the transactional outbox solve?
The dual write: updating the database and publishing to a queue are two writes with no shared transaction. A crash or error between them leaves a committed payment with no event, or an event for a payment that was never saved.
Does the outbox pattern give exactly-once delivery?
No. The relay can publish a message more than once, for example if it crashes after the broker accepts the message but before it marks the row as published. You get at-least-once delivery, and make it effectively once with an idempotent consumer that records each event ID in the same transaction as its work.
Why use SELECT ... FOR UPDATE SKIP LOCKED for the relay?
It lets several relay workers claim different batches of unpublished rows without blocking on each other. PostgreSQL's documentation describes SKIP LOCKED as suitable for multiple consumers of a queue-like table. The trade-off is ordering: with several workers, events can be published out of order.
Polling relay or change data capture?
A polling relay is a SQL query in a loop and is the simplest first version. Change data capture, such as Debezium's Outbox Event Router, reads the database's transaction log instead, which removes the polling load but adds Kafka Connect and Debezium to run.