> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# External integration (outbox, CDC, sagas)

> An order management system never operates in isolation.

An order management system never operates in isolation. Every significant state change must reach other systems: a payment processor to capture funds, a warehouse management system (WMS) to pick and pack, a carrier to ship, and a notification service to email the customer. The database is the system of record; those other systems are the systems of action. This page addresses the boundary between them.

This page defines the delivery invariant, shows how to uphold it on CockroachDB with the Transactional Outbox pattern, and then covers the two delivery mechanisms (changefeeds and pollers), the inbox for inbound callbacks, sagas for multi-service workflows, reconciliation for drift, and cleanup. Read [Transactions & SQL](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md) first. The outbox depends on each of these operations occurring inside one `SERIALIZABLE` transaction.

## The core invariant and the dual-write problem

**Invariant.** Every committed business change that must reach an external system is delivered **at least once**, and **nothing is ever sent for a change that rolled back.**

**WHY.** These are the only two failure modes that corrupt a distributed order flow, and they are opposites:

* **Lost change.** The database commits an order as `paid`, but the "charge the card" message never reaches the processor. The customer holds a paid order that was never charged.
* **Phantom change.** The processor is called and funds are captured, but the transaction that was to record the capture rolls back. A card is charged for an order that, as far as the database is concerned, does not exist.

Both arise from the same root cause: **the dual write.** The defect, written the obvious way:

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  UPDATE orders SET status = 'paid' WHERE id = $order_id;
COMMIT;                              -- (1) database commit
publish_to_kafka("order.paid", ...) -- (2) separate external call
```

There is no atomic bracket around (1) and (2). If the process dies between them, the commit stands and the message is lost. Reversing the order, publishing first and then committing, leaves a message already in flight that describes a change that never happened if the commit at (1) rolls back. No ordering of two independent side effects is safe, because the failure window falls *between* them and cannot be reduced to zero.

> [!CAUTION]
>
> **Never write to the DB and call the external system in two separate steps**
> A database transaction and a network call to another system cannot be made atomic with each other. Any code that commits a row and then publishes a message (or publishes and then commits) has a crash window that violates the invariant. The solution is not retries or ordering adjustments. Make the intent to publish part of the same transaction as the business change. That is the outbox.

## The Transactional Outbox pattern

**Invariant.** The decision *that* a message must be sent is committed in the **same transaction** as the business change it describes. Whether it has *actually* been sent is tracked separately and happens after commit.

**WHY.** CockroachDB can atomically write the `orders` row, the `order_events` row, and an `outbox` row together under one `SERIALIZABLE` transaction. Either all commit or none do. The outbox row therefore exists **if and only if** the business change committed. This is what makes at-least-once delivery possible without phantom sends: a relay that later reads committed outbox rows can never see a row for a rolled-back change.

### DDL

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE outbox (
  id            UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  aggregate     STRING NOT NULL,          -- 'order', 'shipment', ...
  aggregate_id  UUID   NOT NULL,          -- e.g. the order id
  event_type    STRING NOT NULL,          -- 'order.paid', 'order.shipped'
  payload       JSONB  NOT NULL,          -- the full message body
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  -- delivery bookkeeping (used by the poller variant; see below)
  published_at  TIMESTAMPTZ,              -- NULL = not yet delivered
  INDEX unsent_idx (created_at) WHERE published_at IS NULL
);
```

The write occurs as part of the business transaction, as one atomic unit:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  UPDATE orders
     SET status = 'paid', updated_at = now()
   WHERE id = $order_id AND status = 'created';   -- guarded transition; 0 rows = reject

  INSERT INTO order_events (order_id, seq, from_state, to_state, actor, occurred_at)
    VALUES ($order_id, $seq, 'created', 'paid', 'payments', now());

  INSERT INTO outbox (aggregate, aggregate_id, event_type, payload)
    VALUES ('order', $order_id, 'order.paid',
            jsonb_build_object('order_id', $order_id, 'amount', $amount));
