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

# Find and fix transaction contention

> Reproduce a 40001 retry error and a blocked write, find the blocking session, and fix the transaction so it waits briefly instead of failing.

> [!NOTE]
>
> **Recipe** · 20 minutes · **Works on:** Cockroach Continuum, CockroachDB Cloud, self-hosted · **Verified on:** CockroachDB v26.4.1, Dec 1, 2026

## What you'll fix

A stock reservation that reads a row, decides in the application, and writes it back. Under load it fails with `SQLSTATE 40001` (`restart transaction`), or it sits waiting behind another transaction. You'll reproduce both, find the blocker, and fix the write so concurrent requests queue briefly and succeed.

CockroachDB runs transactions at `SERIALIZABLE` isolation by default. When two transactions touch the same row, one of them either waits for the other's lock or is asked to retry. That conflict is called *transaction contention*. A little is normal. A lot shows up as retry errors and slow requests.

## Start a cluster

You need two SQL shells connected to the same cluster.

> [tab] Cockroach Continuum
>
> Create a free cluster by following the [Continuum quickstart](https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart.md), then open two SQL shells with the connection string from the Console.

> [tab] Local (self-hosted)
>
> [Install CockroachDB](https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-mac.md), then start a local single-node cluster and open two SQL shells:
>
> ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> cockroach start-single-node --insecure --store=contention-demo --background
> cockroach sql --insecure
> ```
>
> Run `cockroach sql --insecure` again in a second terminal.

## Create the schema

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

INSERT INTO inventory VALUES ('sku-1', 100);
```

## Reproduce the retry error

Run these in order, switching shells where shown. Both transactions read `100`, and both try to write `99`.

| Step | Shell A | Shell B |
| - | - | - |
| 1 | `BEGIN;` | |
| 2 | `SELECT qty FROM inventory WHERE sku = 'sku-1';` returns `100` | |
| 3 | | `BEGIN;` |
| 4 | | `SELECT qty FROM inventory WHERE sku = 'sku-1';` returns `100` |
| 5 | | `UPDATE inventory SET qty = 99 WHERE sku = 'sku-1';` |
| 6 | | `COMMIT;` |
| 7 | `UPDATE inventory SET qty = 99 WHERE sku = 'sku-1';` | |

Shell A fails:

```
ERROR: restart transaction: TransactionRetryWithProtoRefreshError: WriteTooOldError: ...
SQLSTATE: 40001
```

This is CockroachDB protecting you. If shell A's write had succeeded, two reservations would have left the count at `99` instead of `98`: a lost update. Run `ROLLBACK;` in shell A.

## Reproduce a blocked write

Reset the row with `UPDATE inventory SET qty = 100 WHERE sku = 'sku-1';`, then:

| Step | Shell A | Shell B |
| - | - | - |
| 1 | `BEGIN;` | |
| 2 | `UPDATE inventory SET qty = qty - 1 WHERE sku = 'sku-1';` | |
| 3 | | `UPDATE inventory SET qty = qty - 1 WHERE sku = 'sku-1';` hangs |

Shell B waits for shell A's lock. In a real application, shell A is the request that opened a transaction and then called a slow service before committing.

## Find the blocker

