The interviewer asks you to “make sure every order that gets written to the database also produces an OrderPlaced event on Kafka.” It sounds trivial. You save the row, you publish the event, done. Then they ask what happens if the process dies between those two lines, and the whole thing falls apart. You cannot write to a database and publish to a broker in one atomic step - they are two systems with two separate failure domains and no shared transaction. This is the dual-write problem, and it is not a bug you can code around with careful ordering or retries. It is a property of writing to two systems that do not commit together.

The transactional outbox pattern is the standard, correct answer: instead of writing to the DB and then the broker, you write the business row and an event row into an outbox table in one local transaction, then a separate relay process reads undelivered outbox rows and publishes them to the broker, marking them sent only after the broker acknowledges. The core invariant: a downstream event exists if and only if the database write it describes was committed - never one without the other. This post builds that system end to end, with the hard part front and center: how the relay delivers exactly-once across a service boundary when the broker, the relay, and the database can each fail independently.

Functional Requirements (FR)

In scope:

  • Atomic event capture. When a service commits a business state change (create an order, update a balance, change a status), the corresponding event is persisted atomically with that change. If the business write commits, the event is guaranteed to be captured; if it rolls back, no event exists.
  • Reliable relay to a broker. A relay process reads captured-but-undelivered events and publishes them to a message broker (Kafka, or a similar log/queue), in order per aggregate, and does not lose any.
  • Delivery acknowledgment and status. An event is marked delivered only after the broker confirms the write durably (acked by the required replicas). Un-acked events are retried.
  • Idempotent production. A relay that crashes and re-publishes an event does not create a visible duplicate downstream; the effective guarantee to consumers is exactly-once (or at-least-once plus a consumer dedup contract).
  • Ordering per aggregate. Events for the same aggregate (same order, same account) are delivered in the order they were produced. Events across different aggregates may interleave freely.
  • Observability. Expose relay lag (how far behind real time the relay is), outbox backlog depth, and a dead-letter path for events that cannot be published after N attempts.

Explicitly out of scope (state it so you own the scope):

  • The broker’s internals. I treat Kafka (or equivalent) as a durable, partitioned, replicated log with a producer API that supports idempotent writes and acks. I do not design the broker.
  • Consumer business logic. I design the delivery contract (keys, idempotency, ordering) that consumers rely on, but not what each downstream service does with an event.
  • Schema registry / event versioning governance. I assume an envelope and a serialization format; I do not design the registry.
  • Cross-datacenter replication of the broker. Single-region broker cluster here; I note the multi-region seam but do not build it.

The decision that drives everything: the write to the DB and the publish to the broker cannot share a transaction, so we never try. We make the DB write atomic with an event record, and move the “publish” to a separate, retriable, idempotent step that reads committed state. Correctness comes from atomic capture plus idempotent delivery, not from a distributed transaction we cannot have.

Non-Functional Requirements (NFR)

  • Scale: a busy service tier producing ~20,000 business writes/sec at peak, each generating one or more outbox events - call it ~30,000 events/sec peak, ~10,000 average. The relay must keep up with this sustained, and drain a backlog faster than real time after an incident.
  • Latency: end-to-end from DB commit to event visible on the broker, p99 under ~2s in steady state, p50 under ~200ms. This is not a user-facing synchronous path - the producing transaction returns as soon as it commits locally - so the budget is for the relay, not the write.
  • Availability: 99.99% for event capture (if the DB is up, events are captured). The relay can be briefly down without losing events - they sit durably in the outbox - but relay downtime directly adds to end-to-end latency, so target 99.95% for delivery with fast failover.
  • Consistency: the capture is strongly consistent with the business write (same ACID transaction). Delivery is at-least-once at the broker layer, upgraded to effectively exactly-once via idempotent producer semantics and consumer-side dedup. No event is ever published for an uncommitted write.
  • Durability: zero event loss. Once a business transaction commits, its event will be delivered, period. An event survives relay crashes, broker leader elections, and DB failovers. Nothing in flight vanishes silently.
  • Ordering: per-aggregate ordering preserved end to end. A later event for an order never overtakes an earlier one.

The central tension: at-least-once is the only thing the broker and relay can honestly promise across a crash, but duplicates are unavoidable under at-least-once, so the entire design is about making those unavoidable duplicates harmless - via idempotent producer writes and a stable per-event key that consumers dedup on. We lean into at-least-once delivery and build exactly-once effect on top of it.

Back-of-the-Envelope Estimation (BoE)

Real numbers, because they decide whether polling is enough or we need CDC.

Event write volume (into the outbox):

