System Design

Patterns

The Outbox Pattern

Write the event in the same transaction as the change, and let a relay send it afterwards. The outbox is a queue that lives inside your database, so every hard part of it is a queue problem: who reads it, in what order, how it gets emptied, and how far behind it is.

The shape

A service saves an order and then sends an OrderPlaced event to Kafka. Those are two writes to two systems, and no transaction covers both. If the process dies after the commit and before the send, the order exists and nothing downstream hears about it. This is a dual write, and retrying cannot fix it, because the retry does not know how far the first attempt got.

The outbox moves the second write into the first system. In the same transaction as the order, the service inserts a row describing the event into an outbox table. The commit keeps both rows or neither. A separate process, the relay, reads the outbox afterwards and sends each row to Kafka, retrying until Kafka confirms. Because the relay retries, an event can be sent twice. Idempotency and Exactly-Once Delivery explains why that trade is right: a lost event cannot be repaired, and a repeated one can.

In any system, when a change in one place has to reach another, write the message in the same transaction as the change, and deliver it later from what you wrote. The outbox is a queue that lives inside your database. The commit puts work on it, and the relay is its consumer. So every hard decision about it is a queue decision: how the relay reads it, in what order, how it gets emptied, and how far behind it may fall.

The same fix applies in two other places. Sending a welcome email after signup is a dual write with the email provider, and the fix is a table of emails to send, written by the signup transaction. And a consumer that has to remember which messages it has handled is the same pattern facing the other way, called an inbox.

The outbox and the inbox, end to end
The badges follow one event, e7. The order service writes the order row and outbox row e7 in one Postgres transaction (1). The relay reads the pending row (2) and sends it to Kafka, keyed by the order id (3). The stock service writes e7 into its inbox and reserves the stock in one transaction of its own (4). The green notes are the two local guarantees, and the orange note is the one place a repeat can come from.The badges follow one event, e7. The order service writes the order row and outbox row e7 in one Postgres transaction (1). The relay reads the pending row (2) and sends it to Kafka, keyed by the order id (3). The stock service writes e7 into its inbox and reserves the stock in one transaction of its own (4). The green notes are the two local guarantees, and the orange note is the one place a repeat can come from.
Each end commits locally, and only the hop in the middle can repeat. The badges follow one event, e7. The order service writes the order row and outbox row e7 in one Postgres transaction (1). The relay reads the pending row (2) and sends it to Kafka, keyed by the order id (3). The stock service writes e7 into its inbox and reserves the stock in one transaction of its own (4). The green notes are the two local guarantees, and the orange note is the one place a repeat can come from.

The mechanism

The outbox row

The row is the event, not a copy of the order. The aggregate is the thing the event is about, here one order, and aggregate_id names it.

CREATE TABLE outbox (
  id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_id       uuid        NOT NULL DEFAULT gen_random_uuid(),
  aggregate_type text        NOT NULL,  -- 'order': picks the topic
  aggregate_id   text        NOT NULL,  -- 'ord_42': the message key
  event_type     text        NOT NULL,  -- 'OrderPlaced'
  payload        jsonb       NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now(),
  sent_at        timestamptz            -- NULL until the relay sends it
);
CREATE INDEX outbox_pending ON outbox (id) WHERE sent_at IS NULL;

BEGIN;
UPDATE orders SET status = 'placed' WHERE id = 'ord_42';
INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES ('order', 'ord_42', 'OrderPlaced', '{"order_id": "ord_42", "total": 4200}');
COMMIT;

The payload is written for the consumers, so it is a contract. If consumers instead read raw row changes from the database's log, every one of them depends on your columns. Message Queues vs Event Streams counts that as the cost of change data capture (CDC).

The relay loop, and where it can crash

Every relay runs the same loop. It reads a batch of pending events, sends them to Kafka, waits for Kafka to confirm, then records how far it got. A crash can happen between any two steps, and none of them loses an event. So every event arrives at least once, and some twice.

