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

# Order lifecycle & idempotency

> Place each order exactly once with an idempotency key, and move it through its lifecycle as an explicit state machine in the same transaction.

Two invariants live together on this page because they are enforced by the same transaction:

> **An order moves only along legal state transitions, and its history never diverges from its state.**
>
> **A retried request produces at most one order and returns the same response both times.**

The first invariant prevents orders from entering impossible states, such as shipping before payment. The second prevents network retries from turning one customer action into two orders or two charges.

## The lifecycle as an explicit state machine

Define the states and the legal transitions, and enforce them in the database rather than documenting them only in a diagram.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE orders (
  id          UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  customer_id UUID NOT NULL,
  status      STRING NOT NULL DEFAULT 'created',
  version     INT    NOT NULL DEFAULT 0,      -- optimistic concurrency
  currency    CHAR(3) NOT NULL,
  total       DECIMAL(18,2) NOT NULL DEFAULT 0,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  CONSTRAINT valid_status CHECK (status IN
    ('created','paid','fulfilling','shipped','delivered','cancelled','returned'))
);
```

The legal graph for this guide:

```
created ──▶ paid ──▶ fulfilling ──▶ shipped ──▶ delivered
   │          │           │
   ▼          ▼           ▼
cancelled  cancelled   (partial) ──▶ returned
```

### Enforce transitions with compare-and-set

Do not read the status, decide in application code, and then write the new status. That sequence is a lost-update race. Instead, make the expected current state part of the `WHERE` clause. A stale or illegal transition matches zero rows and is rejected atomically.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
UPDATE orders
   SET status = 'paid', version = version + 1, updated_at = now()
 WHERE id = $order_id
   AND status = 'created';         -- guard: only created → paid
-- rows_affected = 0  →  illegal/stale transition, reject
```