Peak business writes:   20,000 writes/sec
Events per write (avg):  ~1.5  (some writes emit multiple events)
Peak event inserts:     20,000 * 1.5 = 30,000 events/sec
Average:                ~10,000 events/sec
Daily volume:           ~10,000 * 86,400 = ~864M events/day

These outbox inserts are free in the sense that they ride inside transactions the service is already committing - one extra INSERT per transaction, same disk flush.

Relay read / publish throughput required:

The relay must sustain >= 30,000 events/sec publish to keep up at peak,
and handle backlog drain. Target design throughput ~60,000 events/sec
(2x headroom) so a 1-hour outage (30,000 * 3,600 = 108M backlog)
drains in ~1 hour of catch-up, not days.

This number is the whole ballgame for the polling-vs-CDC decision. A naive SELECT ... WHERE sent=false poll every 200ms that each grab a batch of a few thousand rows can do tens of thousands/sec - but only if the query is indexed and the delete/mark is cheap. We will see it strain and move to CDC.

Outbox storage (steady state, before cleanup):

Per outbox row:
  id(8) + aggregate_id(16) + aggregate_type(16) + event_type(32)
  + payload(~800 avg) + headers(~100) + created_at(8) + status(1)
  ~= 1 KB per row with index overhead

If we delete rows ~minutes after delivery, hot table stays small:
  30,000 rows/sec * 60 s of retention = 1.8M rows ~= 1.8 GB  (tiny)

If we instead KEEP delivered rows 7 days for replay/audit:
  864M/day * 7 * 1 KB = ~6 TB  (now it needs partitioning)

Decision falls out of this: delete-after-delivery keeps the outbox a small, fast hot table; keep-for-replay turns it into a partitioned archive. We will do both - a small hot outbox plus an async archive - and explain why.

Broker bandwidth:

30,000 events/sec * 1 KB avg = 30 MB/sec = ~240 Mbps at peak,
before replication fan-out. With replication factor 3 the broker
writes ~90 MB/sec internally. Well within a modest Kafka cluster.

Relay lag budget:

End-to-end p99 target = 2s. Budget:
  poll interval / CDC latency   ~200-500 ms
  batch publish + broker ack    ~50-200 ms
  mark-sent commit              ~10-50 ms
Headroom for retries and GC pauses leaves us comfortably under 2s.

The headline: capture is cheap (one INSERT per existing transaction). The engineering is entirely in the relay - sustaining 30-60k events/sec publish, keeping the hot outbox small, and making the inevitable at-least-once duplicates invisible. That is where the design spends everything.

High-Level Design (HLD)

The spine: a producing service writes its business row and an outbox row in one local ACID transaction. A relay processor (either polling the outbox or tailing the DB’s change log via CDC) reads committed-but-undelivered events, publishes them to a message broker with idempotent producer semantics keyed by aggregate, and marks them delivered only after broker ack. Consumers read from the broker and dedup on a stable event id. A reaper deletes delivered rows from the hot outbox after archiving them.

          ┌───────────────────────────────────────────────┐
          │              Producing Service                  │
          │  handle request -> BEGIN                        │
          │    INSERT/UPDATE business row                   │
          │    INSERT INTO outbox (event row)   <-- atomic  │
          │  COMMIT                                          │
          └───────────────┬───────────────────────────────┘
                          │  (two rows, one transaction)
                 ┌────────▼─────────────────────────────┐
                 │          Database (SQL primary)        │
                 │  business tables  |  outbox table      │
                 │  WAL / change log (for CDC option)     │
                 └───┬────────────────────────┬───────────┘
                     │ (A) poll SELECT          │ (B) CDC tail WAL
                     │     WHERE sent=false     │     (Debezium)
          ┌──────────▼──────────────────────────▼──────────┐
          │              Relay Processor                     │
          │  read undelivered batch (ordered per aggregate)  │
          │  publish to broker (idempotent producer,         │
          │     key = aggregate_id)                          │
          │  on broker ACK -> mark sent / advance offset     │
          │  retries + backoff + DLQ for poison events       │
          └───────────────┬─────────────────────────────────┘
                          │ produce (acks=all, idempotent)
                 ┌────────▼─────────────────────────────┐
                 │          Message Broker (Kafka)        │
                 │  topic partitioned by aggregate_id     │
                 │  replicated, durable log               │
                 └───┬────────────────────┬───────────────┘
                     │                    │
          ┌──────────▼──────┐   ┌─────────▼──────────┐
          │  Consumer A      │   │  Consumer B         │
          │  (billing)       │   │  (search index)     │
          │  dedup on         │   │  dedup on           │
          │  event_id         │   │  event_id           │
          └──────────────────┘   └─────────────────────┘

          ┌──────────────────────────────────────────────┐
          │  Reaper: archive + DELETE delivered rows from  │
          │  hot outbox (keeps SELECT WHERE sent=false fast)│
          └──────────────────────────────────────────────┘

