Dev

Designing a Transactional Outbox in Practice — dual writes, SKIP LOCKED polling, Debezium CDC, partition cleanup

The transactional outbox removes the dual-write problem by writing to one store only. This walks through a PostgreSQL outbox table with range partitions and a partial index, a polling relay built on FOR UPDATE SKIP LOCKED, and a Debezium 3.7.1.Final EventRouter CDC pipeline. It covers per-aggregate ordering, poison messages and DLQ handling, at-least-once delivery and consumer idempotency, replication-slot WAL retention, and dropping partitions instead of deleting rows.

Poll batch
200 rows
Delivery
At-least-once
CDC baseline
3.7.1.Final
Cleanup
DROP PARTITION

When you try to write to two stores at once

Take a single order API. It writes the order to orders and must also tell the rest of the world that it happened, by producing an event to Kafka.

orderRepository.save(order);              // 1. commit to the database
kafkaTemplate.send("order-created", ev);  // 2. publish to the broker

There is always a gap between those two lines, and whichever one fails produces a different lie.

  • 1 succeeds, 2 fails: the order exists, the event does not. Inventory, shipping and billing never learn about it until someone greps the logs and re-sends it by hand.
  • 2 succeeds, 1 fails: the world has an “order created” event for an order that does not exist. Consumers fail to look it up, or worse, start creating it themselves.

There is a third case. Both succeed and the response is lost, so the client retries and the event goes out twice.

This is the dual-write problem. The instinct is a distributed transaction (2PC), and even when the broker supports XA, 2PC holds participants for the length of the commit and leaves them locked if the coordinator dies. Not something you introduce to process a few payments.

The answer is to stop writing to two places. Write to one. Put the business change and the fact that an event must be sent into the same local transaction, and let a separate process publish after the commit. The database guarantees atomicity, and publish failures get retried.

flowchart LR
  subgraph DW["Dual write · two stores"]
    A1["Commit to database"] --> A2["Publish to broker"]
    A2 -. "publish fails" .-> A3["Lost event<br/>order remains"]
    A4["Publish to broker"] --> A5["Commit to database"]
    A5 -. "commit fails" .-> A6["Phantom event<br/>no order"]
  end
  subgraph OB["Outbox · one store"]
    B1["Business row change"] --> B2["Outbox INSERT in the same transaction"]
    B2 --> B3["Commit (atomic)"]
    B3 --> B4["Relay publishes after commit"]
    B4 --> B5["At-least-once delivery + retries"]
  end

This post designs that separate process two ways: a polling relay inside the application, and Debezium CDC reading the WAL. They need different table shapes and get ordering in different ways. The comparison comes at the end.

1. Table design — partitions and a partial index

An outbox table is a queue. Hundreds of rows per second go in, and everything past the retention window must disappear. In PostgreSQL, the structure that meets both requirements is a partitioned table.

CREATE TABLE outbox (
    id             uuid        NOT NULL,
    aggregate_type text        NOT NULL,   -- order, payment, shipment
    aggregate_id   text        NOT NULL,   -- the ordering unit
    event_type     text        NOT NULL,   -- OrderCreated, OrderCancelled
    payload        jsonb       NOT NULL,
    headers        jsonb       NOT NULL DEFAULT '{}'::jsonb,
    created_at     timestamptz NOT NULL DEFAULT now(),
    available_at   timestamptz NOT NULL DEFAULT now(),   -- retry time after backoff
    attempts       smallint    NOT NULL DEFAULT 0,
    locked_until   timestamptz,                          -- lease held by a relay
    delivered_at   timestamptz,
    last_error     text,
    PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);

-- Weekly partitions. Old ones are removed whole with DROP.
CREATE TABLE outbox_2026w48 PARTITION OF outbox
    FOR VALUES FROM ('2026-11-23') TO ('2026-11-30');

-- Partial index holding only undelivered rows.
CREATE INDEX outbox_pending_idx ON outbox (created_at)
    WHERE delivered_at IS NULL;

-- For keeping per-aggregate order
CREATE INDEX outbox_aggregate_idx ON outbox (aggregate_id, created_at)
    WHERE delivered_at IS NULL;

Five things worth pointing out.

Why created_at is in the primary key. PostgreSQL requires the partition key to be part of any unique constraint on a partitioned table. PRIMARY KEY (id) alone fails with there is no unique constraint matching given keys for referenced table. So the key is (id, created_at), and the relay addresses rows with both. Use a time-ordered id such as UUID v7 and index locality improves.

