Skip to main content
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:
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.
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.
Because CockroachDB defaults to SERIALIZABLE 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 (SQLSTATE 40001). The application must wrap the transaction in a retry loop. Retry handling is required to preserve correctness under contention.
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 takes an exclusive lock and queues contending transactions in read order. Per the documentation, this increases throughput and decreases tail latency for contended operations.
[!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 more of them.

Consider READ COMMITTED with the guard in place

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.
A reservation hits one random shard with the same guard; availability is the sum across shards:
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 (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).
Treat expiry as a read-time decision, not a background one. Compute live availability by treating expired holds as already released:
Use Row-Level TTL 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.
[!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 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.

Tradeoffs

[!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 and the evaluation tasks.