The capture path (synchronous, inside the business request):

  1. The service handles a request and opens a transaction.
  2. It writes the business change (e.g. INSERT INTO orders ...).
  3. In the same transaction, it inserts one row per event into the outbox table, carrying a unique event_id, the aggregate_id (for ordering/keying), the event_type, and the serialized payload.
  4. It COMMITs. Either both rows are durable or neither is. The request returns. The service does not talk to the broker at all - that is deliberate.

The relay path (asynchronous, continuous):

  1. The relay discovers undelivered events - option A polls SELECT ... WHERE sent=false ORDER BY id LIMIT N, option B tails the DB write-ahead log via CDC so it sees every committed outbox INSERT without querying.
  2. For each event, it publishes to the broker with the idempotent producer enabled and key = aggregate_id so all events for one aggregate land on one partition and stay ordered.
  3. It waits for acks=all (the broker’s required replicas have the record durably).
  4. Only then does it mark the event delivered - polling sets sent=true (or deletes the row); CDC commits the consumer offset / LSN.
  5. If the broker call fails or is ambiguous, the relay retries the same event with the same producer key and sequence, which the broker deduplicates.

The consumer path:

  1. Consumers read their partitions, process each event, and record event_id in a processed-set (or rely on an idempotent write) so a redelivered event is a no-op.

The structural insight: the only atomic step is the local transaction that captures the event; everything after is an idempotent, retriable transport problem. We never attempt a distributed transaction between the DB and the broker, because we cannot have one. We replace “atomic across two systems” with “atomic capture, then idempotent delivery.”

Component Deep Dive

The hard parts, naive-first then evolved: (1) atomic capture without the dual-write, (2) the relay - polling, its ceiling, and the move to CDC, (3) exactly-once delivery over an at-least-once broker, (4) keeping the hot outbox small while preserving ordering and replay.

1. Atomic capture: killing the dual-write

The job: guarantee that a downstream event exists exactly when the business write it describes committed - never an event for a rolled-back write, never a committed write with no event.

Naive approach: write the DB, then publish the broker

def place_order(cart):
    order = db.insert(Order(items=cart.items, total=cart.total))  # (A) commit
    broker.publish("orders", OrderPlaced(order.id, order.total))  # (B) publish
    return order

Where it breaks:

  • Crash between A and B. The order is committed; the process dies before publishing. The order exists forever with no event. Billing never charges, search never indexes, and nothing threw an error. You find out from a customer.
  • Broker up, DB rolled back. Flip the order - publish first, then commit - and now a broker outage or a later ROLLBACK (constraint violation, deadlock retry) leaves an event for an order that does not exist. Consumers act on a phantom.
  • Retry makes it worse, not better. Wrapping B in a retry loop means an ambiguous publish (sent, but the ack was lost) gets published again - a duplicate - and if the whole request is retried, you may get duplicate orders and duplicate events. Retries convert “lost” into “duplicated”; they never give you “exactly once.”

There is no ordering of two independent commits that is safe. A failure can always land in the gap. This is the dual-write problem, and careful engineering cannot close a gap that is structural.

Evolved approach: one transaction, two rows (the outbox)

Stop writing to two systems in the request path. Write only to the DB, but write the event there too, atomically:

BEGIN;
  INSERT INTO orders (id, items, total, status)
    VALUES (:id, :items, :total, 'placed');

  INSERT INTO outbox (event_id, aggregate_id, aggregate_type,
                      event_type, payload, created_at, sent)
    VALUES (:event_id, :id, 'order', 'OrderPlaced',
            :payload_json, now(), false);
COMMIT;
  • Atomicity is free and local. Both rows are in the same database, so the same ACID transaction covers them. If the order commits, the outbox row commits. If anything rolls back, both vanish. There is no gap because there is no second system in this step.
  • The service never touches the broker. Publishing is now someone else’s job (the relay), reading only committed state. The request returns as soon as the local commit is durable - fast and simple.
  • event_id is generated now, at capture time, and is stable forever. It is the dedup anchor the whole exactly-once story hangs on. Generate it in the producing service (UUIDv7 or a {aggregate_id}:{seq} scheme), persist it, and it rides through the relay and the broker to the consumer unchanged.