Where the relay can crash
A crash before the send (1) only delays the batch, in green. A crash after the send and before Kafka confirms (2), or after Kafka confirms and before the relay records its progress (3), makes the next run send the batch again, in red.A crash before the send (1) only delays the batch, in green. A crash after the send and before Kafka confirms (2), or after Kafka confirms and before the relay records its progress (3), makes the next run send the batch again, in red.
A crash delays an event or repeats it, and never loses it. A crash before the send (1) only delays the batch, in green. A crash after the send and before Kafka confirms (2), or after Kafka confirms and before the relay records its progress (3), makes the next run send the batch again, in red.

Polling the table, or tailing the log

Polling. A loop asks the table for pending rows, sends them and marks them sent.

Log tailing. A CDC connector, such as Debezium, reads the database's write-ahead log (WAL), the log it writes every change to before applying it, and sends each committed outbox insert.

A polling relay is a few lines of SQL around a Kafka producer.

-- every 200 ms, or straight away if the last batch was full
BEGIN;
SELECT id, event_id, aggregate_type, aggregate_id, event_type, payload
FROM outbox
WHERE sent_at IS NULL
ORDER BY id
LIMIT 500
FOR UPDATE;
-- send the batch to Kafka and wait for every confirmation;
-- $1 holds only the ids whose send succeeded
UPDATE outbox SET sent_at = now() WHERE id = ANY($1);
COMMIT;

FOR UPDATE locks the rows it returns until the commit, so a second relay running the same query waits instead of sending them too. At the course's 2,000 events a second, each 200 ms poll finds about 400 rows.

Do not poll with a high-water mark, the highest id the relay has seen, as in WHERE id > last_seen. An id is handed out when a row is inserted, but the row becomes visible only when its transaction commits. Transaction A can take id 100 and transaction B id 101, and B can commit first. The relay reads 101, moves its mark past it, and never asks for 100 again. Gunnar Morling describes this failure in his 2024 review. Polling for sent_at IS NULL does not lose row 100. It sends it late, after 101.

Log tailing reads the commit instead of the table. On Postgres, the connector reads through a replication slot, a named position in the WAL that the database keeps for one reader. Postgres hands the connector each transaction in the order it committed, and never one that rolled back, so it cannot skip a row the way a high-water mark can.

Debezium's outbox event router expects columns like the ones above. It sends each outbox insert to a topic named after the aggregate type, such as outbox.event.order, keys it by the aggregate id, and ignores deletes. So the service can delete the outbox row in the same transaction that inserts it. The insert is in the log, and the table stays empty.

On Postgres you can drop the table altogether. pg_logical_emit_message(true, 'outbox', payload) writes a message into the WAL, and the connector receives it in commit order. The true makes the message part of the current transaction, so a rollback discards it. SeatGeek described running this in 2025, with Debezium reading the messages.

The cost moves from the table to the log. A slot keeps every byte of WAL its reader has not confirmed, even when nothing is connected. By default Postgres puts no limit on that, so if the connector stays stopped, the disk fills.

Keeping nothing in the table also makes the log the only copy of any event the connector has not read. If that copy is lost, a fresh snapshot of the empty outbox cannot bring the events back, and no error is raised.

Postgres can lose that copy in two ways. If you set a limit on a slot's WAL or on its idle time, Postgres invalidates a slot that passes the limit, and the connector cannot resume from it. And a failover loses the slot unless the standby keeps a copy of it. Postgres 17 added this as failover slots.

Either keep sent rows for a window, so they can be read again, or use failover slots with no limit set, and watch the disk.

Two ways to read the outbox
In the top half, the relay queries the outbox table for pending rows every 200 ms (1), sends them to Kafka (2) and sets sent_at on each row (3). In the bottom half, the commit writes the outbox insert to the WAL (1), Debezium reads it through a replication slot in commit order (2), and the outbox event router sends it to the topic for its aggregate type, keyed by aggregate id (3).In the top half, the relay queries the outbox table for pending rows every 200 ms (1), sends them to Kafka (2) and sets sent_at on each row (3). In the bottom half, the commit writes the outbox insert to the WAL (1), Debezium reads it through a replication slot in commit order (2), and the outbox event router sends it to the topic for its aggregate type, keyed by aggregate id (3).
Polling reads the table, and tailing reads the log the commit already wrote. In the top half, the relay queries the outbox table for pending rows every 200 ms (1), sends them to Kafka (2) and sets sent_at on each row (3). In the bottom half, the commit writes the outbox insert to the WAL (1), Debezium reads it through a replication slot in commit order (2), and the outbox event router sends it to the topic for its aggregate type, keyed by aggregate id (3).

