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

# Inventory & reservations

> Inventory management is the most demanding part of an order-management system.

Inventory management is the most demanding part of an order-management system. Every pattern on this page protects one invariant:

> **You never sell a unit you don't have.** For every SKU, `committed + reserved ≤ on_hand`, and `available` never drops below zero.

A design that is too permissive oversells: the system accepts payment for stock it cannot ship, then cancels orders and issues refunds. A design that is too conservative produces phantom stockouts: holds that never expire cause in-stock items to appear unavailable. Both failure modes must be prevented under peak load, when a large volume of concurrent requests targets a single row.

The following sections present the design in steps. Each step addresses a limitation of the previous one.

## The concurrency problem

The primary failure mode is a lost update. Two requests run concurrently for the last unit:

```
Buyer A: read available = 1   ─┐
Buyer B: read available = 1   ─┤  both see 1
Buyer A: write available = 0  ─┤  both write 0
Buyer B: write available = 0  ─┘  → TWO orders, ONE unit. Oversold.
```

Without external locking, this outcome is difficult to prevent on an eventually consistent store. CockroachDB prevents it by default, provided the transaction is written correctly.

## Pattern 1: Guarded decrement

Model inventory as a counter with a non-negativity constraint. Make the decrement conditional on sufficient stock.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE inventory (
  sku       STRING PRIMARY KEY,
  on_hand   INT NOT NULL CHECK (on_hand   >= 0),
  reserved  INT NOT NULL DEFAULT 0 CHECK (reserved >= 0),
  available INT AS (on_hand - reserved) STORED CHECK (available >= 0)
);
```

The reservation is a single guarded `UPDATE`. The `WHERE` clause enforces the invariant: if stock is insufficient, the statement matches **zero rows** and the sale is rejected atomically, with no race.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- Returns rows-affected = 1 on success, 0 if insufficient stock.
UPDATE inventory
   SET reserved = reserved + $qty
 WHERE sku = $sku
   AND on_hand - reserved >= $qty;   -- the guard
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  UPDATE inventory SET reserved = reserved + :qty
    WHERE sku = :sku AND on_hand - reserved >= :qty;
  -- if rows_affected = 0  → ROLLBACK, return OUT_OF_STOCK
  INSERT INTO reservations (sku, order_id, qty, expires_at)
    VALUES (:sku, :order_id, :qty, now() + INTERVAL '15 minutes');
COMMIT;
```

