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

# Fulfillment, partial shipments & returns

> Order creation is only the first step.

Order creation is only the first step. The operations that follow unfold over days and weeks: a warehouse ships three of five units today and the remainder next week, a second warehouse splits the remainder across two parcels, one unit is backordered, the customer cancels a line that was never picked, and a month later two units are returned. Each of these events moves quantity, money, and physical stock. Each can arrive more than once, out of order, or against stale state.

This page specifies the data model and the write patterns that keep these flows correct on CockroachDB. One principle governs the page: **quantity is conserved per line, and order status is derived, never asserted.**

> [!NOTE]
>
> **Scope and cross-references**
> This page covers fulfillment, cancellation, and returns at **line granularity**. Hot-row handling for the single-SKU inventory counter lives on the Inventory page; the full order state machine lives on the Lifecycle page; refund mechanics live on the Payments page; and the general idempotency contract lives on the Idempotency page. Each is referenced where it applies.

## 1. The core invariant: per-line quantity conservation

**Invariant.** For every order line, the quantities committed to downstream flows must never exceed what was ordered:

```
shipped + backordered + cancelled + returned  <=  ordered      (per line)
```

As a corollary, `returned <= shipped`: a unit that never shipped cannot be returned. The order's status is a **function of the aggregate of its lines**. It is computed, not stored as a source of truth.

### Why this is difficult

The invariant spans time and processes. The `ordered` quantity is fixed at checkout. The `shipped`, `backordered`, `cancelled`, and `returned` quantities each accrue from independent, asynchronous actors: warehouse management systems, carrier callbacks, customer-service tools, and RMA intake. These actors retry, duplicate, and reorder their messages. Two failure modes dominate:

* **Shipping more than ordered.** Two warehouses each believe they own the open quantity on a line and both ship. Without a guard evaluated atomically against current state, the system ships 7 of 5 units and the invariant is violated silently.
* **Refund/restock mismatch.** A return re-enters stock but the refund is never issued, or a refund is issued twice for one physical return. Money and inventory drift apart.