Take polling if you do not already run Kafka Connect, the framework Debezium usually runs on. It is one query and one loop, and its failures show up in your own code. Move to log tailing when you need lower delay, when polling load shows on the primary, or when you already run Debezium.

Ordering, per aggregate

Like any queue, the outbox keeps order only within a key. A single global order would mean one relay and one Kafka partition. Consumers need only one order's events in the order they happened: placed, then paid, then shipped. Three links have to keep that order.

The outbox ids follow the order's history. Update the order row before inserting the outbox row. The update locks the row, so a second transaction on ord_42 waits at its own update until the first commits, and only then takes a higher outbox id. If the code inserts the outbox row first, the second transaction can take a lower id before it blocks, and its event sorts ahead of the one it follows.

One relay sends all of an order's events. Adding SKIP LOCKED to the query lets several relays drain the table at once, because each relay skips rows another one has locked. Then one order's events can land in two batches. If the second batch finishes first, the later event reaches Kafka first.

So run one active relay with a standby, or give each relay a fixed share of orders, such as the orders where hash(aggregate_id) % N equals its number. Either way, lock with plain FOR UPDATE. A relay that takes over then waits for the old relay's locks, instead of skipping an order's earlier row and sending a later one.

With Kafka's default settings, a stuck relay can hold those locks for up to 2 minutes while the producer retries a send. A Postgres timeout on idle transactions ends the stuck relay's session and frees the locks. A log reader needs none of this, because one connector reads the slot in commit order.

The key holds the order inside Kafka. With aggregate_id as the key, one order's events share a partition, and by default Kafka's producer keeps their order when it retries a send. If one event will not send, the relay holds back that order's later events rather than skip ahead.

Two relays and one order
In the top half, relay A takes the batch holding row 300, ord_42 placed, and relay B takes the batch holding row 700, ord_42 paid. B finishes first (1), so the ord_42 partition gets paid before placed, in red. In the bottom half, each relay owns a share of orders by a hash of the aggregate id, and locks rows with plain FOR UPDATE, so a relay taking over a share waits for the old one's locks. Relay A owns ord_42 and sends rows 300 and 700 in id order (2), so the partition gets placed, then paid.In the top half, relay A takes the batch holding row 300, ord_42 placed, and relay B takes the batch holding row 700, ord_42 paid. B finishes first (1), so the ord_42 partition gets paid before placed, in red. In the bottom half, each relay owns a share of orders by a hash of the aggregate id, and locks rows with plain FOR UPDATE, so a relay taking over a share waits for the old one's locks. Relay A owns ord_42 and sends rows 300 and 700 in id order (2), so the partition gets placed, then paid.
An order's events stay in order only if one relay sends all of them. In the top half, relay A takes the batch holding row 300, ord_42 placed, and relay B takes the batch holding row 700, ord_42 paid. B finishes first (1), so the ord_42 partition gets paid before placed, in red. In the bottom half, each relay owns a share of orders by a hash of the aggregate id, and locks rows with plain FOR UPDATE, so a relay taking over a share waits for the old one's locks. Relay A owns ord_42 and sends rows 300 and 700 in id order (2), so the partition gets placed, then paid.

Duplicates, and the inbox on the other side

Because the relay sends at least once, a consumer will receive some events twice. The fix is the inbox. In one transaction, the consumer inserts the event id into an inbox table with a unique key, and applies the change. For a repeat, the insert adds no row, so the consumer rolls back, commits its Kafka offset and moves on.

BEGIN;
INSERT INTO inbox (event_id, received_at)
VALUES ($1, now())
ON CONFLICT (event_id) DO NOTHING;
-- 0 rows inserted: a repeat, so ROLLBACK and commit the offset
UPDATE stock SET reserved = reserved + 1 WHERE sku = 'sku_7';
COMMIT;