The outbox table is just a durable, ordered to-do list of events to publish, written transactionally with the thing they describe. We have converted an impossible “atomic across two systems” into a trivial “atomic within one system plus a reliable copy job.” Everything hard now lives in the copy job - which is good, because that part we can make correct.

2. The relay: polling, its ceiling, and CDC

The job: continuously move committed-but-undelivered outbox rows to the broker, in per-aggregate order, keeping up with 30k events/sec and draining backlogs faster than real time, without ever skipping a row.

Naive approach: a single poller that selects, publishes, and updates one by one

while True:
    rows = db.query("SELECT * FROM outbox WHERE sent=false ORDER BY id LIMIT 500")
    for r in rows:
        broker.publish(r.topic, r.payload)
        db.execute("UPDATE outbox SET sent=true WHERE id=%s", r.id)
    sleep(0.2)

Where it breaks:

  • The WHERE sent=false scan rots. If delivered rows are not deleted, the table grows to billions and the index on sent becomes a huge low-cardinality scan. Even with a partial index, a growing table of mostly-sent rows makes each poll slower, right when you need it fast.
  • One-row-at-a-time UPDATE caps throughput. A round trip per event (publish, then update) cannot reach 30k/sec; you are latency-bound, not CPU-bound. Thousands of tiny UPDATEs per second also bloat the table with dead tuples and hammer vacuum/compaction.
  • A single poller is a SPOF and a serialization point. One instance cannot scale; two naive instances both SELECT the same rows and double-publish everything.
  • Polling latency floor. A 200ms sleep adds up to 200ms base latency even when idle, and tightening it to near-zero turns the poll into a busy-loop hammering the DB.

Polling works - and for modest volume it is the right, boring choice - but the naive single-threaded version hits a wall on throughput, table bloat, and concurrency safety.

Evolved approach A: concurrent, claim-based polling with batched marking and a reaper

Keep polling but fix each failure:

  • Claim rows so multiple relays do not collide. Use SELECT ... FOR UPDATE SKIP LOCKED so each poller grabs a disjoint batch:
BEGIN;
  SELECT * FROM outbox
    WHERE sent = false
    ORDER BY id
    LIMIT 500
    FOR UPDATE SKIP LOCKED;    -- other pollers skip these locked rows
  -- publish the batch to the broker, wait for acks ...
  UPDATE outbox SET sent = true WHERE id = ANY(:ids);  -- one batched update
COMMIT;

SKIP LOCKED lets N relay instances run concurrently, each taking a different slice, with no double-claim. Mark the whole batch in one UPDATE, not per row.

  • Partial index keeps the scan cheap. CREATE INDEX idx_outbox_undelivered ON outbox (id) WHERE sent = false; - the index only contains undelivered rows, so once the reaper deletes delivered ones it stays tiny regardless of total throughput.
  • Reaper deletes delivered rows. A background job archives then DELETEs rows where sent=true older than a few minutes (batched, to avoid long locks). The hot table stays at the ~1.8M-row size we estimated, so the poll query is always fast.
  • Order within a batch, ordered by id. Because we publish keyed by aggregate_id and the broker preserves per-partition order, and we read in id order per aggregate, ordering is preserved. (Two relays could publish two events of the same aggregate out of order if they land in different batches - fix: hash aggregate_id to a relay shard so one aggregate is always handled by one relay. More on this under ordering.)

This scales polling to the tens-of-thousands/sec range and removes the SPOF. For many systems you stop here.

Evolved approach B: CDC - let the database’s log be the outbox feed

At the top of our scale, polling still has costs: it queries the DB constantly, adds poll-interval latency, and the mark-sent UPDATE writes back to the same hot table. Change Data Capture removes the polling entirely by reading the database’s own write-ahead log.

  • Tail the WAL, do not query the table. A connector (Debezium on Postgres logical decoding, or MySQL binlog) streams every committed change to the outbox table as it happens. The relay consumes this stream - it learns about a new outbox row the instant its transaction commits, with no SELECT, no poll interval, and near-zero added latency.
  • No mark-sent write-back to the DB. The relay’s progress is a log offset / LSN, committed to the connector, not an UPDATE on the outbox table. The hot table takes zero extra write load from the relay; it is INSERT-only from the service and DELETE-only from the reaper.
  • Natural ordering and no missed rows. The WAL is the authoritative, totally-ordered record of commits. CDC cannot miss a committed row (it is in the log) and gives transaction-consistent ordering for free. Debezium’s outbox event router reads the outbox row and publishes it to the right topic with the right key directly.
  • The cost. CDC is operationally heavier: a connector cluster, logical replication slots (which, if the relay stalls, pin WAL and can fill the disk - a real failure mode to monitor and alarm on), and schema/format coupling to the DB’s log. Polling is simpler to run and debug.
