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

# Terminology

> This page defines the vocabulary used throughout the guide.

This page defines the vocabulary used throughout the guide. Every term below has a single meaning, and that meaning is the same in prose, in SQL, in API payloads, in event schemas, and in tests. The entity names (`orders`, `order_lines`, `inventory`, `reservations`, `order_events`, `idempotency_keys`, `payment_events`) are the schema; they are not approximations. A human reading this page and an agent generating code from it should arrive at an identical model of the system.

The glossary is grouped into three layers: the **order domain** (what the business means), **correctness** (the properties the system must never violate), and **CockroachDB** (the database behavior you build on). Subtle terms carry a "Why it matters for orders" line so the stakes are explicit.

***

## Order-domain terms

### Order

A customer's committed intent to purchase, represented by one row in the `orders` table. An order owns one or more line items, carries a monetary total in a single currency, and has exactly one lifecycle state at any instant. The order is the unit of consistency: its lines, its state, and its audit history must always agree with one another.

### Line item

One purchasable entry within an order: a single SKU, a quantity, and a price snapshot, stored as a row in `order_lines` and keyed by `(order_id, line_no)`. An order with three distinct SKUs has three line items. Quantity lives on the line, never on the order.

### SKU

Stock-keeping unit: the atomic identifier for a sellable, countable product. Inventory is counted per SKU, reservations are taken per SKU, and line items reference a SKU. One SKU maps to exactly one row in `inventory`.

### Price snapshot

The unit price, discount, and tax copied onto the `order_lines` row at the moment the order is created. Once written, it is immune to later changes in the catalog.

> [!NOTE]
>
> **Why it matters for orders**
> The catalog price is a moving target; the order is a historical fact. If you recompute an order's total from the live catalog, a mid-flight price change silently alters a placed order, breaking receipts, refunds, and accounting reconciliation. The snapshot is the contract between what the customer agreed to and what you charge.

### Inventory reservation

A time-bounded hold on stock for an in-progress order, recorded as a row in `reservations` with a SKU, a quantity, and an `expires_at`. A reservation reduces effectively-available stock without yet decrementing the sold count, so two customers cannot both claim the last unit.

> [!NOTE]
>
> **Why it matters for orders**
> Reservation is the mechanism that converts "checking out" into "nobody else can take this stock" without committing a sale that may never be paid for. Expiry (`expires_at < now()`, evaluated at read time) returns stock when checkout is abandoned. Without reservations, overselling is a race, not an exception.

### Backorder

An order line accepted for a SKU whose available quantity is currently zero or insufficient, to be fulfilled when stock arrives. A backordered line is a committed obligation with deferred fulfillment, distinct from a rejected line.

### Partial fulfillment

Shipping some, but not all, of an order's line items (or some of a line's quantity) while the remainder stays open. The order stays in a fulfilling state and the `order_events` history records what shipped and what remains.

### Split shipment

A single order fulfilled across more than one physical shipment, often because stock lives in different locations or becomes available at different times. Split shipment is the operational form that partial fulfillment usually takes; each shipment is its own audit event.

### Return / RMA

The reverse flow: goods coming back from the customer. An **RMA** (Return Merchandise Authorization) is the authorized, tracked instance of a return: the record that a specific set of line items from a specific order is approved to come back, triggering restock and refund. A return is not a deletion; it is a new set of events appended to the order's history.

### Order lifecycle / state machine

The fixed set of states an order can occupy and the only legal transitions between them (for example `created -> paid -> fulfilling -> shipped -> delivered`, with `cancelled` and `returned` as terminal or reverse branches). The lifecycle is enforced, not merely documented: an illegal transition is a bug the system must reject.

> [!TIP]
>
> **Why it matters for orders**
> The state machine is the single source of truth for "what can happen next." Encoding it explicitly, as a `CHECK` constraint on allowed states plus guarded transitions in the write path, turns a class of ordering bugs (shipping an unpaid order, paying a cancelled one) into rejected operations instead of corrupt data.