The partial index is where the performance is. Most rows in an outbox are already delivered. A full index carries those dead rows and grows, and the batch query has to wade through all of them to find the living fraction. With WHERE delivered_at IS NULL in the index definition, index size is proportional to the current backlog. A few megabytes in steady state, growing only when something is actually stuck.

DROP TABLE instead of DELETE. Deleting delivered rows piles up dead tuples that VACUUM must chase. At hundreds of inserts per second, vacuum never catches up. Dropping a partition just removes files. One scheduled job that drops partitions older than the retention window (say seven days) is the whole cleanup story.

locked_until is a lease. If the relay that claimed a batch dies mid-publish, those rows stay claimed forever. A row whose locked_until has passed can be taken by another relay.

available_at is backoff. Re-claiming a failing row immediately means one poison message keeps failing the whole batch. Record the next attempt time on the row and skip it until then.

Partitioning also means queries must include created_at. Without it, partition pruning cannot happen and every query scans every partition. Put an explicit range in the batch query, like delivered_at IS NULL AND created_at >= now() - interval '7 days'.

2. Relay 1 — polling with FOR UPDATE SKIP LOCKED

The cheapest option: a scheduler inside the application that claims a batch in a short transaction and publishes it.

The key is SKIP LOCKED. With a plain FOR UPDATE, the second relay waits on rows the first one locked. While one batch of 200 is being processed, other instances do nothing, and adding instances only adds waiting. SKIP LOCKED steps over locked rows and takes the next ones. One keyword turns the table into a work queue several relays can share without contending.

WITH batch AS (
    SELECT id, created_at
      FROM outbox
     WHERE delivered_at IS NULL
       AND available_at <= now()
       AND (locked_until IS NULL OR locked_until < now())
       AND created_at >= now() - interval '7 days'
     ORDER BY created_at
     LIMIT 200
       FOR UPDATE SKIP LOCKED
)
UPDATE outbox o
   SET locked_until = now() + interval '60 seconds',
       attempts     = o.attempts + 1
  FROM batch b
 WHERE o.id = b.id AND o.created_at = b.created_at
RETURNING o.id, o.created_at, o.aggregate_type, o.aggregate_id,
          o.event_type, o.payload, o.headers, o.attempts;

One statement claims, marks the lease, and counts the attempt. Once it commits, the row locks release and other relays skip the row thanks to locked_until.

Publishing and marking happen outside the transaction. Never publish inside the transaction — if the event reaches the broker and the database then rolls back, you have created the phantom event you were trying to avoid.

@Component
public class OutboxPoller {

    private static final int BATCH = 200;
    private static final int MAX_ATTEMPTS = 10;

    private final JdbcClient jdbc;
    private final KafkaTemplate<String, String> kafka;

    @Scheduled(fixedDelayString = "${outbox.poll-interval:500}")
    public void poll() {
        var rows = jdbc.sql("""
                WITH batch AS (
                    SELECT id, created_at
                      FROM outbox
                     WHERE delivered_at IS NULL
                       AND available_at <= now()
                       AND (locked_until IS NULL OR locked_until < now())
                       AND created_at >= now() - interval '7 days'
                     ORDER BY aggregate_id, created_at
                     LIMIT :limit
                       FOR UPDATE SKIP LOCKED
                )
                UPDATE outbox o
                   SET locked_until = now() + interval '60 seconds',
                       attempts     = o.attempts + 1
                  FROM batch b
                 WHERE o.id = b.id AND o.created_at = b.created_at
                RETURNING o.id, o.created_at, o.aggregate_type, o.aggregate_id,
                          o.event_type, o.payload::text AS payload, o.headers::text AS headers,
                          o.attempts
                """)
            .param("limit", BATCH)
            .query(OutboxRow.class)
            .list();

        String currentAggregate = null;
        for (OutboxRow row : rows) {
            // If an earlier event of this aggregate failed, hold the rest back.
            if (row.aggregateId().equals(currentAggregate)) break;

            try {
                var record = new ProducerRecord<>(
                        "outbox.event." + row.aggregateType(),
                        row.aggregateId(),                       // partition key = ordering unit
                        row.payload());
                record.headers().add("id", row.id().toString().getBytes(StandardCharsets.UTF_8));
                record.headers().add("type", row.eventType().getBytes(StandardCharsets.UTF_8));
                kafka.send(record).get(5, TimeUnit.SECONDS);      // wait for acks=all

                jdbc.sql("UPDATE outbox SET delivered_at = now(), last_error = NULL " +
                         "WHERE id = :id AND created_at = :createdAt")
                    .param("id", row.id()).param("createdAt", row.createdAt())
                    .update();
            } catch (Exception e) {
                backoffOrPark(row, e);
                currentAggregate = row.aggregateId();             // stop this aggregate here
            }
        }
    }

