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

# Architecture and request flow

> This page gives the end-to-end picture that the rest of the guide fills in.

This page gives the end-to-end picture that the rest of the guide fills in. It names the components of an order service built on CockroachDB, shows how they fit together, and then traces a single request, placing an order, from the client call to fulfillment. Read it first; every later page is a detailed treatment of one step described here.

## Purpose and audience

This guide is an implementation specification for an **order service**: the application that accepts customer orders, holds stock, charges payment, and drives fulfillment, with CockroachDB as its system of record. A **system of record** is the authoritative store for a piece of data; here it is the database that owns order, inventory, and payment-intent state.

The guide is written for two audiences:

* **Developers** building or operating an order service and choosing the patterns that keep it correct under load.
* **AI agents** generating or reviewing such a service. Each page states its invariants, shows concrete DDL and SQL, and ends in checks an agent can run (see [Verification](https://docs.cockroachlabs.com/docs/cookbook/order-management/verification.md) and [Evaluation tasks](https://docs.cockroachlabs.com/docs/cookbook/order-management/evaluation-tasks.md)).

The guide assumes familiarity with SQL and transactions but not with CockroachDB specifically. Terms are defined on first use; see also [Terminology](https://docs.cockroachlabs.com/docs/cookbook/order-management/terminology.md).

## Component overview

The system has four tiers and three external systems.

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
          ┌────────────┐
          │   Client   │  web / mobile / partner API
          └─────┬──────┘
                │  HTTPS, Idempotency-Key header
          ┌─────▼──────┐
          │ API layer  │  auth, validation, rate limiting
          └─────┬──────┘
                │
          ┌─────▼────────────┐
          │  Order service   │  application tier: business logic,
          │ (application tier)│  SERIALIZABLE transactions, retry loop
          └─────┬────────────┘
                │  Postgres wire protocol
          ┌─────▼────────────┐
          │   CockroachDB    │  system of record:
          │                  │  orders, inventory, payments, outbox, ...
          └─────┬────────────┘
                │  changefeed / outbox relay + inbox
   ┌────────────┼─────────────────┐
   ▼            ▼                  ▼
Payment      Warehouse          Shipping
provider     / WMS              / carrier
```

* **Client / API layer.** Accepts requests, authenticates and validates them, and forwards each call to the order service. Clients retry, so every state-changing call carries a caller-supplied **idempotency key**, a token that lets the server recognize a retry of the same logical request.
* **Order service (application tier).** Holds the business logic. It opens CockroachDB transactions, enforces state transitions, and wraps every transaction in a retry loop for transaction retry errors (`SQLSTATE 40001`). It is stateless and horizontally scalable; correctness lives in the database, not in the process.
* **CockroachDB (system of record).** A distributed SQL database that is strongly consistent and, by default, uses `SERIALIZABLE` isolation. It owns the authoritative state for orders, line items, inventory, reservations, payment intent, and the audit log. It is also compatible with the PostgreSQL wire protocol, so existing drivers and tools connect to it unchanged.
* **External systems.** The **payment provider** (money movement), the **warehouse management system (WMS)** (picking and packing), and the **shipping carrier** (delivery) are systems of *action*, reached asynchronously. The database never calls them inside a transaction. Instead, each committed change writes a row to a **transactional outbox** table, and a relay driven by **changefeeds** (CockroachDB's change-data-capture mechanism) delivers those rows outward. Inbound callbacks are absorbed through an **inbox**. See [External integration](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md).

## Request flow: placing an order

The following steps trace one `POST /orders` request. Steps 1 to 4 execute inside a single `SERIALIZABLE` transaction; steps 5 to 6 happen asynchronously after commit.

1. **Idempotency check.** The service reads the request's idempotency key. If the key already exists and its work is complete, it returns the stored response and does nothing else. A retry produces no second order. If the key is new, it is claimed in the same transaction as the work below. See [Order lifecycle and idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md).

2. **Inventory reservation (guarded).** For each line item, the service issues a *guarded* decrement, an `UPDATE` whose `WHERE` clause requires sufficient stock. If stock is insufficient, the statement matches zero rows and the order is rejected atomically, with no overselling race. See [Inventory and reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md).

3. **Write order, lines, audit event, and outbox row, atomically.** In the same transaction, the service inserts the `orders` row, its `order_lines`, an `order_events` audit record, and an `outbox` row describing the downstream message. Because they commit together, state and history can never diverge, and no message is ever emitted for a change that rolled back.

4. **Commit (with retry).** The transaction commits. Under contention it may return a transaction retry error (`SQLSTATE 40001`); the service's retry loop re-runs the whole transaction. Only after commit does the caller receive a success response.

5. **Asynchronous payment capture.** The outbox row drives a request to the payment provider, keyed by a service-generated idempotency key. The provider's webhooks return through the inbox, which deduplicates them and advances payment state forward only. See [Payments and callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md).

6. **Fulfillment.** Once payment is captured, further outbox events notify the WMS and carrier, and shipment and return records track the physical flow. See [External integration](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md).

> [!NOTE]
>
> **Why one transaction for steps 1 to 4**
> Combining the idempotency claim, the guarded reservation, and the order, line, event, and outbox writes into a single `SERIALIZABLE` transaction is what makes the core path correct: either every effect of placing the order is recorded, or none is. Splitting these into separate transactions reintroduces the double-order, oversell, and lost-message races the rest of the guide works to eliminate.

## Environmental assumptions and prerequisites

* **CockroachDB v26.2.7 or later** (the latest LTS release). Every pattern referenced in this guide, including server-side triggers, is available at this version. Version boundaries noted elsewhere in the guide record when a feature first shipped; confirm feature availability against your target release.
* **A PostgreSQL-protocol driver.** The order service connects over the PostgreSQL wire protocol using any standard driver (for example, pgx, pg, or psycopg). No CockroachDB-specific client is required.

For the full installation and bring-up sequence, see [Setup](https://docs.cockroachlabs.com/docs/cookbook/order-management/setup.md).