DimensionPolling relayCDC relay
Added latencypoll interval (100-500ms)near-real-time (ms)
DB loadrepeated SELECT + mark UPDATEread WAL, no table queries
Throughput ceilingtens of k/sec (query-bound)very high (log-bound)
Operational costlow - just the service + a jobhigher - connector, repl slots
Failure modeslow polls, bloat if no reaperstalled slot pins WAL, fills disk
Orderingneeds sharding by aggregatetransaction-order from the log

The opinion: start with claim-based polling + reaper; it is simpler, and correct, and handles most systems. Move to CDC when you need sub-second end-to-end latency, when polling load on the DB is itself a problem, or when you are past ~20-30k events/sec. The outbox table and the capture code are identical either way - only the relay’s read mechanism changes - so this is a reversible decision, which is exactly why you start with the simpler one.

3. Exactly-once delivery over an at-least-once broker

The job: every event reaches the broker and its consumers, and a relay crash that re-publishes does not create a visible duplicate. The honest truth is the broker and relay can only promise at-least-once across a crash - so the design makes duplicates harmless.

Naive approach: publish, then mark sent, and assume it worked

broker.publish(topic, event)          # (1)
db.execute("UPDATE outbox SET sent=true WHERE id=%s", event.id)  # (2)

Where it breaks:

  • Crash between 1 and 2. The broker got the event; the relay dies before marking it sent. On restart the row is still sent=false, so the relay publishes it again. A duplicate event on the broker.
  • Ambiguous publish. The broker received the event but the ack was lost to a network blip. The relay does not know if it landed, so it retries - another duplicate - or gives up and loses it. The ack alone cannot disambiguate.
  • Mark-sent-first is worse. Reverse the order (mark sent, then publish) and a crash in the gap loses the event forever - sent=true with nothing on the broker. That violates zero-loss.

You cannot avoid the crash window. publish then mark risks duplicates; mark then publish risks loss. Since loss is unacceptable, we must choose the duplicate-risking order - and then eliminate the duplicates downstream. At-least-once is forced on us; our job is to make it look exactly-once.

Evolved approach: idempotent producer + stable key + consumer dedup

Three layers compose into effectively-exactly-once:

1. Idempotent producer at the broker (dedups relay retries). Enable the broker’s idempotent producer (enable.idempotence=true, acks=all). The producer attaches a producer id and a per-partition monotonic sequence number to every record. If the relay retries a publish after an ambiguous failure, the broker sees the same (producer id, sequence) and discards the duplicate - the record lands exactly once in the log despite multiple send attempts. This closes the “crash between publish and mark” and “ambiguous ack” windows at the broker layer, as long as it is the same producer session retrying.

2. Stable event_id as the application dedup key (dedups across everything else). The broker’s idempotent producer only dedups within a producer session. A relay restart is a new producer session, and consumers can still see a redelivery (e.g. the relay published, crashed before mark, restarted, re-read the row, re-published under a new producer id). So we carry the event_id generated at capture time in the record, and every consumer dedups on it:

def consume(event):
    if processed.contains(event.event_id):   # already handled
        return                                # no-op, safe
    with db.transaction():
        apply_business_effect(event)
        processed.add(event.event_id)         # same txn as the effect

The processed set is a table (or Redis with TTL) of seen event_ids, written in the same transaction as the side effect, so “did the work” and “recorded that I did it” commit together. A redelivered event finds its id already present and does nothing. This is the real exactly-once guarantee - it holds across relay restarts, broker edge cases, and consumer retries, because it is anchored on an id that is stable from capture to consumption.

3. Transactional outbox + idempotent consumer = end-to-end exactly-once effect. No single component achieves exactly-once; the composition does. Capture is atomic (no event for an uncommitted write). The relay is at-least-once (never loses, may duplicate). The idempotent producer removes most duplicates. The consumer’s event_id dedup removes the rest. The net effect a downstream service observes is: every committed write produces exactly one applied effect.

A note on Kafka transactions: Kafka’s own exactly-once (transactional producer + read-process-write) covers Kafka-to-Kafka pipelines, not DB-to-Kafka - it cannot enroll your Postgres transaction. So for the outbox, the DB transaction gives capture atomicity and the idempotent producer + consumer dedup give delivery exactly-once-effect. Do not reach for Kafka transactions expecting them to solve the dual-write; they are a different seam.

