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

# Why CockroachDB for Order Management

> Order management uses a small data model (orders, line items, inventory, payments) but runs a demanding workload.

Order management uses a small data model (orders, line items, inventory, payments) but runs a demanding workload. The system operates on money, stock, and customer trust. It must remain correct while many concurrent requests contend for the same rows, while external systems fail and retry, and while traffic rises by as much as 50× during a sale.

**Purpose.** This page describes the order-management workload, explains why it exceeds the guarantees of many databases, and summarizes the CockroachDB capabilities that keep it correct and available.

**Intended audience.** Engineers and architects designing or operating an order-management service, and automated agents generating code from this guide.

## Scope of this workload

Order management covers the status, flow, and state of inventory as it is purchased through orders, together with the returns that follow. The core entities are the order, its line items, the inventory those line items draw from, and the payment that settles them.

The workload is most often associated with retail and eCommerce, but it appears wherever a catalog, a cart, and a purchase funnel exist. Virtual-goods purchases in games, business-to-business distribution, online marketplaces, and food ordering all run the same pattern. The vocabulary of *basket*, *shopping cart*, *order*, and *inventory* identifies this workload regardless of industry.

Order management rarely stands alone. It typically operates alongside:

* **Payments**: authorizing, capturing, and refunding funds for an order. This guide addresses payments only at the order boundary; see [Payments & callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md).
* **Identity and access management**: authenticating the customer and authorizing the request.
* **Routing and logistics**: fulfilling and delivering the order after it is placed.