The update adds 1, a write that is unsafe to repeat. The inbox makes it safe, because the insert and the update commit together or not at all.

Keep inbox ids for as long as a repeat can arrive. If the outbox keeps 7 days of rows for replay, the inbox needs at least 7 days of ids.

Emptying the table

On a polling outbox, each event is three row writes: the insert, the update that sets sent_at, and a later delete. In Postgres, an update or a delete leaves the old version of the row behind as a dead row. Until vacuum, the Postgres cleanup process, removes them, the poll has to step over their index entries.

Vacuum falls behind while any long transaction is open, because it cannot remove a row that transaction might still see. Brandur measured this on a Postgres job queue in 2015. With one transaction left open for an hour, lock time reached 15 times normal at its peaks, and the queue grew to 60,000 jobs. The polling relay holds its transaction open while it sends, so keep the send short.

Back of envelopeWhat a week of outbox rows costs to remove
The course sizes the outbox at 2,000 events/s, about 200 B
a row, kept 7 days so the relay can replay them. The question
is how to remove old rows: one at a time, or a day at a time.

Rows
  per day        2,000 × 86,400            =  172.8M
  kept           172.8M × 7                =   1.21B
  size           1.21B × 200 B             ≈  242 GB

Deleting sent rows
  deletes        same as the insert rate   =  2,000/s, all day
  dead rows      2,000 updates/s + 2,000 deletes/s
                                           =  4,000/s for vacuum

Dropping one partition a day
  deletes                                  =  0
  dead rows      2,000 updates/s           =  2,000/s for vacuum
  removal        one DROP TABLE, 172.8M rows, once a day

Partitioning by day halves the dead rows vacuum has to clear
and removes the delete load entirely.

Partition the table by day on created_at, and drop the oldest partition each night. Before each drop, check the partition for rows where sent_at IS NULL, and page someone instead of dropping it. A log-tailing outbox can keep its window the same way.

A row that can never be sent, such as one over Kafka's size limit, is moved on purpose to a dead-letter table, a table for events that failed. There a person decides what happens to that order's later events.

Relay lag, the number to alarm on

As with any queue, alarm on how long the oldest item has waited, not on how many are waiting.

SELECT coalesce(
  (SELECT now() - created_at FROM outbox
   WHERE sent_at IS NULL ORDER BY id LIMIT 1),
  interval '0') AS oldest_pending;

A healthy relay keeps this near one poll interval, 200 ms. A stuck one makes it grow by a second every second. The row count can stay flat while one row fails again and again, for example because its payload is over Kafka's default size limit of about 1 MB.

For log tailing, watch the slot instead. In the pg_replication_slots view, pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) gives how many bytes of WAL the connector has not confirmed.

Row count against the age of the oldest row
In the left column, a bulk import commits 40,000 orders at once, and the pending row count jumps (1). The age of the oldest row never gets near the red alarm line. In the right column, one row cannot be sent. The count does not move, and the age of that row crosses the alarm line a minute later (2).In the left column, a bulk import commits 40,000 orders at once, and the pending row count jumps (1). The age of the oldest row never gets near the red alarm line. In the right column, one row cannot be sent. The count does not move, and the age of that row crosses the alarm line a minute later (2).
The count jumps on a burst, and the age climbs when something is stuck. In the left column, a bulk import commits 40,000 orders at once, and the pending row count jumps (1). The age of the oldest row never gets near the red alarm line. In the right column, one row cannot be sent. The count does not move, and the age of that row crosses the alarm line a minute later (2).
Back of envelopeHow long the relay takes to catch up
While Kafka is down, orders keep committing and their events
wait in the table. Afterwards the relay sends the backlog and
the new events at the same time. The question is how long
until events are on time again. The course's figures: 2,000
events/s, a poll every 200 ms, at most 500 rows per poll.

Backlog after a 10 minute outage
  rows           2,000 × 600 s             =  1.2M

Polling on a fixed 200 ms timer
  capacity       500 / 0.2 s               =  2,500 rows/s
  spare          2,500 − 2,000             =    500 rows/s
  catch-up       1.2M / 500                =  2,400 s, 40 min

