> ## 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.

# Payments & callbacks

> Payment processing is where an order-management system interacts with real money through an external system.

Payment processing is where an order-management system interacts with real money through an external system. The invariants:

> **At most one successful authorization and one capture per order attempt. Refunds never exceed captures. A payment that succeeded at the provider is never lost from your records.**

Payment processing is external, asynchronous, and retried by design. The system calls a provider, and the call may time out after the money has moved. The provider sends webhooks that are at-least-once, can arrive out of order, and can be delayed by minutes. The mechanisms on this page exist to make this correct.

## The boundary: who is authoritative for what

Define this boundary explicitly to avoid double charges.

* **The payment provider is authoritative for money movement.** Whether a card was actually charged is their truth, not yours.
* **CockroachDB is authoritative for your intent and your recorded outcome.** What you *meant* to charge, and what you *believe* happened, lives in your database.

Everything below keeps the two in agreement without assuming they cannot diverge.

## Record intent before you call out

Create the payment record *before* calling the provider, keyed by an **idempotency key that the application generates** and sends to the provider. If the call times out and is retried, the provider deduplicates on that key, which prevents a double charge.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE payment_transactions (
  id              UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  order_id        UUID NOT NULL REFERENCES orders(id),
  idempotency_key STRING NOT NULL UNIQUE,     -- sent to the provider
  state           STRING NOT NULL DEFAULT 'initiated'
                  CHECK (state IN ('initiated','authorized','captured','failed','refunded')),
  amount          DECIMAL(18,2) NOT NULL,
  currency        CHAR(3) NOT NULL,
  refunded_amount DECIMAL(18,2) NOT NULL DEFAULT 0
                  CHECK (refunded_amount >= 0 AND refunded_amount <= amount),
  provider_ref    STRING,                     -- the provider's own id
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

The `UNIQUE` constraint on `idempotency_key` guarantees that one logical payment attempt yields one row. The `CHECK (refunded_amount <= amount)` constraint makes over-refunding impossible.

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;                                   -- record intent
  INSERT INTO payment_transactions(order_id, idempotency_key, amount, currency, state)
    VALUES (:order, :key, :amt, :ccy, 'initiated');
COMMIT;
-- now call the provider with :key and :amt   (outside the transaction)
```

> [!WARNING]
>
> **Never hold a transaction open across the provider call**
> The external call can take seconds and can hang. Record intent, commit, *then* call the provider. Holding a CockroachDB transaction open while waiting on a third party converts the provider's latency into contention in the cluster.

## Process callbacks through an inbox

Provider webhooks are **at-least-once and may be reordered**. Treat every callback as potentially duplicate and potentially stale. An inbox table keyed by the provider's event id makes duplicate processing a no-op.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE payment_events (
  provider            STRING NOT NULL,
  provider_event_id   STRING NOT NULL,
  payment_id          UUID   NOT NULL REFERENCES payment_transactions(id),
  kind                STRING NOT NULL,          -- 'authorized','captured','failed','refunded'
  provider_status_at  TIMESTAMPTZ NOT NULL,     -- the provider's event timestamp
  received_at         TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, provider_event_id)      -- dedupe
);
```

Handle a callback in one transaction: deduplicate, lock the payment row, and **advance state only forward**.

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  INSERT INTO payment_events(provider, provider_event_id, payment_id, kind, provider_status_at)
    VALUES (:prov, :eid, :pid, :kind, :pts)
    ON CONFLICT (provider, provider_event_id) DO NOTHING;   -- 0 rows → already processed
  -- if replay: COMMIT and return 200 (idempotent ack)

  SELECT state FROM payment_transactions WHERE id = :pid FOR UPDATE;   -- serialize callbacks
  -- apply the transition ONLY if it moves forward (e.g. authorized → captured),
  -- using the provider_status_at to ignore a late/old event:
  UPDATE payment_transactions
     SET state = :new_state, provider_ref = :pref, updated_at = now()
   WHERE id = :pid
     AND state = :expected_prev_state;     -- compare-and-set; 0 rows = out-of-order, ignore
COMMIT;                                      -- retry loop on 40001
```

Two mechanisms perform the work. The inbox `ON CONFLICT` eliminates **duplicates**, and the `FOR UPDATE` lock combined with the compare-and-set eliminates **races and out-of-order** events. [`SELECT ... FOR UPDATE`](https://docs.cockroachlabs.com/docs/stable/select-for-update) serializes concurrent callbacks for the same payment, and the transaction runs under a [`40001` retry loop](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference).

> [!NOTE]
>
> **Always ack duplicates with success**
> If the application returns an error to a duplicate webhook, the provider continues to redeliver it. A replay should commit, performing no change, and return `200`. Under idempotent processing, a duplicate is a *successful no-op*, not a failure.

## Refunds

A refund is a forward transition bounded by the captured amount. The `CHECK (refunded_amount <= amount)` constraint is the backstop; the guarded update is the gate.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
UPDATE payment_transactions
   SET refunded_amount = refunded_amount + $refund,
       state = CASE WHEN refunded_amount + $refund = amount THEN 'refunded' ELSE state END,
       updated_at = now()
 WHERE id = $pid
   AND state = 'captured'
   AND refunded_amount + $refund <= amount;    -- 0 rows → reject over-refund
```

Refunds are idempotent through their own provider idempotency key and inbox event, in the same way as captures.

## Reconciliation: detect drift and repair it

Regardless of how carefully the write path is implemented, an ambiguous case remains: the capture call succeeded at the provider but the local commit was lost. The provider charged the customer, but the database records `initiated`. This case cannot be prevented; it must be **detected and repaired**.

Run a periodic job that compares the provider's ledger against `payment_transactions` and resolves discrepancies, such as marking the local record captured or requesting a refund for a charge with no matching order. Use [follower reads](https://docs.cockroachlabs.com/docs/stable/follower-reads.md) (`AS OF SYSTEM TIME follower_read_timestamp()`) so these scans do not contend with the live write path.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT id, order_id, state, amount, currency
  FROM payment_transactions
  AS OF SYSTEM TIME follower_read_timestamp()
 WHERE state = 'initiated' AND created_at < now() - INTERVAL '15 minutes';
-- cross-check each against the provider; repair drift
```

This closes the gap that the write path cannot: at-least-once delivery, idempotent processing, and reconciliation together provide effectively-once money movement.

## Payment-attempt tables get big

The payment-attempt and payment-event tables are among the highest-volume tables in the system. They can reach **tens or hundreds of millions of rows**, because every retry, callback, and status change is a row. Design for this volume from the start:

* **Partition by time and/or merchant** so queries and retention touch a bounded slice.
* **Index for the queries you actually run** (by order, by provider reference, by status + time), not speculatively.
* **Keyset pagination**, not `OFFSET`, for scanning history.
* **Row-Level TTL** to age out resolved attempts you no longer need online.

Predictable payment latency comes from bounded, well-indexed access paths, not from raw cluster speed.

## Driving the order forward

Payment outcomes advance the order lifecycle. When a capture completes, transition the order `created → paid` and commit the inventory reservation in the **same transaction** as the payment-state change, then enqueue downstream work through the [outbox](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md). See [Order lifecycle & idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md) and [Inventory & reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md).

## Tradeoffs

| Choice | Option A | Option B | Guidance |
| - | - | - | - |
| Duplicate protection | Provider idempotency key (outbound) | Inbox dedupe (inbound) | Use **both**: they protect different directions |
| Callback ordering | Trust provider order | Monotonic compare-and-set + event timestamp | Never trust order; advance state only forward |
| Catching ambiguous charges | Write-path only | Write path **+ reconciliation** | Always add reconciliation; the ambiguous case is unavoidable |
| Reconciliation reads | Leaseholder | Follower / `AS OF SYSTEM TIME` | Follower reads: scans shouldn't contend |

> [!CAUTION]
>
> **Anti-patterns**
>
> * Calling the provider **inside** an open database transaction.
> * Treating a duplicate webhook as an error (causes infinite redelivery).
> * Applying callbacks in arrival order without a monotonic guard: a late "authorized" after a "captured" corrupts state.
> * Relying on the write path alone and skipping reconciliation: the charged-but-not-recorded case will happen.
