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

# Transactions, isolation & retries

> The domain patterns in this guide depend on the mechanics described here.

The domain patterns in this guide depend on the mechanics described here. Order management is a contention problem: many writers compete for a few rows. CockroachDB addresses this with serializable transactions and client-managed retries. The domain patterns on later pages build on this model.

## `SERIALIZABLE` is the default isolation level

CockroachDB runs [`SERIALIZABLE`](https://docs.cockroachlabs.com/docs/stable/read-committed) by default. It is the strongest ANSI isolation level. It guarantees that concurrent transactions produce a result equivalent to some serial order. Under this guarantee, the following anomalies cannot occur:

* **Lost updates.** Two buyers decrement the last unit and both commit. This is the overselling bug.
* **Write skew.** Two transactions each read a consistent view and write based on it, but their combined effect violates an invariant.
* **Phantom reads.** A row appears or disappears mid-transaction.

For money and stock, this guarantee is what makes the guarded decrement and the state machine safe.

## Handling `40001` retry errors

Because the database does not permit a non-serializable outcome, a transaction that would violate serializability is aborted and must be retried. All such errors share [`SQLSTATE 40001`](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference) with a message containing "restart transaction." The application must wrap transactions in a retry loop. This is required for every transaction, and the loop is the same in each case:

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
for attempt in 1..MAX_RETRIES:
  try:
     BEGIN
       <statements>
     COMMIT
     break
  except error where SQLSTATE == '40001':
     sleep(exponential_backoff(attempt))
     continue
```

> [!NOTE]
>
> **One exception: `RETRY_COMMIT_DEADLINE_EXCEEDED`**
> Most `40001` errors should be retried, and the loop does not need to distinguish the subtypes. The exception is `RETRY_COMMIT_DEADLINE_EXCEEDED`, where retrying "may not be advisable" because the transaction is too long. The fix is to shorten the transaction rather than retry it. Keep order and inventory transactions small.

Many drivers and frameworks, including Cockroach Labs' own adapters, provide this loop. Use the provided loop where one exists, but do not run transactions without one.

## `READ COMMITTED` for extreme contention

[`READ COMMITTED`](https://docs.cockroachlabs.com/docs/stable/read-committed) is GA in **v24.1** (preview in v23.2). Under it, CockroachDB retries individual statements transparently, so the transaction never returns `40001` to the client, and no client retry loop is required. In exchange, it permits non-repeatable reads, phantoms, lost updates, and write skew, which are the anomalies that `SERIALIZABLE` forbids.

`READ COMMITTED` is therefore useful where the contention overhead of `SERIALIZABLE` is significant, such as a highly contended SKU, but only when correctness is re-established with explicit locks or guards:

* A single guarded `UPDATE ... WHERE available >= qty` is safe under `READ COMMITTED` because the row is locked and re-checked at write time.
* A read-then-write split across two statements is not safe under `READ COMMITTED` without `SELECT ... FOR UPDATE`.

Set it per transaction (`BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED`) or per session or role (`default_transaction_isolation`). It is enabled cluster-wide by default via `sql.txn.read_committed_isolation.enabled`.

> [!CAUTION]
>
> **The rule for `READ COMMITTED`**
> `READ COMMITTED` does not weaken invariants without cost. Keep every guard (`WHERE … >= …`) and every `FOR UPDATE`. `READ COMMITTED` removes serialization retries; it does not remove the need to prevent lost updates in the application. When you move a transaction to `READ COMMITTED`, document which anomalies the application now owns (lost update, write skew, phantoms) and how each is prevented.

## Reducing contention

The documented levers, roughly in order of reach:

1. **Touch fewer rows and use smaller transactions.** The less a transaction reads, and the shorter it is open, the smaller the conflict window.
2. **Lock early with [`SELECT … FOR UPDATE`](https://docs.cockroachlabs.com/docs/stable/select-for-update).** Acquire the exclusive lock up front so that contenders queue in read order instead of colliding and retrying. The documentation notes that this *increases throughput and decreases tail latency for contended operations*.
3. **Read historical data with `AS OF SYSTEM TIME`.** Historical and [follower reads](https://docs.cockroachlabs.com/docs/stable/follower-reads.md) do not conflict with writes, which suits history and dashboards.
4. **Use `UPSERT`** instead of read-then-insert or update where applicable.
5. **Send the transaction as a single batch** so that CockroachDB can auto-retry more of it server-side.

### Locking details worth knowing

* `UPDATE` and `UPSERT` already take an implicit `FOR UPDATE` on the rows they touch.
* `FOR SHARE` takes a shared (multi-reader) lock. It is primarily for `READ COMMITTED`, because shared locks are not enabled by default for `SERIALIZABLE`.
* Under `SERIALIZABLE`, `FOR UPDATE` locks are by default fast, in-memory, unreplicated locks. They are best-effort and can be dropped on a lease transfer or range split. Serializability is still guaranteed in that case; only the queueing benefit is lost. Set `enable_durable_locking_for_serializable = true` if the locks must survive those events, at a latency cost. This caveat does not apply under `READ COMMITTED`.
* Wait policies: `SKIP LOCKED` skips already-locked rows, which is useful for queue-like scans, and `NOWAIT` fails instead of waiting.

## Claiming work without blocking (`SKIP LOCKED`)

For queue-like workloads, such as a worker pool draining the `outbox`, reclaiming expired reservations, or processing jobs, each worker should claim a different row without blocking on rows another worker already holds. `SELECT ... FOR UPDATE SKIP LOCKED` locks and returns only currently unlocked rows, skipping the rest:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT id, payload FROM outbox
 ORDER BY created_at
 LIMIT 100
 FOR UPDATE SKIP LOCKED;     -- each worker claims a disjoint batch
```

Pair it with a short critical section and a selective, well-indexed claim query so that workers spend their time doing work rather than contending.

## The pattern used by every domain page

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
retry-loop:
  BEGIN
    <guarded write: UPDATE ... WHERE <invariant still holds>>   -- 0 rows → reject
    <insert the records + the audit event + the outbox row>     -- all atomic
  COMMIT
```

One small serializable transaction, a guard that rejects at zero rows, and everything that must be atomic committed together. See [Inventory & reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md), [Order lifecycle & idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md), and [Payments & callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md) for the concrete applications.

## Tradeoffs

| Dimension | `SERIALIZABLE` | `READ COMMITTED` |
| - | - | - |
| Correctness | No lost updates / write skew / phantoms | Permits them. You must add guards/locks |
| Client code | Must handle `40001` retry loop | No client retry loop (statements retry internally) |
| Hot-row cost | Retries/backoff under heavy contention | Sheds serialization retries |
| Use for | Order, payment, state transitions (default) | Extreme hot counters, *with* guards/locks |