COMMIT;
```

> [!TIP]
>
> **Partial index on unsent rows**
> `INDEX ... WHERE published_at IS NULL` keeps the poller's scan for unsent work inexpensive even when the table holds millions of already-delivered rows, because the index contains only the backlog. Combine it with [Row-Level TTL](#cleanup-with-row-level-ttl) to prevent the table from growing without bound. Note that at high write rates this same time-ordered tail becomes a write hotspot; see "High volume" under the poller relay below for the sharded variant.

Once the outbox row is committed, delivery is a separate concern with two implementations.

### (a) Changefeed-driven relay (CockroachDB-native)

**Invariant.** A changefeed emits a message for every committed change to a watched table, so the database itself is the relay: no application poller exists.

Create a changefeed that watches the `outbox` table (or the business tables directly) and streams rows to an external sink:

> [!NOTE]
>
> **Enable rangefeeds first**
> Changefeeds require `kv.rangefeed.enabled`, which may be off by default. Set it once per cluster before creating a feed, or `CREATE CHANGEFEED` fails with *"rangefeeds require the kv.rangefeed.enabled setting"*:
>
> ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SET CLUSTER SETTING kv.rangefeed.enabled = true;
> ```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Production: emit INTO a sink.
CREATE CHANGEFEED FOR TABLE outbox
  INTO 'kafka://broker:9092?topic_prefix=om_'
  WITH updated, resolved = '10s', min_checkpoint_frequency = '10s';
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Prototyping only: a "sinkless" feed streams rows back to the SQL client.
CREATE CHANGEFEED FOR TABLE outbox WITH updated;
```

A **sinkless** changefeed (`CREATE CHANGEFEED FOR TABLE ...`) returns rows to the SQL session and is for experimentation. A **sinked** changefeed (`... INTO 'sink'`) is the production form; supported sinks are **Kafka, webhook, cloud storage, and Google Cloud Pub/Sub.** Feeds are managed as jobs with `PAUSE`, `RESUME`, `ALTER`, and `CANCEL`. ([Change Data Capture Overview](https://docs.cockroachlabs.com/docs/stable/change-data-capture-overview.md))

The advantage is operational: there is no relay service to write, deploy, scale, monitor, or keep from falling behind. CockroachDB tracks progress (the high-water mark) durably inside the job, survives restarts, and resumes where it left off. The feed can be pointed at the business tables directly, skipping the `outbox` table entirely, though an explicit `outbox` provides one stable message schema rather than exposing the table layout to every downstream consumer.

> [!NOTE]
>
> **Enterprise licensing: confirm before you rely on it**
> The exact Enterprise-license gating of changefeed **sinks** under the current CockroachDB Software License is a licensing detail that changes over releases. Confirm what your cluster's license permits before designing around sinked changefeeds. ([Licensing FAQs](https://docs.cockroachlabs.com/docs/stable/licensing-faqs.md))

### (b) Poller-driven relay

**Invariant.** A worker reads committed-but-unsent `outbox` rows, publishes them, and marks them sent, so delivery logic lives entirely in your application.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Claim a batch of unsent rows (uses the partial index).
SELECT id, event_type, payload
  FROM outbox
 WHERE published_at IS NULL
 ORDER BY created_at
 LIMIT 100
 FOR UPDATE SKIP LOCKED;     -- claim disjoint rows; see High volume below

-- ... publish each to the external system ...

UPDATE outbox SET published_at = now() WHERE id = ANY($ids);
```

The poller provides full control: the sink protocol, batching, retry policy, and payload transformation are all defined in ordinary application code, and no changefeed license is required. The cost is ownership of a service, including its liveness, its lag, its scaling, and the `FOR UPDATE SKIP LOCKED` coordination between workers, plus a steady read load against the `outbox` table to discover work.