This guide covers the order and inventory core and defines the integration boundaries to those adjacent systems rather than implementing them. A single order-management service also commonly spans multiple markets or geographies; running a separate stack per market produces data silos and prevents a single view of inventory and orders. [Multi-region & scale](https://docs.cockroachlabs.com/docs/cookbook/order-management/multi-region-and-scale.md) describes how to serve multiple regions from one cluster.

## The order-management workload

An order service is not a single workload. It comprises several workloads with distinct access patterns and failure modes. Treating them as one is a common design mistake.

| Sub-workload | Access pattern | Dominant risk |
| - | - | - |
| **Order write path** | Short bursty transactions; create / update one order | A retry creating a *second* order |
| **Inventory & reservations** | Many writers converging on a few hot rows | **Overselling**; hot-row contention collapsing throughput |
| **Payment** | External, asynchronous, retried by design | Double charge; a captured payment never recorded |
| **Fulfillment & status** | Moderate writes spread across many rows | Illegal state transitions; partial-shipment accounting |
| **Order history & ops reads** | Read-heavy, latency-tolerant | Over-provisioning the hot path to serve cold reads |

The traffic has three properties that compound one another:

1. **Contention is concentrated.** On a normal day, load is distributed. During a product drop or flash sale, demand concentrates on a single SKU's inventory row. That row's throughput then limits the throughput of the entire system.
2. **Everything is retried.** Mobile clients time out and resend. Payment providers deliver webhooks at-least-once and out of order. Internal services retry on transient errors. Any operation that is not idempotent will eventually run twice.
3. **Peaks are large and scheduled.** Seasonal sales, a product launch, and a daily rush for food ordering produce predictable spikes. The database must absorb the spike, or the business loses revenue during its highest-demand period.

## What "correct" means here: the invariants

These are the properties that must *never* break. Everything in this guide exists to protect one of them.

* **No overselling.** `committed + reserved ≤ on_hand`. You never sell the same unit twice.
* **No double charge.** At most one successful capture per order attempt; refunds never exceed captures.
* **No lost or duplicated orders.** A retried request produces *at most one* order and the same response both times.
* **Money is exact.** The amount charged equals the amount shown; totals equal the sum of their parts under a defined rounding rule; currencies never mix.
* **History is truthful.** Every state change is recorded and can never diverge from current state. You can reconstruct and audit any order.
* **The service stays up.** A node, zone, or even region failure does not stop customers placing orders.

The difficulty is holding all of these invariants simultaneously: under concurrency, across external systems, and during peak traffic.

## Why this breaks ordinary databases

Order teams commonly adopt CockroachDB after reaching the limits of one of three architecture classes:

* **Eventually-consistent, horizontally-scaled stores.** These systems scale writes well but permit overselling, because two buyers can read the same stock and both succeed. Without single-key linearizable guarantees and multi-statement transactions, the oversell invariant cannot be enforced at the database layer. Teams then add locks, queues, and reconciliation jobs in the application, which become their own source of outages.
* **Single-writer, vertically-scaled relational databases.** These systems provide correctness but reach a capacity ceiling. A planned traffic spike can exhaust vertical headroom, which drops requests and produces incomplete orders. Failover requires downtime, during which customers cannot place orders.
* **Manually-sharded or application-partitioned databases.** These systems achieve scale by moving distributed-systems problems into the application: cross-shard transactions, resharding, and the loss of a single global inventory view. The complexity remains, now owned by the application team.

Each class forces a choice between **scale** and **transactional correctness**. Order management requires both.

## What CockroachDB gives you

CockroachDB is a distributed SQL database. It scales horizontally and provides serializable, distributed ACID transactions. The following table maps its capabilities to the invariants above.

| You need | CockroachDB provides | Why it matters here |
| - | - | - |
| No overselling, no lost updates | **`SERIALIZABLE` isolation by default**: the strongest level; prevents write skew and lost updates | The guarded inventory decrement is safe under concurrency |
| Atomic multi-row changes | **Distributed ACID transactions** across the entire keyspace | Decrement stock, create the order, write the audit event, and enqueue the outbox message in *one* transaction |
| Absorb 50× peaks | **Horizontal scale**: add nodes, data rebalances automatically | A traffic spike is a capacity decision, not a correctness problem |
| Stay up through failure | **Multi-active availability**: survives node, zone, and (configurable) region loss with no failover downtime | Customers continue placing orders during the incident |
| Fast, correct writes near users | **Multi-region data homing** (`REGIONAL BY ROW`, survival goals) | A global catalog with locally-homed orders, without manual sharding |
| Hand off to external systems safely | **Changefeeds / CDC** | A transactional outbox that reliably drives payment, warehouse, and shipping integrations |
| Migrate without a rewrite | **PostgreSQL wire compatibility** | Existing drivers, ORMs, and SQL are largely compatible |

In summary, CockroachDB lets you develop the order service as a single, correct SQL database, then operate it at scale and across regions without sacrificing that correctness.

## Boundaries: what CockroachDB does not do

The following constraints are stated so they can be designed for, rather than discovered in production:

* **CockroachDB is not a cache for a hot counter.** A single flash-sale SKU row will become a hotspot. Design around it with a guarded decrement, `SELECT FOR UPDATE`, and counter sharding, covered later in this guide. The database does not eliminate contention; it provides correct tools to manage it.
* **It is not your payments ledger of record.** The payment provider is authoritative for money movement; CockroachDB is authoritative for your *intent and recorded outcome*. The double-entry ledger lives in the companion *Ledger*/*Wallet* guides.
* **`SERIALIZABLE` requires the application to handle retries.** Under contention, a transaction can return a `40001` retry error, and the application must wrap it in a retry loop. This is how correctness is preserved, and it is required work. It is documented here so it is implemented from the start.
* **Follower reads are stale by design.** They are appropriate for order history and incorrect for the oversell decision. Identifying which reads tolerate staleness is part of the design.

## How to read this guide

1. **[Terminology](https://docs.cockroachlabs.com/docs/cookbook/order-management/terminology.md)** and **[Using CockroachDB for order management](https://docs.cockroachlabs.com/docs/cookbook/order-management/using-cockroachdb-for-order-management.md)**: the shared vocabulary and how to think about the workload.
2. **Best practices**: the [data model](https://docs.cockroachlabs.com/docs/cookbook/order-management/schema-design.md), [transactions & retries](https://docs.cockroachlabs.com/docs/cookbook/order-management/transactions-and-sql.md), then the deep per-requirement pages: [lifecycle & idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md), [inventory & reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md), [money](https://docs.cockroachlabs.com/docs/cookbook/order-management/representing-money.md), [payments](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md), [fulfillment & returns](https://docs.cockroachlabs.com/docs/cookbook/order-management/fulfillment-and-returns.md), [external integration](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md), and [multi-region & scale](https://docs.cockroachlabs.com/docs/cookbook/order-management/multi-region-and-scale.md).
3. **Build & verify**: [set up](https://docs.cockroachlabs.com/docs/cookbook/order-management/setup.md) a cluster, run the [reference app](https://docs.cockroachlabs.com/docs/cookbook/order-management/reference-app.md), and prove correctness with [executable checks](https://docs.cockroachlabs.com/docs/cookbook/order-management/verification.md).
4. The **[evaluation tasks](https://docs.cockroachlabs.com/docs/cookbook/order-management/evaluation-tasks.md)** your agent should be able to pass.

> [!NOTE]
>
> **Supported versions**
> Baseline **CockroachDB v26.2.7+**, the latest LTS release. It includes GA `READ COMMITTED`, server-side triggers, and the current license model. Version boundaries called out at individual patterns record when a feature first shipped; all of them are available at this baseline.