Ordering, tied in: we publish with key = aggregate_id, so all events for one order go to one partition and the broker keeps them in offset order. With the idempotent producer, max.in.flight.requests.per.connection can stay at 5 without reordering on retry (the broker enforces sequence order). For the polling relay, we additionally hash aggregate_id to a relay instance so two relays never publish the same aggregate’s events concurrently out of order. Per-aggregate order is preserved end to end; cross-aggregate order is not promised and does not need to be.

4. Keeping the hot outbox small, with ordering and replay intact

The job: the outbox must stay a small, fast table for the relay, yet we often also want to replay history (new consumer, bug reprocess) and audit what was emitted - two goals that pull in opposite directions.

Naive approach: one table, keep everything, or delete immediately

  • Keep everything forever: the table grows to billions of rows, the undelivered scan (even partial-indexed) sits on a bloated heap, vacuum/compaction never catches up, and backups balloon. The relay slows as the archive grows.
  • Delete the instant you publish: the hot table stays tiny, but you have thrown away the one durable record of what you emitted. A new consumer joining next week, or a consumer that needs to reprocess after a bug, has nothing to replay from the source. And an aggressive delete racing the mark-sent can drop an un-acked event.

Either extreme sacrifices one of {fast relay, replayable history}.

Evolved approach: small hot outbox + the broker (or an archive) as the replay log + partitioned retention

Separate the two jobs by giving each to the system built for it:

  • The hot outbox is a queue, not an archive. It holds only undelivered and very-recently-delivered rows. A reaper runs continuously: it archives delivered rows (ship them to the broker’s own long-retention topic or to object storage / a partitioned history table), then batch-DELETEs them a few minutes after sent=true. The few-minute grace window means a delete never races an in-flight publish. The hot table stays at ~1.8M rows, so the relay query/scan is always fast.
  • The broker is the replay log. Set the events topic to long retention (days to weeks) or make it log-compacted keyed by aggregate_id for latest-state replay. A new consumer just subscribes from the earliest offset and replays - it does not re-read the outbox. This is what Kafka’s durable log is for; do not reinvent replay in the DB.
  • Partition the archive by time. If you keep a DB-side history table for audit, partition it by created_at (daily/weekly). Old partitions are cheap to drop whole (DROP PARTITION) instead of mass-deleting rows, and never shard by time for the hot path (it concentrates all current writes on the newest partition) - time-partitioning is right only for the append-only, read-rarely archive.
  • Ordering under reaping. Reaping touches only sent=true rows; the relay reads only sent=false. They never contend for the same rows, so deletion cannot reorder or drop undelivered work. Per-aggregate order is a property of the publish key and the relay sharding, untouched by retention policy.

Why this is right: a queue and an archive have opposite access patterns - the queue wants to be small and churny, the archive wants to be large and immutable - so forcing both into one table makes both bad. Give the hot path a small outbox, give replay to the broker’s log, give audit to a time-partitioned archive, and each is simple and fast.

API Design & Data Schema

API

The outbox has almost no external API - its “API” is the transaction contract the producing service follows and the event envelope consumers receive. The operational endpoints are for monitoring and control.

Producer-side contract (library/SDK, not a network call): the service calls a helper that enforces “insert the outbox row in the current transaction”:

emit_event(txn, aggregate_id, aggregate_type, event_type, payload)
  -> inserts one outbox row inside the caller's open transaction
  -> returns the generated event_id
  // MUST be called inside the same txn as the business write;
  // the SDK asserts an active transaction and refuses otherwise.

The event envelope delivered to the broker / consumers:

{
  "event_id":       "0193c7a1-...-uuidv7",   // stable dedup key, from capture
  "aggregate_id":   "order_8821",            // partition/order key
  "aggregate_type": "order",
  "event_type":     "OrderPlaced",
  "occurred_at":    "2026-12-02T09:04:00Z",
  "sequence":       42,                        // per-aggregate monotonic
  "payload":        { "order_id": "8821", "total": 250000, "currency": "INR" },
  "trace_id":       "..."                      // propagated for observability
}

Operational / monitoring endpoints (relay control plane):

GET  /relay/health            -> relay up, connected to DB and broker
GET  /relay/lag               -> { backlog_rows, oldest_undelivered_age_ms,
                                    publish_rate, end_to_end_p99_ms }
GET  /relay/dlq               -> events that failed N publish attempts
POST /relay/dlq/{event_id}/retry   -> re-queue a poison event after a fix
POST /relay/pause | /resume   -> stop/start publishing (for maintenance)
GET  /outbox/{event_id}       -> inspect a single event's capture + delivery state