> [!WARNING]
>
> **High volume: a single time-ordered poller is an anti-pattern**
> Two properties of the simple poller do not scale. Every new row lands at the tail of the `created_at` index, which concentrates inserts on one range (a write hotspot), and a single time-ordered claim tends to funnel all workers at the same head rows. The term "outbox" and the pattern are correct; at high write rates, parallelize it:
>
> * **Shard the outbox.** Add a `bucket` column (for example `bucket INT2`, set at insert from a hash of the aggregate id), or a [hash-sharded index](https://docs.cockroachlabs.com/docs/stable/hash-sharded-indexes.md), so inserts spread across ranges instead of piling onto one tail.
> * **Assign buckets to workers.** Each worker claims only its buckets with `FOR UPDATE SKIP LOCKED`, so pollers drain in parallel without contending for the same rows.
> * **Or use the changefeed relay instead.** A changefeed has no application poller and no claim contention, so it avoids both limits (see the changefeed option above).
> * **Or use a purpose-built queue** on CockroachDB such as [FabMQ](https://github.com/fabiog1901/fabmq), which implements sharded, parallel claiming for you.

> [!WARNING]
>
> **Mark-sent is itself not atomic with the publish**
> A poller publishes, then updates `published_at`. If it crashes in between, the row is republished on the next pass. This is **expected** and is why the invariant is at-*least*-once: the duplicate is normal, and downstream consumers must deduplicate (see the inbox and idempotency sections). Do not attempt to make "publish then mark sent" atomic. It is the same unsolvable dual-write, relocated.

## Changefeed delivery semantics you must design for

Build consumers around the following guarantees, not around assumed behavior. ([Changefeed Messages](https://docs.cockroachlabs.com/docs/stable/changefeed-messages.md))

* **At-least-once delivery.** Every row change is emitted one *or more* times. There is no exactly-once.
* **Per-key ordering only, on first emission.** Messages for a single primary key arrive in timestamp order *the first time each is emitted*. There is **no total ordering and no transactional ordering** across keys: two rows written in the same SQL transaction may arrive in either order, arbitrarily far apart.
* **Duplicates are possible.** A node restart, a `PAUSE`/`RESUME`, a schema change, or `min_checkpoint_frequency` can all cause a row to be re-emitted. Duplicates are not an error condition; they are part of the contract.
* **`resolved` timestamps are the consistency barrier.** A `resolved` timestamp is a high-water mark: every change at or below it has already been emitted. Nothing below a resolved timestamp will appear later. Use it as a checkpoint: everything up to a resolved timestamp may safely be acted on, aggregated, or snapshotted, with the guarantee that no earlier change is still in flight.

**The consumer rule that follows:** consumers **must be idempotent**, and the way to achieve idempotency is to **deduplicate by primary key plus the `updated` timestamp.** The `updated` column (enabled with `WITH updated`) stamps each message with the MVCC timestamp of the change. The pair `(key, updated)` uniquely identifies a specific version of a row. If that pair has already been processed, drop the message.

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
on message(key, updated, payload):
    if seen(key, updated):          # dedupe table keyed by (key, updated)
        ack and return              # duplicate, safe to drop
    apply(payload)                  # your side effect, done once per (key, updated)
    record_seen(key, updated)
    ack
```

> [!WARNING]
>
> **Do not assume order across keys**
> Treat `order.paid` and `order.shipped` as potentially arriving out of order, including `shipped` before `paid`. Make each consumer action commutative, or guard it with a state check (`WHERE status = 'paid'`), following the same monotonic-advance discipline used for state transitions in [Transactions & SQL](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md). Never encode "paid must arrive before shipped" as an assumption; encode it as a guard.

## Inbox pattern for inbound callbacks

**Invariant.** An inbound external event (a payment webhook, a carrier status callback) is processed **exactly once** regardless of how many times the provider delivers it.

**WHY.** Providers are at-least-once as well. A payment processor retries its webhook until it receives a `2xx`, so duplicate "charge succeeded" callbacks will arrive. A `UNIQUE` constraint on the provider's event id turns deduplication into a database guarantee rather than application logic. ([UNIQUE constraints](https://docs.cockroachlabs.com/docs/stable/unique.md) enforce this at write time.)

This is the mirror image of the outbox: the outbox makes *outbound* delivery safe; the inbox makes *inbound* delivery safe. The payment side is covered in [Transactions & SQL: Handle duplicate payment callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md). The general form uses a dedicated `processed_events` inbox:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE processed_events (
  provider          STRING NOT NULL,         -- 'stripe', 'fedex', ...
  provider_event_id STRING NOT NULL,         -- the id the provider assigns
  order_id          UUID,
  kind              STRING NOT NULL,
  payload           JSONB,
  received_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
  CONSTRAINT pk_processed PRIMARY KEY (provider, provider_event_id)
);
```

The handler performs a no-op-on-conflict insert **in the same transaction** as the effect the event drives:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  INSERT INTO processed_events (provider, provider_event_id, order_id, kind, payload)
    VALUES ('stripe', $eid, $order_id, 'payment.captured', $body)
    ON CONFLICT (provider, provider_event_id) DO NOTHING;
  -- If 0 rows inserted, this event was already processed: COMMIT and return 200. Do nothing else.
  -- If 1 row inserted, apply the effect (guarded transition) here, in THIS transaction:
  UPDATE orders SET status = 'paid', updated_at = now()
   WHERE id = $order_id AND status = 'created';
COMMIT;
```

Because the dedupe row and the effect commit together, the event cannot be recorded as processed without applying the effect, and the effect cannot be applied twice.

## Sagas and compensating actions

**Invariant.** A workflow that spans multiple services has **no distributed transaction**. Consistency is reached by forward progress plus **compensations**, not by rolling back across systems.

**WHY.** The `orders`, `order_events`, and `outbox` writes can be made atomic because they are all in one CockroachDB cluster. "Reserve inventory," "capture payment," and "create shipment" cannot be placed in one transaction: the payment processor exposes no `ROLLBACK`, and a database transaction cannot be held open across three network round-trips to external systems. Decompose the workflow into local steps, each with a defined **compensating action** that semantically undoes it.

**Worked example: order fulfillment saga.**

1. **Reserve inventory** (local transaction + outbox `inventory.reserved`). Compensation: `inventory.release`.
2. **Capture payment** (external call, recorded via inbox on callback). Compensation: `payment.refund`.
3. **Create shipment** (external call to WMS/carrier). Compensation: `shipment.cancel`.

Suppose step 2 fails: the capture is declined **after** inventory was reserved. Do **not** attempt to roll back step 1 by reversing the entire flow. Emit the **compensation for the steps that succeeded**:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  UPDATE orders SET status = 'payment_failed', updated_at = now()
   WHERE id = $order_id AND status = 'awaiting_payment';
  INSERT INTO outbox (aggregate, aggregate_id, event_type, payload)
    VALUES ('order', $order_id, 'inventory.release',
            jsonb_build_object('order_id', $order_id, 'sku', $sku, 'qty', $qty));
COMMIT;
```

The `inventory.release` message flows through the same outbox and at-least-once delivery, so the inventory service must apply it idempotently (releasing an already-released reservation is a no-op). Each compensation is another business change plus outbox write, and inherits the full mechanism already built.

> [!TIP]
>
> **Design compensations as commutative no-ops**
> A compensation can be delivered more than once (at-least-once) and may race with a late success of the step it compensates. Make "release reservation" idempotent and safe to apply out of order, exactly like any other changefeed consumer action.

## Reconciliation

**Invariant.** The local system of record and each external system **converge** even after lost messages, bugs, or manual intervention. Periodically, a job detects drift and emits compensations to close it.

**WHY.** At-least-once delivery plus idempotency handles the common failures but not all of them: a consumer bug can drop a message, an operator can cancel a shipment directly in the WMS, or a compensation can be lost during an outage. Reconciliation is the backstop. A periodic job pulls external state (open captures from the processor, shipments from the WMS) and compares it to local state, emitting compensations or corrections for any mismatch.

These scans are large and read-only, and must not take locks or contend with live order traffic. Run them as **non-blocking historical reads** with `AS OF SYSTEM TIME` and follower reads. ([Follower Reads](https://docs.cockroachlabs.com/docs/stable/follower-reads.md))

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Non-blocking scan of orders stuck awaiting shipment, read from a follower.
SELECT id, status, updated_at
  FROM orders
  AS OF SYSTEM TIME follower_read_timestamp()
 WHERE status = 'paid'
   AND updated_at < now() - INTERVAL '1 hour';
```

For each drifted order (paid long ago but with no shipment confirmed), the job emits the appropriate forward action or compensation through the outbox. Reconciliation is slow and coarse. It is the floor under correctness, not the primary path.

## Cleanup with Row-Level TTL

**Invariant.** Delivered `outbox` rows and old `processed_events` rows are garbage-collected automatically, so these tables do not grow without bound.

Use **Row-Level TTL**, which runs a background job to delete expired rows. ([Row-Level TTL](https://docs.cockroachlabs.com/docs/stable/row-level-ttl.md))

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- GC outbox rows 24h after they were delivered.
ALTER TABLE outbox SET (
  ttl_expiration_expression = $$ (published_at AT TIME ZONE 'UTC') + INTERVAL '24 hours' $$,
  ttl_job_cron = '@hourly'
);

-- GC processed_events 30 days after receipt.
ALTER TABLE processed_events SET (
  ttl_expiration_expression = $$ (received_at AT TIME ZONE 'UTC') + INTERVAL '30 days' $$
);
```

> [!WARNING]
>
> **TTL deletion is batched and background, not immediate**
> The TTL job runs on a schedule (`ttl_job_cron`, default `@daily`) and deletes in batches. An expired row is **not** removed the instant it expires. Never treat absence-by-TTL as a correctness mechanism: a row past its TTL may still be present and readable until the next job pass. Keep the inbox dedupe window (for example, 30 days) comfortably longer than any provider's retry horizon, or a late duplicate will be reprocessed as new. Prefer `ttl_expiration_expression` over a fixed column-age TTL so that rows are garbage-collected on *delivery* time, not *creation* time.

## Tradeoffs: changefeed vs poller

Both mechanisms uphold the same invariant (at-least-once, no phantom sends) because both read only committed outbox rows. They differ in who operates the relay and what can be controlled.

**Operational ownership.** The changefeed is run *by the database*. CockroachDB tracks the high-water mark durably, survives node restarts, resumes automatically, and exposes the feed as a job that is managed with `PAUSE`, `RESUME`, `ALTER`, and `CANCEL`. No relay service is written. The poller is operated by the application: it is deployed, scaled, and monitored for lag, and competing workers are coordinated with `FOR UPDATE`. If it fails, delivery stops until the failure is noticed. Fewer moving parts favors the changefeed for most teams.

**Control and transformation.** The poller is preferable when rich per-message logic is required (custom protocols, complex payload shaping, conditional routing, or provider-specific retry and backoff), because it is ordinary application code. A changefeed emits a fixed message shape to one of four sink types (Kafka, webhook, cloud storage, Pub/Sub). If the downstream consumer accepts one of those, the changefeed suffices, but it is less flexible than code.

**Load profile.** The poller pays a continuous read cost to *discover* work: it must scan for unsent rows even when nothing has changed (mitigated, but not eliminated, by the partial index). The changefeed is push-based: CockroachDB emits as changes occur, so there is no polling-interval latency and no idle scan load. For high-throughput order flows, the changefeed is both lower-latency and lower-overhead.

**Licensing.** The poller needs no changefeed license; it is plain SQL. Sinked changefeeds may be gated by license tier; confirm against the [Licensing FAQs](https://docs.cockroachlabs.com/docs/stable/licensing-faqs.md) before committing. This is sometimes the deciding factor regardless of the technical merits.

**Delivery semantics are identical downstream.** **Neither choice relaxes the consumer's obligations.** Both are at-least-once. Both can produce duplicates. Neither provides total or transactional ordering. Whichever relay is chosen, the consumer must deduplicate by `(key, updated)`, guard state transitions, and treat cross-key ordering as arbitrary. Choosing changefeed versus poller is an operations and control decision. It is **not** a way to avoid building idempotent consumers. A design that relies on the relay to deliver exactly once or in order is incorrect on either mechanism.

**Default recommendation.** Start with the changefeed-driven relay: less code, durable progress tracking, lower latency, and push-based delivery. Use the poller when transformation or routing exceeds what the sinks can express, when licensing rules out sinked changefeeds, or when an existing queue infrastructure already owns delivery and only needs to be fed. In both cases, the outbox, inbox, sagas, reconciliation, and TTL cleanup around the relay remain the same.