    private void backoffOrPark(OutboxRow row, Exception e) {
        if (row.attempts() >= MAX_ATTEMPTS) {
            jdbc.sql("""
                    UPDATE outbox
                       SET delivered_at = NULL, locked_until = NULL,
                           last_error = :err, available_at = 'infinity'
                     WHERE id = :id AND created_at = :createdAt
                    """)
                .param("err", abbreviate(e)).param("id", row.id()).param("createdAt", row.createdAt())
                .update();
            return;
        }
        jdbc.sql("""
                UPDATE outbox
                   SET locked_until = NULL,
                       available_at = now() + (interval '1 second' * power(2, attempts))
                                      + (random() * interval '1 second'),
                       last_error = :err
                 WHERE id = :id AND created_at = :createdAt
                """)
            .param("err", abbreviate(e)).param("id", row.id()).param("createdAt", row.createdAt())
            .update();
    }
}

The whole flow looks like this.

sequenceDiagram
  autonumber
  participant R as Relay instance
  participant P as PostgreSQL
  participant K as Kafka
  R->>P: Claim a batch (FOR UPDATE SKIP LOCKED)
  P-->>R: 200 rows + locked_until 60s, committed
  loop each event in the batch
    R->>K: produce (key is aggregate_id)
    K-->>R: acks all
    R->>P: UPDATE outbox SET delivered_at = now()
  end
  Note over R,P: dying between ack and mark means the next tick re-sends it
  Note over R,K: which is why the outbox is at-least-once

Flip the order — mark first, publish second — and you get the opposite bug. Dying before the publish makes the event disappear forever, which is the exact failure the outbox exists to prevent. So the order is always publish, confirm, mark, and the price is duplicates. Duplicates can be removed by consumers (below). Lost events cannot.

Ordering per aggregate

ORDER BY aggregate_id, created_at plus break is the cheapest way to keep order. The batch is sorted by aggregate, so the moment one event of an aggregate fails, the rest of that aggregate is deferred to the next tick instead of overtaking the failed one.

There is a trap here. created_at is the transaction start time (now()). If transaction A starts at 10:00:00 and commits at 10:00:05, while B starts at 10:00:01 and commits at 10:00:02, then B landed in the database first but A has the earlier created_at. When two transactions touch the same aggregate concurrently, polling can emit them in reverse.

Three practical answers.

  1. Serialize per aggregate: handle changes to one order in one transaction at a time (pessimistic lock, or a queue partitioned by key). Removes the problem at the source.
  2. A version field: put aggregate_version in payload and have consumers drop events older than what they have already applied. Order can flip; the final state stays right.
  3. Bucket the relays: fix each aggregate to one of N relays with hashtext(aggregate_id) % N = worker_idx. Each instance handles only its buckets, so one aggregate never publishes from two relays at once. The cost is reshuffling buckets when you scale the relay fleet.
-- Only aggregates owned by worker 1 of 3
AND hashtext(aggregate_id) % 3 = 1

3. Poison messages and the DLQ

Split failures into two kinds. Transient (leader election, timeouts) resolves on retry. Permanent (a record larger than the broker’s max.message.bytes, a serialization error) fails identically forever. Without that distinction, one poison message pins the relay.

  • Keep attempts on the row and increment per try.
  • On failure, push available_at out with exponential backoff (2^attempts seconds plus jitter in the code above).
  • Past a limit (say 10), set available_at = 'infinity' to park the row and raise an alert. It drops out of normal batch queries, and once the cause is fixed, a human sets available_at = now() and it flows again.

Many teams keep a separate DLQ table. The upside is a list of parked messages you can replay one at a time; the downside is a second table and one more transaction boundary. Start with available_at = 'infinity' on the same table, and split into a table when manual replay becomes routine.

The message lifecycle fits in one state diagram.

stateDiagram-v2
  state "Pending" as PENDING
  state "Claimed" as CLAIMED
  state "Delivered" as DELIVERED
  state "Backoff" as BACKOFF
  state "Parked (DLQ)" as DEAD
  [*] --> PENDING: committed with the business change
  PENDING --> CLAIMED: claimed by SKIP LOCKED batch
  CLAIMED --> DELIVERED: broker ack + delivered_at
  CLAIMED --> BACKOFF: publish failed
  BACKOFF --> CLAIMED: available_at reached
  BACKOFF --> DEAD: attempts exceeded
  DEAD --> PENDING: manual replay after a fix
  DELIVERED --> [*]: partition DROP after retention