### Audit event

An append-only, immutable record of something that happened to an order, stored as a row in `order_events` keyed by `(order_id, seq)`. Each event captures the from-state, the to-state, the actor, and a payload. Audit events are written in the same transaction as the state change they describe, so state and history can never diverge.

***

## Correctness terms

### Invariant

A property of the data that must hold true at every committed state, regardless of concurrency or failure: for example `inventory.available >= 0`, or "an order's total equals the sum of its line totals," or "every state in `orders` has a matching final event in `order_events`." Invariants are the specification the system is tested against.

### Idempotency key

A caller-supplied token that makes a repeated request apply **at most once**. The server records the key (in `idempotency_keys`) together with the result of the first execution; a retry carrying the same key returns the stored result instead of performing the operation again.

> [!NOTE]
>
> **Why it matters for orders**
> Networks retry. Without an idempotency key, a retried "place order" or "charge payment" creates a duplicate order or double-charges a customer. The key is what lets a client retry safely after a timeout it cannot interpret: the defining situation in any payment or order API.

### Optimistic concurrency / compare-and-set

A write that proceeds without holding a lock and only commits if the row has not changed since it was read, typically by checking a version column or the previous value in the `WHERE` clause (`UPDATE ... WHERE id = ? AND version = ?`). If the guarded condition matches zero rows, the write lost the race and the caller re-reads and retries.

> [!NOTE]
>
> **Why it matters for orders**
> Compare-and-set is how you advance an order's state or decrement inventory correctly under contention without a pessimistic lock. It converts "two concurrent updates both succeed and one is lost" into "one succeeds, the other is told to retry."

### Overselling

Committing to sell more units of a SKU than exist: the canonical order-system failure. Prevented by enforcing a non-negative inventory invariant and taking reservations or guarded decrements inside a transaction, so concurrent checkouts cannot both consume the last unit.

### Exactly-once vs at-least-once

Two delivery guarantees for messages and effects. **At-least-once** means an effect may be applied more than once, so duplicates are possible and the consumer must tolerate them. **Exactly-once** means the effect is applied precisely once. True exactly-once delivery is generally unachievable across systems; the practical equivalent is **at-least-once delivery plus an idempotent consumer**: deliver possibly-repeated messages, and make applying them more than once a no-op.

