Skip to main content
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 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:
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

The write occurs as part of the business transaction, as one atomic unit:
[!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 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”:
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) 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)

(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.
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, 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, 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)
  • 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.
[!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. 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 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. The general form uses a dedicated processed_events inbox:
The handler performs a no-op-on-conflict insert in the same transaction as the effect the event drives:
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:
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)
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)
[!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 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.