4. Relay 2 — Debezium CDC with EventRouter

Polling is simple but pays in constant table scanning: latency equals the poll interval when traffic is low, and batch UPDATEs pressure the index when it is high. CDC moves that work out of the database. Debezium reads the changes PostgreSQL already wrote to the WAL and streams them to Kafka. No relay code, no delivered_at marking, no UPDATE.

Three things to prepare in the database.

-- 1. Turn on logical decoding (requires a restart)
ALTER SYSTEM SET wal_level = 'logical';
-- also raise max_replication_slots and max_wal_senders in postgresql.conf

-- 2. Publish the outbox table
CREATE PUBLICATION iinow_outbox_pub FOR TABLE outbox;

-- 3. Replication and read privileges for the Debezium role
ALTER ROLE debezium WITH REPLICATION;
GRANT SELECT ON outbox TO debezium;

The outbox table should use the column names EventRouter expects. You can map different names through SMT options, but following the defaults lets you copy the docs and examples verbatim.

CREATE TABLE outbox (
    id            uuid         NOT NULL,
    aggregatetype varchar(255) NOT NULL,   -- topic name segment
    aggregateid   varchar(255) NOT NULL,   -- message key = partition key
    type          varchar(255) NOT NULL,   -- event type
    payload       jsonb,
    created_at    timestamptz  NOT NULL DEFAULT now()
) PARTITION BY RANGE (created_at);

The connector configuration comes out like this.

connector.class=io.debezium.connector.postgresql.PostgresConnector
plugin.name=pgoutput
slot.name=iinow_outbox
publication.name=iinow_outbox_pub
table.include.list=public.outbox

# apply the transformation to the outbox table only
transforms=outbox
transforms.outbox.type=io.debezium.transforms.outbox.EventRouter
transforms.outbox.route.by.field=aggregatetype
transforms.outbox.route.topic.replacement=outbox.event.${routedByValue}
transforms.outbox.table.expand.json.payload=true

# keep the replication slot from holding WAL forever
heartbeat.interval.ms=30000
heartbeat.action.query=SELECT pg_logical_emit_message(false, 'outbox_heartbeat', now()::varchar)

Reading it back: a row with aggregatetype = order goes to the outbox.event.order topic, and payment to outbox.event.payment (${routedByValue} in route.topic.replacement is filled from route.by.field). aggregateid becomes the Kafka message key, so events for one order land in one partition and stay ordered. id goes into a message header and is the consumer’s dedupe key. With table.expand.json.payload=false (the default) the payload ships as an escaped JSON string and the consumer parses it again; true emits a real JSON object.

sequenceDiagram
  autonumber
  participant A as Order service
  participant P as PostgreSQL
  participant D as Debezium connector
  participant K as Kafka
  participant C as Consumer
  A->>P: BEGIN
  A->>P: INSERT orders
  A->>P: INSERT outbox (aggregatetype=order)
  A->>P: COMMIT
  P-->>D: WAL stream (pgoutput)
  D->>D: EventRouter SMT transforms the row
  D->>K: outbox.event.order (key is aggregateid)
  K-->>C: delivered in partition order

This is where the CDC design diverges on cleanup. EventRouter filters DELETE events out automatically, and in its default configuration logs a warning and skips UPDATEs on the outbox table (table.op.invalid.behavior). The table is assumed to be append-only. So the “mark delivered then purge” shape does not fit. Cleanup is, again, partition DROP: DDL produces no row events, so nothing flows into the CDC path.

5. Choosing between them

  Polling + SKIP LOCKED Debezium CDC + EventRouter
Latency Poll interval (200ms–2s typical) Tens to hundreds of ms (WAL streaming)
Database load Periodic index scan + batch UPDATE WAL decoding + slot retention
Extra infrastructure None (scheduler in the app) Kafka Connect or Debezium Server, Kafka
Ordering You build it (sort, break, buckets) WAL commit order + aggregateid key
Failure recovery attempts, backoff, parking — yours Connector offsets, re-sends on restart
Cleanup delivered_at + partition DROP Partition DROP (DELETE auto-filtered)
Table shape Anything (add marking columns) EventRouter default names preferred
Learning curve Low Medium to high
Fits One or two services, no Kafka operators Kafka and Connect already running, many consumers

My take: start with polling. It is about a hundred lines, and every failure mode shows up in your own table. Move to CDC when poll latency actually hurts, when UPDATE load is measured rather than feared, or when several consumer teams make topic contracts a shared concern. If the table is already partitioned, the migration is a column-rename and marking-column cleanup, not a rewrite.