Because CockroachDB defaults to [`SERIALIZABLE`](https://docs.cockroachlabs.com/docs/stable/read-committed) isolation, the two concurrent transactions cannot both commit. One transaction's read is invalidated by the other's write, forcing it to retry. On retry it re-reads `available = 0`, and its guard fails. Exactly one transaction succeeds.

> [!WARNING]
>
> **You must handle `40001`**
> Under `SERIALIZABLE`, a contended transaction can return a [transaction retry error](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md) (`SQLSTATE 40001`). The application **must** wrap the transaction in a retry loop. Retry handling is required to preserve correctness under contention.
>
> ```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> for attempt in 1..MAX:
>   try:    BEGIN; &lt;guarded decrement + insert>; COMMIT; break
>   except SQLSTATE 40001: sleep(backoff * attempt); continue
> ```

The `CHECK (available >= 0)` constraint is a backstop: no code path can drive stock negative.

## Pattern 2: Contended rows

The guarded decrement is correct at any scale, but correctness does not guarantee throughput. During a high-demand event, many transactions target one SKU's row. They serialize on that row's leaseholder, and under `SERIALIZABLE` the transactions that lose the race return `40001` retries and back off. Throughput on that row, and therefore the checkout rate for the contended item, plateaus.

Three techniques address this, in order of preference.

### Lock early with `SELECT ... FOR UPDATE`

Acquire the row lock before the read instead of allowing transactions to collide and retry. [`SELECT ... FOR UPDATE`](https://docs.cockroachlabs.com/docs/stable/select-for-update) takes an exclusive lock and **queues** contending transactions in read order. Per the documentation, this *increases throughput and decreases tail latency for contended operations*.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
  SELECT on_hand - reserved AS available
    FROM inventory WHERE sku = $sku FOR UPDATE;   -- queue here
  -- app checks available >= qty
  UPDATE inventory SET reserved = reserved + $qty WHERE sku = $sku;
  INSERT INTO reservations (...);
COMMIT;
```

> [!NOTE]
>
> **Lock durability nuance**
> Under `SERIALIZABLE`, `FOR UPDATE` locks are by default in-memory **unreplicated** locks. They are best-effort and can be lost on a lease transfer or range split. Correctness is still guaranteed by the serializable check; only the queueing benefit is lost in that event. To make the lock survive those events, set `enable_durable_locking_for_serializable = true`, at a latency cost. `UPDATE` already takes an implicit `FOR UPDATE`.

### Keep the transaction small and batched

Each additional statement lengthens the time the contended row is held. Include only the decrement and the reservation insert in the transaction; defer all non-essential work. Sending the statements as a single batch allows CockroachDB to [auto-retry](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md) more of them.

### Consider `READ COMMITTED` with the guard in place

[`READ COMMITTED`](https://docs.cockroachlabs.com/docs/stable/read-committed) (GA in v24.1) does not return serialization retry errors. It retries individual statements transparently, so the contended row avoids the `40001` and backoff overhead. However, `READ COMMITTED` **permits lost updates**, which is the concurrency failure described above. Under `READ COMMITTED`, the guarded `UPDATE ... WHERE available >= qty` (or `SELECT ... FOR UPDATE`) is **mandatory**. The single-statement guarded `UPDATE` is safe under `READ COMMITTED` because the row is locked and re-evaluated at write time.

> [!CAUTION]
>
> **Never drop the guard**
> `READ COMMITTED` without the `WHERE available >= qty` guard (or a `FOR UPDATE` lock) oversells. The guard makes the lower isolation level safe.

## Pattern 3: Shard the counter for flash sales

Even when fully tuned, a *single logical row* has a throughput ceiling. For a flash sale, where a few SKUs receive very high concurrent write volume, split one SKU's stock across **N physical sub-rows** and distribute writers across them.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE inventory_shards (
  sku      STRING NOT NULL,
  shard    INT    NOT NULL,               -- 0..N-1
  on_hand  INT    NOT NULL CHECK (on_hand  >= 0),
  reserved INT    NOT NULL DEFAULT 0 CHECK (reserved >= 0),
  PRIMARY KEY (sku, shard)
);
```

A reservation hits one random shard with the same guard; availability is the sum across shards:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
-- reserve against a randomly chosen shard
UPDATE inventory_shards
   SET reserved = reserved + $qty
 WHERE sku = $sku AND shard = $rand_shard
   AND on_hand - reserved >= $qty;        -- 0 rows → try another shard, or OUT_OF_STOCK

-- availability across all shards (tolerant, for display)
SELECT sum(on_hand - reserved) AS available
  FROM inventory_shards WHERE sku = $sku;
```

This trades read complexity for write throughput. Reads must aggregate N rows, and a request can fail on an empty shard while stock exists on another, so the application may need to retry across shards near sell-out. In return, write throughput scales to N times the single-row ceiling. Keep N modest and matched to measured contention.

> [!NOTE]
>
> **Sharding a counter ≠ hash-sharded indexes**
> [Hash-sharded indexes](https://docs.cockroachlabs.com/docs/stable/hash-sharded-indexes.md) (`USING HASH`) address a *sequential-key* write hotspot on an index. A single contended *logical counter* is a distinct problem. Splitting it into sub-rows is an application-level pattern, not a function of an index.

## Reservations and expiry

A reservation is a time-bounded hold. It ensures an abandoned cart eventually returns its stock.

> [!NOTE]
>
> **Basket availability is not a reservation**
> Distinguish two concepts. **Soft availability** is the value shown while a shopper browses or fills a basket; it is a display value and tolerant of slight staleness. A **durable reservation** is created at checkout; it holds stock and must be strongly consistent. Only the durable reservation decrements real availability. Modeling the two as one leads to overselling (soft holds treated as durable) or phantom stockouts (display holds never released).

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE reservations (
  id         UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  sku        STRING NOT NULL REFERENCES inventory(sku),
  order_id   UUID   NOT NULL,
  qty        INT    NOT NULL CHECK (qty > 0),
  state      STRING NOT NULL DEFAULT 'held'
             CHECK (state IN ('held','committed','released','expired')),
  expires_at TIMESTAMPTZ NOT NULL
);
```

Treat expiry as a read-time decision, not a background one. Compute live availability by treating expired holds as already released:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT i.on_hand
     - COALESCE(sum(r.qty) FILTER (
         WHERE r.state = 'held' AND r.expires_at > now()), 0) AS available
  FROM inventory i
  LEFT JOIN reservations r ON r.sku = i.sku
 WHERE i.sku = $sku
 GROUP BY i.on_hand;
```

Use [Row-Level TTL](https://docs.cockroachlabs.com/docs/stable/row-level-ttl.md) only to **garbage-collect** expired rows, not to release stock in real time. Its deletion runs as a batched background job (`ttl_job_cron`, default `@daily`), so a row can outlive its `expires_at` before it is physically removed.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
ALTER TABLE reservations SET (ttl_expiration_expression = 'expires_at');
```

> [!WARNING]
>
> **Don't rely on TTL for correctness**
> If availability depended on TTL having *already deleted* expired rows, stock would be under-counted during the interval between expiry and the next TTL job run. Always filter `expires_at > now()` at read time, and use TTL only for cleanup.

When an order is paid, set the hold to `committed` and move stock from `reserved` to sold in the same transaction. When an order is cancelled or expires, release the stock.

## Multi-region inventory

Do not serve inventory decisions from a stale replica. The oversell decision must be a fresh write against the leaseholder. [Follower reads](https://docs.cockroachlabs.com/docs/stable/follower-reads.md) are appropriate for *displaying* "In stock" on a product page, where slight staleness is acceptable, but not for the decrement. For global catalogs with centralized stock, keep inventory `REGIONAL BY TABLE` (or a single home region) rather than `GLOBAL`. See [Multi-region & scale](https://docs.cockroachlabs.com/docs/cookbook/order-management/multi-region-and-scale.md).

## Tradeoffs

| Choice | Option A | Option B | Guidance |
| - | - | - | - |
| Stock model | Single guarded counter row | Reservation ledger (sum holds) | Counter for throughput; ledger when you need per-hold audit |
| Isolation on the decrement | `SERIALIZABLE` (retry loop, no lost update) | `READ COMMITTED` (no serialization retries, **needs guard/lock**) | `SERIALIZABLE` by default; `READ COMMITTED`+guard for extreme hot rows |
| Hot SKU | `SELECT FOR UPDATE` on one row | Shard the counter into N rows | `FOR UPDATE` first; shard only for true flash-sale SKUs |
| Expiry | Read-time filter (`expires_at > now()`) | Background TTL release | Read-time for correctness; TTL only to GC |

> [!CAUTION]
>
> **Anti-patterns**
>
> * Read-then-write availability in two statements **without** a guard or `FOR UPDATE` → oversold under concurrency.
> * Serving the oversell decision from a **follower read** → oversold on stale data.
> * Relying on **Row-Level TTL** to release stock in real time → phantom stockouts.
> * `FLOAT` or unconstrained `INT` for stock with no `CHECK (… >= 0)` backstop.

## Verify it

Load-test the contended path at approximately **2× expected peak**. With `on_hand = 1` and 50 concurrent buyers, exactly one order is created, `available = 0`, and 49 requests return `OUT_OF_STOCK`. See [Verification](https://docs.cockroachlabs.com/docs/cookbook/order-management/verification.md) and the [evaluation tasks](https://docs.cockroachlabs.com/docs/cookbook/order-management/evaluation-tasks.md).