The `version` column provides general [optimistic concurrency](https://docs.cockroachlabs.com/docs/stable/transactions.md) for edits that are not a simple status change: read `version`, then `UPDATE ... WHERE id = $id AND version = $v`.

> [!NOTE]
>
> **Enum vs STRING + CHECK, and triggers**
> A `STRING` + `CHECK` is the most evolvable encoding (adding a state is a constraint change). A native `ENUM` gives stronger type safety but altering its values is a schema change. If you prefer to centralize transition rules in the database, [triggers](https://docs.cockroachlabs.com/docs/stable/triggers.md) can reject illegal transitions server-side, at the cost of more coupling. Application-side compare-and-set is portable and explicit; it's the default this guide uses.

## History that cannot drift

Write the audit event in the **same transaction** as the state change. Because the two commit atomically, state and history can never disagree: there is no window where the order says `paid` but no event records it.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE order_events (
  order_id    UUID NOT NULL REFERENCES orders(id),
  seq         INT  NOT NULL,
  from_state  STRING,
  to_state    STRING NOT NULL,
  actor       STRING NOT NULL,         -- 'customer:123', 'system:payment', ...
  payload     JSONB,
  occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (order_id, seq)
);
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  UPDATE orders SET status='paid', version=version+1 WHERE id=:id AND status='created';
  -- rows_affected = 0 → ROLLBACK, reject
  INSERT INTO order_events(order_id, seq, from_state, to_state, actor, payload)
    VALUES (:id, (SELECT coalesce(max(seq),0)+1 FROM order_events WHERE order_id=:id),
            'created','paid','system:payment', :payload);
COMMIT;                                 -- retry loop on 40001
```

> [!TIP]
>
> **Audit is also your recovery log**
> Because `order_events` is append-only and ordered by `seq`, you can reconstruct or verify any order's current state by folding its events. Combined with idempotency (below), this is what lets you safely resume after a crash.

## Idempotent order creation

A client that times out does not know whether the order was created, so it retries. Without protection, the retry creates a duplicate order. The solution is a caller-supplied **idempotency key**, recorded in the same transaction as the effect.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE idempotency_keys (
  key                 STRING PRIMARY KEY,      -- caller-supplied (e.g. UUID)
  request_fingerprint STRING NOT NULL,         -- hash of the request body
  state               STRING NOT NULL DEFAULT 'in_progress'
                      CHECK (state IN ('in_progress','done')),  -- claim/lease
  attempt_count       INT NOT NULL DEFAULT 0,  -- observed retries
  response            JSONB,                   -- cached first-time response
  created_at          TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

The first request inserts the key and performs the work. A retry matches the primary key and returns the stored response without performing the work again.

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
POST /orders   Idempotency-Key: 9f3c…
BEGIN;
  INSERT INTO idempotency_keys(key, request_fingerprint) VALUES (:key, :fp)
    ON CONFLICT (key) DO NOTHING;        -- 0 rows inserted → this is a replay
  IF replay:
     SELECT response FROM idempotency_keys WHERE key=:key;  -- return it, COMMIT, done
  ELSE:
     <guarded inventory decrement>       -- see Inventory & reservations
     INSERT INTO orders(...);  INSERT INTO order_lines(...);
     INSERT INTO order_events(...);  INSERT INTO outbox(...);   -- see External integration
     UPDATE idempotency_keys SET response=:resp WHERE key=:key;
COMMIT;                                   -- retry loop on 40001
```

> [!NOTE]
>
> **The key's scope and the fingerprint**
> The caller owns the key; you define its scope (per customer, per endpoint). Store a `request_fingerprint` so you can detect the dangerous case where the *same key* is reused with a *different* body. That's a client bug, and you should reject it rather than silently return the old response. Expire old keys with [Row-Level TTL](https://docs.cockroachlabs.com/docs/stable/row-level-ttl.md) so the table doesn't grow forever.

> [!TIP]
>
> **The key is also a claim**
> The idempotency row doubles as a **claim/lease**: the first writer inserts the key in `in_progress` state and does the work, then flips it to `done` and stores the `response`. A concurrent or retried request that collides on the primary key either returns the cached response (state `done`) or learns the operation is already in flight (state `in_progress`). Because the primary key is unique, **two workers, even in different regions, cannot both process the same request**. Track `attempt_count` to see how often clients actually retry.

## Concurrency, ordering, and the role of `SERIALIZABLE`

The default isolation level is what makes the patterns on this page safe. [`SERIALIZABLE`](https://docs.cockroachlabs.com/docs/stable/transactions#isolation-levels) prevents the lost updates and write skew that would otherwise let two concurrent transitions both succeed, or let an idempotency check and its insert interleave incorrectly. The cost is that a contended transaction may return a [`40001` retry error](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference), so every transaction here runs inside a client retry loop.

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
for attempt in 1..MAX:
  try:    BEGIN; <statements>; COMMIT; break
  except SQLSTATE 40001: sleep(backoff * attempt); continue
```

**Event ordering.** Inside the database, order events are totally ordered per order by `seq` (and globally by HLC timestamps). Across a [changefeed](https://docs.cockroachlabs.com/docs/stable/changefeed-messages.md), only **per-key ordering** is guaranteed and duplicates are possible, so any consumer of order events must dedupe by key + `updated` timestamp and tolerate reordering across *different* orders. See [External integration](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md).

## Recovery

Idempotency keys + append-only `order_events` make the system resumable. After a crash or ambiguous outcome:

* A retried create with the same key is a no-op that returns the original result, with no duplicate.
* The current state is whatever the last committed transition set it to; you can verify it by folding `order_events`.
* An operation that committed but whose caller never saw the response is safely replay-able.

## Tradeoffs

| Choice | Option A | Option B | Guidance |
| - | - | - | - |
| State encoding | `STRING` + `CHECK` (evolvable) | `ENUM` (type-safe, schema change to alter) | `STRING`+`CHECK` default |
| Transition enforcement | App-side compare-and-set | DB-side [triggers](https://docs.cockroachlabs.com/docs/stable/triggers.md) | App-side unless you need central DB enforcement |
| Isolation | `SERIALIZABLE` (safe, retry loop) | `READ COMMITTED` (fewer retries, permits lost update) | `SERIALIZABLE` for order/idempotency writes |
| Idempotency conflict | Return stored response | Reject on fingerprint mismatch | Return on match; reject on mismatch |

> [!CAUTION]
>
> **Anti-patterns**
>
> * Read status → decide → write status in separate steps (lost-update race). Always put the expected state in the `WHERE`.
> * Creating the order and recording the idempotency key in **separate transactions**: a crash between them double-creates. One transaction, always.
> * Assuming changefeed events arrive in global order. They don't.
