[!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: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. Theordered 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.
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).
[!WARNING] The invariant is non-negotiable If any single query can leaveshipped > orderedfor 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 asWHERE available >= qtyis for inventory.
2. Model at line granularity
A singleorders.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.
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?Theorders.statusis 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 setstatus = 'shipped'without the line rows that justify it.
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.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).
[!NOTE] Contention is low here, by design These are many-row writes: each shipment touches differentshipment_linesrows 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” fromsum(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:
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 tocancelled, subject to shipped + cancelled <= ordered: you cannot cancel quantity that already shipped.
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, andreturned <= 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.
[!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 incrementsreturned (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: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/returnedcounters) 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 setstatus = 'shipped'from application logic that may be acting on stale state.
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 singleorders.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). 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). 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.