> [!TIP]
>
> **Why it matters for orders**
> CockroachDB changefeeds deliver [at-least-once](https://docs.cockroachlabs.com/docs/stable/change-data-capture-overview.md), so every downstream order effect (emailing a receipt, releasing stock, notifying a warehouse) must be idempotent. You get exactly-once *effects* by pairing at-least-once delivery with an idempotency key or an inbox, never by assuming the pipe delivers once.

### Outbox

A table (for example an `outbox` or the `order_events` table itself) written in the **same transaction** as the business change it describes, then relayed to external systems by a separate reader. Because the business row and the outbox row commit atomically, there is no window where the state changed but the message was lost, or the message was sent but the state rolled back.

### Inbox

The consumer-side counterpart to the outbox: a table of already-processed message identifiers that lets a receiver detect and discard duplicates. Before applying an incoming message, the consumer checks the inbox; if the identifier is present, it skips the work. The inbox is how an at-least-once stream is made idempotent at the point of consumption.

### Saga / compensating action

A **saga** is a business transaction spread across multiple services or steps that cannot share one database transaction (for example: reserve stock, charge payment, create shipment). A **compensating action** is the explicit undo for a completed step, invoked when a later step fails: refund the charge, release the reservation. Sagas trade atomicity for a sequence of local transactions plus well-defined compensations.

> [!NOTE]
>
> **Why it matters for orders**
> Order fulfillment crosses systems that have no shared transaction. The saga pattern is how you keep the whole flow consistent: every forward step must have a compensation, so a payment failure after a reservation leaves no stock stranded and no customer charged.

### Reconciliation

A periodic, out-of-band process that compares two sources of truth that should agree (for example order totals against `payment_events`, or on-hand `inventory` against the sum of active `reservations` and sold units) and flags or repairs discrepancies. Reconciliation is the safety net that catches drift that invariants, retries, and sagas are intended to prevent but sometimes do not.

***

## CockroachDB terms

### Transaction

An atomic, isolated unit of work: either all of its statements commit or none do. In CockroachDB a transaction is distributed and strongly consistent by default. Order correctness is built by putting the state change and its audit event (and any guarded inventory write) inside one transaction.

### SERIALIZABLE

CockroachDB's default and strongest isolation level. It guarantees that concurrent transactions produce a result equivalent to some serial (one-at-a-time) ordering, eliminating anomalies such as lost updates, write skew, and phantoms. Under `SERIALIZABLE`, the database may refuse to commit a transaction that would violate serializability, returning a retry error the application handles with a client-side retry loop. See [Read Committed Transactions](https://docs.cockroachlabs.com/docs/stable/read-committed.md).

> [!NOTE]
>
> **Why it matters for orders**
> `SERIALIZABLE` means you can reason about an order transaction as if it ran alone. Write-skew anomalies (two transactions each reading "there's stock" and both decrementing it) simply cannot commit. This is the property that makes "no overselling" an enforced invariant rather than a hopeful one.

### READ COMMITTED

A weaker isolation level available in CockroachDB (GA in v24.1, preview in v23.2). It never returns serialization retry errors to the client (it retries individual statements transparently) but it permits anomalies that `SERIALIZABLE` forbids: lost updates, write skew, and phantoms. See [Read Committed Transactions](https://docs.cockroachlabs.com/docs/stable/read-committed.md).

> [!NOTE]
>
> **Why it matters for orders**
> `READ COMMITTED` removes the client-side retry burden, which is attractive for high-contention workloads, but it reopens the exact anomalies (lost updates, write skew) that cause overselling and double-spend. If you choose it, correctness must be restored explicitly (with `SELECT ... FOR UPDATE`, compare-and-set, or constraint checks), not assumed from the isolation level.

### 40001 retry error

A transaction retry error. All such errors share SQLSTATE `40001` and the message text "restart transaction." Under `SERIALIZABLE`, the application must catch `40001` and re-run the entire transaction from the beginning in a **client-side retry loop**; it is an expected, routine signal under contention, not a failure. See the [Transaction Retry Error Reference](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md).

> [!TIP]
>
> **Why it matters for orders**
> Any code path that writes a contended row (an inventory counter, a popular SKU, an order's state) will see `40001` under load. Handling it correctly (retry the whole transaction, with backoff) is mandatory; treating it as a hard error turns normal contention into failed checkouts.

### SELECT FOR UPDATE

A clause that takes an exclusive lock on the rows a transaction reads, so it can read-then-write them without another transaction intervening. CockroachDB queues contending transactions in read order, which raises throughput and lowers tail latency on hot, contended rows. See [SELECT FOR UPDATE](https://docs.cockroachlabs.com/docs/stable/select-for-update.md).

> [!NOTE]
>
> **Why it matters for orders**
> `SELECT ... FOR UPDATE` is the tool for serializing access to a single hot inventory row: readers line up instead of colliding and retrying. It reduces `40001` churn on the rows that get hammered, and it is the primary way to restore safety when running under `READ COMMITTED`.

### Range

The unit of data distribution and replication in CockroachDB: a contiguous span of the keyspace, replicated across nodes. A table's rows live in one or more ranges ordered by primary key. Ranges are the granularity at which data is placed, replicated, and load-balanced.

### Split

Dividing one range into two. CockroachDB splits ranges automatically when they grow too large, and **load-based splitting** divides a range that is receiving too much traffic so the load can spread across more nodes. See [Performance Best Practices](https://docs.cockroachlabs.com/docs/stable/performance-best-practices-overview.md).

### Hotspot / hot row

A range or single row receiving a disproportionate share of traffic, so one node's resources bottleneck the whole workload. Hotspots arise from **monotonically increasing keys** (every insert hits the latest range) or a **single frequently-updated row** (a shared counter). See [Performance Best Practices](https://docs.cockroachlabs.com/docs/stable/performance-best-practices-overview.md).

> [!NOTE]
>
> **Why it matters for orders**
> The two most natural order-system designs are both hotspots: a sequential order ID funnels every insert to one range, and a per-SKU stock counter funnels every sale of a popular product to one row. This is why the schema uses UUID keys and why a bestselling SKU counter needs deliberate treatment (`SELECT ... FOR UPDATE`, sharding, or a ledger).

### Leaseholder

The single replica of a range that coordinates all reads and writes for that range at a given time. The leaseholder is where a range's traffic lands; concentrating load on one range therefore concentrates it on one leaseholder, which is the mechanism behind a hot row's impact. See [Performance Best Practices](https://docs.cockroachlabs.com/docs/stable/performance-best-practices-overview.md).

### Follower read

A read served from the nearest replica rather than the leaseholder, trading freshness for locality and lower latency. Follower reads are **read-only** and slightly **stale**: they run `AS OF SYSTEM TIME follower_read_timestamp()`, which resolves to roughly 4.2 seconds or more in the past. See [Follower Reads](https://docs.cockroachlabs.com/docs/stable/follower-reads.md).

> [!TIP]
>
> **Why it matters for orders**
> Follower reads are excellent for order history, reporting, and "my past orders" views, where a few seconds of staleness is irrelevant and local latency matters. They are wrong for the checkout path. Never make an inventory or state decision on a stale read. Keep the write path on the leaseholder; push the read-heavy, tolerant-of-staleness queries to followers.

### Changefeed / CDC

Change Data Capture: a changefeed streams row-level changes from CockroachDB to an external sink (Kafka, a webhook, cloud storage, or Pub/Sub). Delivery is **at-least-once**, ordering is guaranteed **per key only**, and **duplicates are possible**. **Resolved timestamps** are periodic markers guaranteeing no earlier change is still outstanding, giving downstream consumers a consistency barrier. See the [Change Data Capture Overview](https://docs.cockroachlabs.com/docs/stable/change-data-capture-overview.md).

> [!NOTE]
>
> **Why it matters for orders**
> A changefeed on `order_events` or an `outbox` table is how order changes reach warehouses, email, and analytics. Because delivery is at-least-once with per-key ordering and possible duplicates, every consumer must be idempotent (see inbox) and must not assume global ordering across different orders. Resolved timestamps are what let a consumer know a window of changes is complete.

### REGIONAL BY ROW

A multi-region table setting in which each row is homed in a specific region, stored in a hidden region column, so a row's data lives close to the users that access it. It lets a single logical table keep European orders in Europe and US orders in the US while remaining one table. See the [Multi-Region Overview](https://docs.cockroachlabs.com/docs/stable/multiregion-overview.md).

### Survival goal

The failure the database is configured to survive without losing availability. **ZONE** survival (the default) tolerates the loss of a zone within a region; **REGION** survival tolerates the loss of an entire region but requires at least three regions. See the [Multi-Region Overview](https://docs.cockroachlabs.com/docs/stable/multiregion-overview.md).

> [!NOTE]
>
> **Why it matters for orders**
> For a global order system, `REGIONAL BY ROW` plus a region survival goal decides both latency (local orders stay local) and resilience (a regional outage does not take down checkout). The choice of `ZONE` vs `REGION` survival is a direct availability-vs-cost decision. `REGION` needs three or more regions.

***

> [!TIP]
>
> **Names are a contract**
> Every name on this page is used identically across all five surfaces: the prose that explains the design, the SQL that implements it, the API payloads clients send and receive, the events the system emits, and the tests that verify it. `order_lines` is `order_lines` everywhere, not `orderLines` in one place and `line_items` in another. This consistency is what lets a developer or an AI agent build a correct piece of the system from the definition alone, without guessing what a word means or which spelling is canonical.