Polling again at once when a batch comes back full
  assume one full batch (read, send, mark) takes 50 ms
  capacity       500 / 0.05 s              = 10,000 rows/s
  spare          10,000 − 2,000            =  8,000 rows/s
  catch-up       1.2M / 8,000              =    150 s

Sleeping 200 ms after every 50 ms batch
  capacity       500 / 0.25 s              =  2,000 rows/s
  spare          2,000 − 2,000             =      0 rows/s
  catch-up                                 =  never

The timer is for an idle relay. A relay that waits for the next
200 ms tick after a full batch turns a 10 minute outage into
50 minutes of late events, and one that sleeps after every
batch never catches up.

How to tell you have this problem

A handler commits and then sends. Any code path that commits and then calls a broker client, an email API or a webhook is a dual write.

Downstream counts drift. List yesterday's order ids that have no OrderPlaced event in the consumer's data. A few missing ids clustered around deploys and broker incidents are sends lost between a commit and a send.

When you do not need one

You need an outbox when an event has to leave your database and must not be lost. In each case below, one of those is false, or the database already keeps the queue for you.

The event can be lost. Clicks and metrics can be sent after the commit, best effort.

The database already exports an ordered log. DynamoDB Streams records each change to a table exactly once, in order for each item, and keeps it for 24 hours. Its consumers need no outbox table, and a consumer that is down for more than 24 hours loses events.

The event is the write. A service that writes only to Kafka and builds its tables from it has no second write. It can no longer read its own writes straight after a request.

What it costs

Every event arrives late. A flow that needs the result before the user's next request has to read from the source.

The primary does more work. Polling adds an insert and an update per event, and five polls a second, on the database that takes every order. Log tailing moves it to a connector and a slot you have to run.

Where it shows up in the course

articlethe form it takes there
Change Data Capturethe event is written in the same transaction as the change and read from the log afterwards
Design a Distributed Job Schedulerthe firing commits first and the queue send follows; the partition's next owner resends every QUEUED run, and the start query is the inbox
Design a Distributed Message QueueKafka transactions cover only Kafka's partitions, so a service writes an outbox row and a relay publishes it
Design a Payment Systemthe processor's answer, the payment's state, the ledger transaction and the event commit together, so no one hears of a payment the database doesn't have
Distributed Transactions and Sagaseach hop of a choreographed saga: an outbox on the sending side and an inbox on the receiving side
Dropbox and Google Drivethe journal row and its reference increments commit together, and a relay carries them to the block index
Idempotency and Exactly-Once Deliverythe fix for a dual write, priced per business write, and the outbox row written with a signup so that the welcome email is always attempted
LSM Trees vs B-Treesthe polling outbox inserts, updates and deletes every row, which is the dead-row load a B-tree store has to vacuum
Message Queues vs Event Streamsthe senior answer to publishing an order event, with change data capture as the staff answer and the reason the outbox alone only approximates commit order
Notification Servicethe producer's outbox row carries the notification request and its idempotency key, so a redelivered request is dropped
Ticketmaster Bookingthe confirm writes the order, tickets and an outbox row in one commit; the relay captures the payment and issues the tickets
Uber Ride-Hailingrequesting and completing a trip each write their event in the trip's transaction, for payments, receipts and the archive
Write-Ahead Logsan outbox read by tailing the WAL ties the log's size on the primary to the reader's health

Getting it wrong

Sending inside the transaction. The send can succeed and the commit fail, which leaves an event for an order that does not exist.

Polling with id > last_seen. A row that commits after a higher id was read is never sent. Poll for sent_at IS NULL.

Reaching for Kafka transactions. Kafka's exactly-once guarantee covers only Kafka, as Confluent says. KIP-939, a Kafka Improvement Proposal that would let Kafka join a two-phase commit, is not released. Morling points out that it would need both systems up for every commit.

Leaving a replication slot unwatched. A slot whose connector stopped keeps WAL until the disk fills. It also stops vacuum from removing old rows in the system catalogs, and in extreme cases that forces Postgres to shut down to prevent transaction ID wraparound.

Sources

Product behaviour comes from each project's own documentation, and the sizing uses the course's figures.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.