**In the Console.** Open the **Transactions** page and look at **Active Executions**. The waiting transaction shows `Waiting` in the **Status** column, and its details name the transaction blocking it. Use the [Cloud Console Transactions page](https://docs.cockroachlabs.com/docs/cockroachcloud/transactions-page.md), or the [DB Console Transactions page](https://docs.cockroachlabs.com/docs/stable/ui-transactions-page.md#active-executions-table) for self-hosted clusters. After the fact, the **Insights** page flags these as **High Contention**.

**In SQL.** From a third shell, join the cluster's locks to the transactions that hold or want them:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT l.granted, t.session_id, l.txn_id, l.duration
FROM crdb_internal.cluster_locks AS l
JOIN crdb_internal.cluster_transactions AS t ON t.id = l.txn_id
WHERE l.table_name = 'inventory';
```

```
  granted |            session_id            |                txn_id                |    duration
----------+----------------------------------+--------------------------------------+------------------
     t    | 18ed29b3edf833580000000000000001 | 789615b3-402d-432c-89cc-c3c031ab489d | 00:00:01.527294
     f    | 18ed29b4191d17880000000000000001 | d3cdaca1-94d2-4daa-b702-c4a4586dd968 | 00:00:00.803964
```

The row with `granted = t` holds the lock: that session is the blocker. The row with `granted = f` is waiting for it. Reading these tables needs the `VIEWACTIVITY` privilege, which `admin` users have.

If the blocker is stuck, cancel its session. Its transaction rolls back and the waiting update completes:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CANCEL SESSION '18ed29b3edf833580000000000000001';
```

After the fact, [`crdb_internal.transaction_contention_events`](https://docs.cockroachlabs.com/docs/stable/crdb-internal#transaction_contention_events) records each wait as a `LOCK_WAIT` event, and [`crdb_internal.cluster_contended_indexes`](https://docs.cockroachlabs.com/docs/stable/crdb-internal#cluster_contended_indexes) shows which indexes saw the most contention.

## Fix it

Pick the first fix that fits. Each was run against the same two-shell setup.

**1. Do it in one statement.** Let the database do the read, the check, and the write. A single statement is an implicit transaction that CockroachDB can retry for you, and it holds the lock only for as long as the statement runs:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
UPDATE inventory
SET qty = qty - 1
WHERE sku = 'sku-1' AND qty >= 1
RETURNING qty;
```

Eight of these run at the same time all succeed with no errors, and `qty` drops by exactly 8. No rows returned means out of stock.

**2. If you must read first, lock the row as you read it.** [`SELECT ... FOR UPDATE`](https://docs.cockroachlabs.com/docs/stable/select-for-update) takes the lock at the read, so the second transaction waits instead of failing later:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
BEGIN;
SELECT qty FROM inventory WHERE sku = 'sku-1' FOR UPDATE;
-- application logic here, kept short
UPDATE inventory SET qty = 99 WHERE sku = 'sku-1';
COMMIT;
```

Rerun the retry-error steps with `FOR UPDATE` on both reads. Shell B's read now waits at step 4. Finish shell A with its `UPDATE` and `COMMIT`, and shell B's read returns `99`. Its update then writes `98`. Nothing fails, and no update is lost.

**3. Keep transactions short.** Never call another service, wait on a user, or sleep inside a transaction. Do that work before `BEGIN` or after `COMMIT`.

**4. Always handle `40001` anyway.** Contention can't be removed entirely. Wrap explicit transactions in a [client-side retry loop](https://docs.cockroachlabs.com/docs/stable/advanced-client-side-transaction-retries.md), with backoff. Pair it with an [idempotency key](https://docs.cockroachlabs.com/docs/cookbook/idempotent-writes.md) so a retry can never apply twice.

## How it fails

| Situation | What happens | What the client does |
| - | - | - |
| Two read-then-write transactions on the same row | One gets `40001` (`RETRY_WRITE_TOO_OLD` or `RETRY_SERIALIZABLE`) | Retry the whole transaction |
| A transaction holds a lock and its client goes quiet | Other writers to that row wait | Find it and `CANCEL SESSION`, then fix the code path |
| Many writers on one row, such as a global counter | Even short transactions queue | Split the row. See [Understand hotspots](https://docs.cockroachlabs.com/docs/stable/understand-hotspots.md) |
| A long-running report reads rows that writers update | The report or the writers retry | Read at a past timestamp with [`AS OF SYSTEM TIME`](https://docs.cockroachlabs.com/docs/stable/as-of-system-time) |

## Trade-offs and when not to use it

* **`FOR UPDATE` turns retries into waiting.** That is usually better, but a long transaction holding the lock now blocks everyone. Keep the locked section short.
* **The single statement only works when the decision fits in SQL.** If the business rule needs data from another service, fetch it before the transaction.
* **`READ COMMITTED` changes the trade-off.** Under [`READ COMMITTED`](https://docs.cockroachlabs.com/docs/stable/read-committed) isolation you see fewer retry errors, but read-then-write patterns can lose updates unless you lock with `FOR UPDATE`.

> [!NOTE]
>
> **On Cockroach Continuum with Cockroach Aegis (private preview):** Aegis reports contention as it happens and explains which transactions conflict. See [Understand transaction contention](https://docs.cockroachlabs.com/docs/continuum/aegis-example-workflows.md#understand-transaction-contention).

## Give it to your agent

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
This CockroachDB service gets SQLSTATE 40001 errors and slow writes on hot rows.
Find read-then-write transactions on the same rows. Rewrite each as a single
conditional statement (UPDATE ... WHERE <condition> RETURNING) where the rule fits
in SQL; otherwise add SELECT ... FOR UPDATE at the read and move any external
calls outside the transaction. Wrap explicit transactions in a retry loop on
40001 with backoff, and use an idempotency key so retries can't apply twice.
Reference: https://docs.cockroachlabs.com/docs/cookbook/transaction-contention
```

## Go deeper

* [Transaction retry error reference](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md)
* [Transactions](https://docs.cockroachlabs.com/docs/stable/transactions.md) and [`SELECT FOR UPDATE`](https://docs.cockroachlabs.com/docs/stable/select-for-update)
* [Performance best practices: transaction contention](https://docs.cockroachlabs.com/docs/stable/performance-best-practices-overview.md#transaction-contention)
* [Performance Tuning Recipes](https://docs.cockroachlabs.com/docs/stable/performance-recipes.md), where this recipe came from

> [card] [Practice transactions in Cockroach University](https://learn.cockroachlabs.com/?utm_source=docs\&utm_medium=recipe\&utm_content=transaction-contention)
>
> Free developer path with hands-on browser labs.