Both are *conservation* bugs. Defend against them the same way as against overselling inventory: push the arithmetic into a `CHECK` constraint for the hard floor, and into a **guarded `UPDATE`** for the atomic decision. CockroachDB supports `CHECK` constraints and standard SQL guards directly ([SQL feature support](https://docs.cockroachlabs.com/docs/stable/sql-feature-support.md)).

> [!WARNING]
>
> **The invariant is non-negotiable**
> If any single query can leave `shipped > ordered` for a line, the system is incorrect regardless of the quality of the surrounding code. Treat the guard as the most important clause in each write, exactly as `WHERE available >= qty` is for inventory.

## 2. Model at line granularity

A single `orders.status` column cannot represent a partial or split flow. A condition such as "60% shipped, one line backordered, one unit in transit back to the warehouse" is not a scalar. The model requires rows, and those rows live below the line.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Established on the Schema page: orders, order_lines.
-- order_lines(order_id, line_no, sku, qty, unit_price, ...) PRIMARY KEY (order_id, line_no)

CREATE TABLE shipments (
  id          UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  order_id    UUID NOT NULL REFERENCES orders(id),
  warehouse   STRING NOT NULL,
  carrier     STRING,
  tracking    STRING,
  status      STRING NOT NULL DEFAULT 'packing'
              CHECK (status IN ('packing','in_transit','delivered','lost')),
  -- Idempotency: the WMS/carrier's own id for this physical shipment.
  external_id STRING NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  CONSTRAINT uq_shipment_external UNIQUE (external_id)   -- duplicate callbacks = no-op
);

CREATE TABLE shipment_lines (
  shipment_id UUID NOT NULL REFERENCES shipments(id),
  order_id    UUID NOT NULL,
  line_no     INT  NOT NULL,
  qty         INT  NOT NULL CHECK (qty > 0),
  PRIMARY KEY (shipment_id, order_id, line_no),
  CONSTRAINT fk_line FOREIGN KEY (order_id, line_no)
    REFERENCES order_lines (order_id, line_no)
);

CREATE TABLE returns (
  id          UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  order_id    UUID NOT NULL REFERENCES orders(id),
  reason      STRING,
  status      STRING NOT NULL DEFAULT 'requested'
              CHECK (status IN ('requested','received','restocked','refunded','rejected')),
  -- Idempotency: the RMA system's external return id.
  external_id STRING NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  CONSTRAINT uq_return_external UNIQUE (external_id)      -- duplicate RMA callbacks = no-op
);

CREATE TABLE return_lines (
  return_id   UUID NOT NULL REFERENCES returns(id),
  order_id    UUID NOT NULL,
  line_no     INT  NOT NULL,
  qty         INT  NOT NULL CHECK (qty > 0),
  restocked   BOOL NOT NULL DEFAULT false,
  PRIMARY KEY (return_id, order_id, line_no),
  CONSTRAINT fk_line FOREIGN KEY (order_id, line_no)
    REFERENCES order_lines (order_id, line_no)
);
```

The shipped, cancelled, and returned quantities for a line are **sums over child rows**, not columns that are overwritten. This is what makes split shipments representable: three `shipment_lines` rows against one `order_line` sum to the shipped quantity, with no scalar forced to fit.

> [!TIP]
>
> **Why not a status column on the order?**
> `orders.status` is a convenience for reads and the UI, not a source of truth. The source of truth is the set of line-level quantities. The column may be retained (Section 7 shows how to maintain it in the same transaction), but it must be derived. Never let a write set `status = 'shipped'` without the line rows that justify it.

The `UNIQUE (external_id)` constraints provide the idempotency guarantee: a WMS or carrier that sends the same "shipment created" callback twice collides on the key, and the second insert is a no-op. See the Idempotency page for the full inbox pattern.

## 3. Partial fulfillment & split shipments

**Invariant.** A shipment may never push a line's cumulative shipped quantity past its ordered quantity.

The guard evaluates the arithmetic atomically and rejects at **0 rows affected**. This is the same pattern as the inventory decrement, applied to fulfillment.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;

-- 1. Create the shipment header (idempotent on external_id).
INSERT INTO shipments (id, order_id, warehouse, external_id)
  VALUES ($ship_id, $order_id, $wh, $external_id)
  ON CONFLICT (external_id) DO NOTHING;      -- duplicate callback stops here

-- 2. Guarded line write: only insert if it keeps shipped + $qty <= ordered.
INSERT INTO shipment_lines (shipment_id, order_id, line_no, qty)
SELECT $ship_id, $order_id, $line_no, $qty
 WHERE $qty <= (
   SELECT ol.qty
          - COALESCE((SELECT sum(sl.qty) FROM shipment_lines sl
                       WHERE sl.order_id = ol.order_id AND sl.line_no = ol.line_no), 0)
     FROM order_lines ol
    WHERE ol.order_id = $order_id AND ol.line_no = $line_no
 );
-- 0 rows inserted => rejected: this ship would exceed the open quantity.

-- 3. Append the audit event (same transaction as the effect).
INSERT INTO order_events (order_id, seq, from_state, to_state, actor, payload)
  VALUES ($order_id, $next_seq, 'fulfilling', 'fulfilling', $wh,
          jsonb_build_object('shipment', $ship_id, 'line', $line_no, 'qty', $qty));

COMMIT;
```

The `WHERE $qty <= (ordered − already_shipped)` subquery is the fulfillment analogue of `WHERE available >= qty`. If a second warehouse races on the same line, serializable isolation forces one of the two transactions to observe the other's committed `shipment_lines` row and re-evaluate the guard. The losing transaction either ships a smaller quantity or inserts 0 rows and is rejected. The application wraps this in the standard retry loop for `40001` (see [Transactions & SQL](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md)).

> [!NOTE]
>
> **Contention is low here, by design**
> These are **many-row writes**: each shipment touches different `shipment_lines` rows keyed by `(shipment_id, order_id, line_no)` and spread across the keyspace. Unlike the single-SKU inventory counter, which is one hot row that every concurrent order contends on, fulfillment writes rarely collide. The only genuine contention is two shipments racing on the *same* line, which is rare and is resolved correctly by the guard. For the hot path, the inventory decrement, see the Inventory page's hot-row techniques.

### A subtlety to watch for

Compute "already shipped" from `sum(shipment_lines.qty)`, not from a cached counter, unless that counter is maintained transactionally (Section 7). A denormalized `order_lines.shipped` column that drifts from the child rows reintroduces the conservation bug the model was built to prevent. If the column is retained, update it in the *same* `UPDATE ... WHERE shipped + $qty <= qty` statement so the guard and the stored value cannot disagree.

## 4. Backorders

**Invariant.** `backordered` is the quantity on a line that is accepted but not yet shippable because stock is unavailable; it is drawn down as stock arrives and converts to `shipped`.

A backorder is not a separate table but a *state of unshipped quantity*. The open quantity on a line, `ordered − shipped − cancelled`, divides into "ready to ship" (reserved against on-hand inventory) and "backordered" (awaiting replenishment). Which category a unit falls into is a function of the reservation ledger and on-hand inventory:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Open, unreserved quantity on a line = the backordered portion.
SELECT ol.qty
       - COALESCE((SELECT sum(sl.qty) FROM shipment_lines sl
                    WHERE sl.order_id = ol.order_id AND sl.line_no = ol.line_no), 0)
       - COALESCE((SELECT sum(r.qty) FROM reservations r
                    WHERE r.order_id = ol.order_id AND r.sku = ol.sku
                      AND r.expires_at > now()), 0)      AS backordered
  FROM order_lines ol
 WHERE ol.order_id = $order_id AND ol.line_no = $line_no;
```

When replenishment arrives, a reservation is created against `inventory` using the guarded decrement (`WHERE available >= qty`), which moves quantity out of the backordered category and makes it shippable. That decrement is the hot-row operation; its mechanics, expiry semantics, and sharding are covered on the **Inventory page**. The only rule here is that backordered quantity must never be reserved against stock that does not exist. The `inventory.available >= 0` `CHECK` and the guarded decrement enforce this.

## 5. Cancellations

**Invariant.** Cancelling a line releases any held reservation/stock and adds to `cancelled`, subject to `shipped + cancelled <= ordered`: you cannot cancel quantity that already shipped.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;

-- Guard: only cancel what is still open (not shipped, not already cancelled).
UPDATE order_lines
   SET cancelled = cancelled + $qty, updated_at = now()
 WHERE order_id = $order_id AND line_no = $line_no
   AND shipped + cancelled + $qty <= qty;     -- 0 rows = nothing cancellable

-- Release the reservation so the stock returns to available.
UPDATE inventory i
   SET available = available + r.qty
  FROM reservations r
 WHERE r.order_id = $order_id AND r.sku = i.sku AND r.qty = $qty;

DELETE FROM reservations
 WHERE order_id = $order_id AND sku = $sku AND qty = $qty;

INSERT INTO order_events (order_id, seq, from_state, to_state, actor, payload)
  VALUES ($order_id, $next_seq, 'fulfilling', 'fulfilling', $actor,
          jsonb_build_object('cancelled_line', $line_no, 'qty', $qty));

COMMIT;
```

The guarded transition follows the same pattern used across the system: `WHERE ... <= qty` rejects an illegal cancellation at 0 rows. Releasing stock is the exact inverse of the reservation's guarded decrement. Because `inventory.available` is the hot row, keep this transaction small and single-batch. The full set of legal transitions, including when a line may move to `cancelled` and how a fully cancelled order collapses to the `cancelled` terminal state, is specified on the **Lifecycle page**.

## 6. Returns / RMA

**Invariant.** A return re-enters physical stock via the reservation ledger / inventory and triggers a refund; it is idempotent on the external return id, and `returned <= shipped` per line.

Returns are the mirror image of fulfillment: quantity flows back. They carry two additional hazards: the intake callback is at-least-once, and the refund is a *separate* system that must be driven exactly once.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;

-- 1. Idempotent intake: the RMA system's external id is the dedupe key.
INSERT INTO returns (id, order_id, reason, external_id)
  VALUES ($return_id, $order_id, $reason, $external_id)
  ON CONFLICT (external_id) DO NOTHING;        -- duplicate RMA callback = no-op

-- 2. Guard: cannot return more than was shipped on the line.
INSERT INTO return_lines (return_id, order_id, line_no, qty)
SELECT $return_id, $order_id, $line_no, $qty
 WHERE $qty <= (
   SELECT COALESCE((SELECT sum(sl.qty) FROM shipment_lines sl
                     WHERE sl.order_id = ol.order_id AND sl.line_no = ol.line_no), 0)
          - COALESCE((SELECT sum(rl.qty) FROM return_lines rl
                       WHERE rl.order_id = ol.order_id AND rl.line_no = ol.line_no), 0)
     FROM order_lines ol
    WHERE ol.order_id = $order_id AND ol.line_no = $line_no
 );
-- 0 rows => more returned than shipped: reject.

-- 3. Restock: re-enter inventory for received, resellable units.
UPDATE inventory
   SET available = available + $qty
 WHERE sku = $sku;

UPDATE return_lines
   SET restocked = true
 WHERE return_id = $return_id AND line_no = $line_no;

INSERT INTO order_events (order_id, seq, from_state, to_state, actor, payload)
  VALUES ($order_id, $next_seq, 'delivered', 'returned', 'rma',
          jsonb_build_object('return', $return_id, 'line', $line_no, 'qty', $qty));

COMMIT;
```

The refund is deliberately **outside** this transaction. Restocking is a local database effect. Refunding is a call to an external payment provider that can fail, time out, or succeed without responding. Binding them in one database transaction would couple the durability of the rows to the availability of a third party.

> [!TIP]
>
> **Refund as a compensating action**
> Treat the refund as a separate, idempotent step driven off the committed return. Record `returns.status = 'received'`, then hand off to payments keyed by the **external return id** so that a retried hand-off is a no-op. The payment provider's idempotency key and the inbox pattern together guarantee an exactly-once economic effect even though the mechanical calls are at-least-once. The refund mechanics and reconciliation live on the **Payments page**. If the refund ultimately fails, it is a compensating-action failure surfaced to operators, not a reason to roll back the restock, which has already physically occurred.

### A subtlety to watch for

Restock only *resellable* units. A return received damaged increments `returned` (for conservation and refund purposes) but must **not** increment `inventory.available`. Gate the `UPDATE inventory` on an inspection outcome, and keep `restocked` as an explicit per-line flag so that the ledger and the counter cannot disagree about how many units re-entered sellable stock.

## 7. Deriving order status from lines

The order's status is a fold over its lines. Compute it on read:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
WITH line_state AS (
  SELECT ol.order_id, ol.line_no, ol.qty AS ordered,
         COALESCE((SELECT sum(sl.qty) FROM shipment_lines sl
                    WHERE sl.order_id = ol.order_id AND sl.line_no = ol.line_no), 0) AS shipped,
         ol.cancelled,
         COALESCE((SELECT sum(rl.qty) FROM return_lines rl
                    WHERE rl.order_id = ol.order_id AND rl.line_no = ol.line_no), 0) AS returned
    FROM order_lines ol
   WHERE ol.order_id = $order_id
)
SELECT CASE
         WHEN sum(returned) = sum(shipped) AND sum(shipped) > 0 THEN 'returned'
         WHEN sum(cancelled) = sum(ordered)                     THEN 'cancelled'
         WHEN sum(shipped) = sum(ordered - cancelled)
              AND sum(ordered - cancelled) > 0                  THEN 'shipped'
         WHEN sum(shipped) > 0                                  THEN 'partially_shipped'
         ELSE 'open'
       END AS order_status
  FROM line_state;
```

This query is the single authority on the state of an order. It cannot be inconsistent, because it reads the same rows the guards wrote.

### Derive-on-read vs maintain-a-summary

* **Derive on read** (above): always correct, with no write-time cost and no drift. The cost is a multi-join aggregate on every status read, which is acceptable for an order page but expensive for a dashboard scanning millions of orders.
* **Maintain a summary column**: keep `orders.status` (and, optionally, `order_lines.shipped/returned` counters) and update them **in the same transaction** as every line write. Reads are cheap, but this introduces an invariant: the summary must always equal the derived value. The only safe way to maintain it is to recompute from the child rows inside the committing transaction, never to set `status = 'shipped'` from application logic that may be acting on stale state.

The default is **derive on read** until a read path proves too slow, then add a transactionally maintained summary for that path only. Never maintain a summary that some write paths update and others bypass; a partially maintained cache is worse than no cache.

## 8. Tradeoffs

**Line granularity vs. order-level simplicity.** Modeling shipments, cancellations, and returns at the line level requires more tables, more joins, and more code than a single `orders.status` enum. The simple model fails the first time a warehouse splits a shipment. Correctness for partial and split flows is purchased with schema and query complexity, which is the correct trade: the complexity is *essential*, not incidental, because the business allows partial fulfillment and the data model must represent it. Direct effort toward making the line-level queries ergonomic (views, the status query saved for reuse) rather than collapsing the model back to a scalar.

**Guarded writes vs. read-modify-write in the application.** Every mutation here is a `WHERE ... <= ordered` guard that rejects at 0 rows affected, rather than a `SELECT`, an application-side permission check, and then an `UPDATE`. The guarded form is safer under concurrency: the decision and the effect are one atomic statement, so no window exists in which another transaction changes the premise between the check and the write. The cost is that the application must inspect the rows-affected count and treat 0 as a domain rejection rather than a successful no-op. This discipline must be enforced everywhere, or the invariant leaks. Under `SERIALIZABLE` (CockroachDB's default), concurrent guards on the same line produce `40001` retries rather than corruption, which is the correct failure mode but requires the client retry loop ([Transactions & SQL](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md)). Under `READ COMMITTED`, the guards and the `CHECK` constraints remain mandatory because lost updates are permitted.

**`CHECK` constraints vs. application validation.** The `qty > 0` and `available >= 0` constraints, together with the per-line guards, push conservation into the database, where it holds regardless of which service writes. CockroachDB enforces `CHECK` as standard SQL ([SQL feature support](https://docs.cockroachlabs.com/docs/stable/sql-feature-support.md)). The tradeoff is that a constraint violation surfaces as a database error that the application must map to a user-facing message, and that changes to constraints are schema migrations. The database is the correct place for the floor: an invariant enforced in one service is one faulty deployment away from violation, whereas an invariant in the schema is enforced for every writer.

**Contention profile vs. the inventory counter.** Fulfillment and return writes spread across many rows keyed by shipment and line, so they contend rarely. This is the opposite of the single-SKU inventory counter, where every concurrent order contends on one hot row. This is the strongest argument for keeping quantity in child rows rather than denormalized counters on `order_lines`: a per-line `shipped` counter that every shipment increments turns a naturally distributed write into a narrow hotspot per popular SKU-line, recreating the hot-row problem that belongs only to inventory. Keep the hot-row techniques (sharding, `SELECT ... FOR UPDATE`, small transactions) where they are genuinely needed, at the inventory decrement, and let fulfillment remain inexpensive and distributed. See the Inventory page.

**Idempotency via `UNIQUE` vs. assuming callbacks do not repeat.** Keying `shipments` and `returns` on an external id with a `UNIQUE` constraint makes duplicate carrier and RMA callbacks no-ops at the database level. The alternative, trusting that each upstream event fires once, fails the first time a carrier retries a webhook, double-restocking inventory or double-refunding a customer. The cost is one column and one constraint per externally driven table, plus the discipline of passing the external id through every handler. It is the least expensive safeguard in the system.

**Refund coupling vs. compensation.** Keeping the refund outside the restock transaction trades a simple "everything commits together" model for resilience: the database effect commits locally and durably, and the economic effect is driven as an idempotent compensating action against payments. Coupling them would let a payment-provider outage block the recording of returned stock, tying local durability to a third party's uptime. The compensation model requires an explicit reconciliation path for refunds that never complete, which is operational work to build and monitor, but it is the only model that remains correct when an external system fails. See the Payments page.

**Derive-on-read vs. maintained summary** (Section 7, restated as a standing decision): correctness by construction and no drift, paid for with read cost, versus cheap reads paid for with a maintained invariant and the risk of a partially updated cache. Default to deriving. Add a transactionally maintained summary only for a read path that has proven too slow, and only if every write path maintains it.