The key metric is oldest_undelivered_age_ms (relay lag) - if it climbs, the relay is falling behind and end-to-end latency is blowing the budget. Alert on it directly.

Data stores

1. Outbox + business tables - SQL, same database, ACID. The entire pattern depends on the outbox row and the business row sharing one transaction, which is only possible if they are in the same relational database (same ACID scope). This is non-negotiable and is the reason the core is SQL (PostgreSQL, MySQL, or distributed SQL like CockroachDB/Spanner). You cannot put the outbox in a different DB or in NoSQL-without-shared-transactions and keep atomic capture.

Table: outbox                          -- the hot queue; small, churny
  id             BIGSERIAL  PRIMARY KEY          -- monotonic, relay read order
  event_id       UUID       UNIQUE NOT NULL      -- stable dedup key
  aggregate_id   STRING     NOT NULL             -- partition / ordering key
  aggregate_type STRING     NOT NULL
  event_type     STRING     NOT NULL
  payload        JSONB      NOT NULL             -- serialized event body
  headers        JSONB                           -- trace_id, schema version
  sequence       BIGINT                          -- per-aggregate monotonic
  created_at     TIMESTAMP  NOT NULL DEFAULT now()
  sent           BOOLEAN    NOT NULL DEFAULT false
  sent_at        TIMESTAMP  NULL
  attempts       INT        NOT NULL DEFAULT 0

  Index: idx_outbox_undelivered ON (id) WHERE sent = false   -- partial, tiny
  Index: idx_outbox_sent_at     ON (sent_at) WHERE sent = true -- for reaper

Table: processed_events                -- consumer-side dedup set (per consumer)
  consumer       STRING
  event_id       UUID
  processed_at   TIMESTAMP  DEFAULT now()
  PRIMARY KEY (consumer, event_id)
  -- TTL/partition by processed_at; retain > max possible redelivery window

Table: outbox_archive                  -- optional audit history, partitioned
  event_id       UUID
  aggregate_id   STRING
  event_type     STRING
  payload        JSONB
  created_at     TIMESTAMP
  PARTITION BY RANGE (created_at)       -- daily; DROP old partitions cheaply
  • The partial index on WHERE sent=false is the single most important index: it is the relay’s read path, and because it only holds undelivered rows, it stays tiny no matter how many events have flowed through.
  • event_id UNIQUE is both the dedup anchor and a safety net - a bug that tries to insert the same event twice is caught by the constraint.
  • attempts drives the DLQ: past a threshold, the relay stops retrying and flags the row for the dead-letter path.

2. Message broker - Kafka (durable, partitioned log). Topics partitioned by aggregate_id (per-aggregate order), replication factor 3, acks=all, idempotent producer on, long retention or log-compaction for replay. This is the delivery substrate and the replay log.

3. Consumer dedup store - SQL table or Redis. processed_events above, or a Redis set with TTL per consumer if the dedup window is short and the consumer can tolerate the loss-on-flush risk (prefer the DB table when the side effect is itself a DB write, so dedup and effect share a transaction).

Why SQL for the core and a log broker for transport: atomic capture requires a shared transaction, which only a single relational DB gives you - so the outbox is SQL, full stop. Transport, fan-out, ordering-per-key, and replay are exactly what a partitioned, replicated log is built for - so delivery is Kafka. Each system does the one job it is good at; the relay is the thin, idempotent bridge between them.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix.

1. The dual-write (breaks first, worst impact). DB committed, broker publish lost (or vice versa) - a silent, error-free inconsistency. Fix: the transactional outbox - the event row is INSERTed in the same local transaction as the business write, so capture is atomic. The relay publishes from committed state only. There is no gap because there is no second system in the capture step. This is the whole reason the pattern exists.

2. Relay throughput ceiling / table bloat. A naive single poller with per-row UPDATEs and no cleanup cannot sustain 30k/sec and the sent=false scan rots as the table grows. Fix: claim-based concurrent polling (FOR UPDATE SKIP LOCKED) across N relay instances, batched mark-sent, a partial index on undelivered rows, and a reaper that deletes delivered rows so the hot table stays ~1.8M rows. Past this, CDC (tail the WAL) removes the polling load and raises the ceiling to log-bound.

3. Duplicate events across a relay crash. At-least-once means a crash between publish and mark re-publishes. Fix: idempotent producer (producer id + sequence number) dedups retries at the broker within a session; a stable event_id carried from capture plus consumer-side dedup in the same transaction as the side effect removes duplicates across sessions. The composition yields exactly-once effect. Never mark-sent before the broker ack (that risks loss); always publish-then-mark and dedup downstream.

