Decompose the workload, then pick the tool
Treat order management as five sub-workloads. Each requires a specific CockroachDB primitive. Using a single primitive for all of them over-engineers some parts and under-engineers others.
Order write path. Creating an order is a short transaction: insert into
orders, insert the order_lines, write the first order_events row, and record the idempotency_keys entry, all together. The one risk is duplication: mobile clients time out and resend, and the gateway retries. Insert the idempotency key in the same transaction as the effect so a duplicate collides on the primary key and returns the stored response instead of creating a second order. CockroachDB’s default SERIALIZABLE isolation makes this an atomic all-or-nothing operation, and a 40001 retry under contention is re-run by the client retry loop (transactions, retry error reference).
Inventory & reservations. This is the only sub-workload where many writers contend for the same rows. The oversell invariant (committed + reserved ≤ on_hand) must hold under full concurrency. Enforce it with a guarded decrement (UPDATE inventory SET available = available - $qty WHERE sku = $sku AND available >= $qty): zero rows affected is the rejection. Under SERIALIZABLE this is safe against write skew and lost updates. Use SELECT ... FOR UPDATE to serialize contending writers, which raises throughput and reduces tail latency on a hot row instead of letting writers collide and retry (SELECT FOR UPDATE). This is the most contention-sensitive part of the system; see Transactions & SQL and the dedicated inventory deep-dive.
Payment. Money movement resides in an external provider that is authoritative and asynchronous. Never call it from inside a transaction. Record your intent in an outbox row, commit, and let a relay make the call. Provider webhooks arrive at-least-once and out of order, so dedupe them in a payment_events inbox keyed by provider_event_id and advance order state monotonically. The provider is authoritative for the money; CockroachDB is authoritative for your recorded intent and outcome.
Fulfillment & status. An order follows a state machine: created → paid → fulfilling → shipped → delivered, with cancelled/returned branches. Every transition is a guarded UPDATE ... WHERE id = $id AND status = $expected: a stale or illegal transition touches zero rows and is rejected, not silently applied. Pair every transition with an append-only order_events insert in the same transaction so state and audit can never diverge.
History & ops reads. Order history, customer “my orders” views, and operational dashboards are read-heavy and do not require the most current data. Serve them from the nearest replica with follower reads / bounded staleness, which keeps cold reads off your leaseholders and out of the write hot path (follower reads).
Core design rule: one serializable transaction, then an outbox
[!TIP]
The primary design rule
Do all the money- and stock-critical mutations in one SERIALIZABLE transaction, and push everything external to an outbox relayed by a changefeed.
When an order is placed, four things must become true together or not at all:
- Decrement stock (the guarded
UPDATEoninventory, plus thereservationsrow). - Create the order (
orders+order_lines, and theidempotency_keysentry). - Write the audit event (the first
order_eventsrow). - Enqueue the outbox message that will later drive payment, the warehouse, and shipping.
Which reads must be fresh, and which may be stale
This split is a deliberate design decision.- Must be fresh: the oversell decision. The read that feeds the inventory decrement sees the leaseholder: it is the current transaction’s own guarded
UPDATE, underSERIALIZABLE, optionally withFOR UPDATE. Never serve the stock-critical path from a stale replica. - May be stale: history, dashboards, “my orders.” These tolerate a bounded lag of a few seconds. Use follower reads so they scale on the nearest replica and never compete with the write path (follower reads). Follower reads are read-only by construction, which is exactly right: nothing that mutates money or stock should ever run against one.
Where contention concentrates
On an ordinary day, load spreads across many SKUs and the system operates comfortably. During a product drop or flash sale, demand concentrates on a single SKU’s inventory row, and that row’s throughput then limits the throughput of the entire system. This is the predictable failure point. The tools are guarded writes,SELECT ... FOR UPDATE to serialize contenders, small single-batch transactions, and counter sharding for extreme cases, covered in full on the inventory page. Plan for the hot SKU before the sale, not during the incident.
Topology at a glance
[!NOTE] Start simple, add regions when a requirement demands it Begin single-region: one region, replicas across its availability zones. This survives node and zone failure with no failover downtime and keeps write latency low, and it is the correct starting point for almost every order service.Adopt multi-region when you need locality (orders written close to customers on different continents) or region survival (the service keeps taking orders through the loss of a whole region). Then: home order rows to their region with
REGIONAL BY ROW, make read-mostly reference data (catalog, SKU metadata) GLOBAL for fast local reads everywhere, and choose a survival goal: ZONE (survive a zone) or REGION (survive a region, at higher write latency). The companion multi-region page works these choices end to end; do not incur their latency cost until a locality or survival requirement demands it.