The reverse is just as valid. If Kafka Connect is already running and someone owns the slots, there is no reason to write a polling relay.

6. At-least-once, and the consumer’s half

An outbox guarantees at-least-once, not exactly once.

  • Polling: dying between a successful publish and the delivered_at write re-sends the event.
  • CDC: dying before the consumer commits its offset makes the connector re-read from the same WAL position.

So consumers must tolerate duplicates. The standard shape is to record the fact in the same transaction as the work.

CREATE TABLE consumed_event (
    consumer    text        NOT NULL,   -- service or handler name
    event_id    uuid        NOT NULL,
    consumed_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer, event_id)
);

-- record and process in one transaction
INSERT INTO consumed_event (consumer, event_id) VALUES ('shipping', :eventId)
ON CONFLICT (consumer, event_id) DO NOTHING;
-- zero rows means already processed, so commit and advance the offset

This is the inbox pattern. consumed_event grows forever too, so give it a retention window and partitions like the outbox. The window must be longer than the longest time an event can come back — the larger of the CDC replay window and the broker retention.

HTTP-level duplicates are a different problem, covered in Designing Idempotency Keys for APIs. The outbox solves the gap between commit and publish; an idempotency key solves client retries. Same vocabulary, different layer.

7. Operational signals — watch the age, not the count

A “pending rows” gauge is hard to read. A traffic spike makes 10,000 pending rows normal, and a broken relay with three pending rows looks fine. What matters is age.

-- 1. Age in seconds of the oldest undelivered row. This is the alarm.
SELECT coalesce(max(extract(epoch FROM now() - created_at)), 0) AS oldest_seconds
  FROM outbox
 WHERE delivered_at IS NULL
   AND available_at <> 'infinity';

-- 2. Parked poison rows
SELECT count(*) AS poisoned
  FROM outbox
 WHERE available_at = 'infinity';
  • oldest_seconds: warn past 60, page past 300. It answers “is data flowing” directly. Count is throughput; age is health.
  • poisoned: anything above zero needs a human. Alert on the first one.
  • attempts distribution: a rising retry rate points at the broker or the schema.

The same principle applies on the CDC side. “Are messages coming out” does not tell you whether the connector is alive, because quiet tables produce no messages either. What tells you is how much WAL the slot is holding.

SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal,
       pg_size_pretty(safe_wal_size) AS headroom,
       now() - inactive_since        AS idle_for
  FROM pg_replication_slots
 WHERE slot_name = 'iinow_outbox';

wal_status walks reserved → extended → unreserved → lost. Once a slot is unreserved the next checkpoint can invalidate it, and once it is lost the changes in between are unreadable; you need a resync.

Check the default here. max_slot_wal_keep_size defaults to -1, which means unlimited. A connector left stopped will keep the slot retaining WAL until the disk fills. Set a number (say 16GB) and crossing it invalidates the slot — replication stops, the disk survives. Which you prefer depends on the service, but leaving it unset is not a choice. Note that safe_wal_size is NULL while the parameter is -1: that NULL means “no idea how much headroom is left”.

PostgreSQL 18 adds idle_replication_slot_timeout to clean this up automatically. Zero (the default) disables it; a non-zero value invalidates slots unused for that long at the next checkpoint. A useful seatbelt when a connector stays down.

8. Checklist

  • Does the outbox row land in the same transaction as the business change (one @Transactional boundary)?
  • Is publishing done outside the transaction, after commit?
  • Does the PRIMARY KEY include the partition key (created_at)?
  • Does the pending query use the partial index? (confirm with EXPLAIN)
  • Are you using SKIP LOCKED, and is there a path to reclaim expired leases (locked_until)?
  • Ordering: can one aggregate publish from two relays at once? If so, do consumers protect themselves with aggregate_version?
  • Is there backoff on failure, plus parking and an alert past the limit?
  • Do consumers dedupe on event_id, and is that dedupe table cleaned up?
  • Is cleanup a partition DROP rather than DELETE?
  • Does the alert watch the age of the oldest row, not the pending count?
  • On CDC, are wal_status / retained_wal monitored and max_slot_wal_keep_size set?

The outbox is not new infrastructure. It is a promise about one table and one ordering rule. Business change and event in the same commit, publishing deferred past the commit, duplicates removed by the consumer. Keep those three lines and lost events and phantom events disappear. Skip one “for now” and the data starts drifting quietly at exactly that spot.

Comments

Type to search

↑↓ moveEnter openEsc close