4. Hot aggregate / hot partition. A single very active aggregate (one giant account) serializes all its events onto one partition and one relay shard, capping its throughput and creating lag on that key. Fix: per-aggregate order only needs to hold where it matters - for a pathological hot key, consider a composite key (aggregate_id + sub-stream) if the consumer can tolerate relaxed ordering within the aggregate, or ensure the hot aggregate’s events are cheap to process so the single partition keeps up. Monitor per-partition lag, not just global lag.

5. Relay as a single point of failure. One relay instance stalls and all delivery stops; events pile up durably but end-to-end latency blows up. Fix: run multiple stateless relay instances with SKIP LOCKED (polling) or a partitioned CDC consumer group (CDC) so one instance’s death is covered by the others; leader election / shard reassignment on failure. The outbox is durable, so a relay outage adds latency but never loses events - but alarm on oldest_undelivered_age_ms so you catch a stalled relay fast.

6. CDC replication slot pins the WAL. If the CDC relay stalls (broker down, bug), Postgres cannot recycle WAL the slot still needs, and the DB disk fills - taking down the producing database. Fix: monitor replication-slot lag and WAL disk usage with hard alarms; set max_slot_wal_keep_size so a runaway slot is dropped before it fills the disk (accepting that you then must resnapshot); have a runbook. This failure mode is the main operational tax of CDC and the reason polling is the safer default until you need CDC’s latency.

7. Backlog drain after an outage. The broker was down an hour; 108M events are queued in the outbox. Fix: design the relay for 2x peak throughput (our ~60k/sec target) so a one-hour backlog drains in ~one hour, not a day; scale relay instances up during drain; ensure the partial index and reaper keep the table fast even at backlog size. Ordering is preserved because we still read in id order per aggregate.

8. Consumer dedup store growth. The processed_events set grows unbounded if never trimmed. Fix: TTL / time-partition the dedup set to the maximum realistic redelivery window (hours to a day - far longer than any crash-and-retry gap, far shorter than forever). Drop old partitions. An event_id older than the window will not be redelivered, so forgetting it is safe.

9. Schema evolution of the payload. A changed event shape breaks consumers reading old and new events. Fix: version the envelope (schema_version in headers), use a backward-compatible serialization (Avro/Protobuf with a registry), and have consumers tolerate unknown fields. The outbox stores whatever the producer serialized; evolution is a consumer contract concern, out of this core but flagged.

Shard keys / partitioning, stated plainly: the broker topic partitions by aggregate_id (co-locates and orders one aggregate’s events, spreads load across aggregates). The polling relay shards work by hashing aggregate_id to an instance (so one aggregate is handled by one relay, preserving order). The outbox table itself does not need sharding for throughput at 30k inserts/sec on a single primary - it needs the partial index and the reaper. If a single DB primary cannot hold the write volume, the service itself is sharded by aggregate_id and each shard carries its own outbox and relay - the pattern composes per shard. The archive partitions by created_at (time) because it is append-only and aged-out whole; never time-partition the hot path.

Wrap-Up

The trade-offs that define this design:

  • No distributed transaction, so atomic capture plus idempotent delivery. The DB and the broker cannot commit together, so we never try. We make the event atomic with the business write inside one local transaction, then treat publishing as a separate, retriable transport problem over committed state. The dual-write disappears because the capture step has exactly one system in it.
  • At-least-once is forced, so we make duplicates harmless. Across a crash the relay can only promise at-least-once (publish-then-mark, because mark-then-publish risks loss). We accept duplicates and erase their effect with an idempotent producer and a stable event_id that consumers dedup on in the same transaction as their side effect. Exactly-once is an emergent property of the composition, not of any one box.
  • Polling first, CDC when you need it. Claim-based polling with a partial index and a reaper is simpler, safe, and enough for most systems. CDC buys sub-second latency and removes DB query load at the top of the scale, at the cost of connector ops and the replication-slot-pins-WAL failure mode. The outbox and capture code are identical either way, so it is a reversible choice - start simple.
  • A small hot outbox, with the broker as the replay log. The outbox is a queue, not an archive: keep it tiny with a reaper, give replay to the broker’s durable log, give audit to a time-partitioned archive. Opposite access patterns get opposite systems.

One-line summary: capture every event in the same local transaction as the business write it describes, then run an idempotent, horizontally-scaled relay (claim-based polling or CDC) that publishes to a partitioned broker keyed by aggregate and marks rows sent only after broker ack - so every committed write produces exactly one delivered effect, with no dual-write inconsistency and no lost or visibly-duplicated events across service boundaries.