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

# Transaction patterns: SERIALIZABLE, READ COMMITTED and retries

> One small rule, kept four ways, in four languages, on CockroachDB.

> [!NOTE]
>
> **Recipe** · **Works on:** Cockroach Continuum, CockroachDB Cloud, self-hosted · **Tested:** weekly in CI against the latest CockroachDB · **Stack:** Python, TypeScript, Go, Java · **Code:** [`recipes/transaction-patterns`](https://github.com/cockroachlabs/cockroach-cookbook/tree/recipes/transaction-patterns/v1.0.0/recipes/transaction-patterns) v1.0.0

One small rule, kept four ways, in four languages, on CockroachDB. A hospital needs at least one doctor
on call every day. Two doctors on call for the same day each ask for that day off at the same moment. Each
request reads the schedule, sees another doctor on call, and takes its own doctor off. Whether the hospital
ends the day with nobody on call depends on the isolation level and on how the code reads. It goes with the
Cockroach University course **Transactions on CockroachDB: SERIALIZABLE, READ COMMITTED and Retries**.

Each language runs the same race: Betty reads the schedule, Abe's whole request runs and commits, then Betty
decides and writes. The demo prints the outcome, and the tests check it. Results, the same in Python,
TypeScript, Go and Java, on CockroachDB v26.1:

| Setup | Abe | Betty | Doctors on call |
| - | - | - | - |
| `READ COMMITTED`, plain read | granted | granted | **0**: the rule is broken (write skew) |
| `SERIALIZABLE`, no retry | granted | SQLSTATE `40001` | 1 |
| `SERIALIZABLE`, with the retry loop | granted | declined on attempt 2 | 1 |
| `READ COMMITTED`, `SELECT ... FOR UPDATE` | waits for Betty, then declined | granted | 1 |

Retry errors come with `SERIALIZABLE` isolation itself: to guarantee a serial order, a database has to refuse
some transactions, and the client runs them again
([Transaction retry error reference](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md)).
CockroachDB runs every transaction at `SERIALIZABLE` unless told otherwise, while PostgreSQL's default is
`READ COMMITTED`, so code that never saw a retry error elsewhere can meet one here.

## The code

| Language | Driver | Retry loop and request | Tests |
| - | - | - | - |
| Python 3.11+ | psycopg 3 | [`python/oncall.py`](https://github.com/cockroachlabs/cockroach-cookbook/blob/recipes/transaction-patterns/v1.0.0/recipes/transaction-patterns/python/oncall.py) | pytest |
| TypeScript, Node.js 22.18+ | node-postgres (`pg`) | [`typescript/src/oncall.ts`](https://github.com/cockroachlabs/cockroach-cookbook/blob/recipes/transaction-patterns/v1.0.0/recipes/transaction-patterns/typescript/src/oncall.ts) | `node --test` |
| Go 1.25+ | pgx v5 | [`go/oncall.go`](https://github.com/cockroachlabs/cockroach-cookbook/blob/recipes/transaction-patterns/v1.0.0/recipes/transaction-patterns/go/oncall.go) | `go test` |
| Java 17+ | the standard JDBC driver (`org.postgresql`) | [`java/src/main/java/.../OnCall.java`](https://github.com/cockroachlabs/cockroach-cookbook/blob/recipes/transaction-patterns/v1.0.0/recipes/transaction-patterns/java/src/main/java/com/cockroachlabs/cookbook/oncall/OnCall.java) | JUnit, Maven |

Every language has the same two functions:

* **The retry loop** (`run_transaction`, `runTransaction`, `RunTransaction`): begins a transaction at the
  isolation level you pass, runs your function, commits, and on SQLSTATE `40001` rolls back and runs the
  whole function again after an exponential backoff with jitter, up to a retry limit. It retries nothing
  else, including `40003` ("result is ambiguous"), which is only safe to retry for an idempotent transaction.
* **The request** (`request_leave` and friends): reads the day's schedule, optionally with `FOR UPDATE`, and
  takes the doctor off call only if another doctor stays on. It has a hook between the read and the write
  that the demo and tests use to start the other doctor's request at exactly that moment.

`schema.sql` holds the two tables from the CockroachDB docs' isolation examples. Each test uses its own random
day, so the suites can share a database.

## Official retry helpers, and why this project writes its own

The CockroachDB docs recommend a library's own retry helper where one exists. This project uses one small
loop in every language instead, so that all four behave the same and you can read exactly what a retry does:

* **Go:** `crdbpgx.ExecuteTx` from [`cockroach-go`](https://github.com/cockroachdb/cockroach-go) retries
  inside the transaction from `SAVEPOINT cockroach_restart`, and a Go test uses it to keep the rule. In
  v2.4.3, one thing to know: with a backoff policy (`ExpBackoffRetryPolicy`) it restarts with a plain
  `BEGIN`, so the retry runs at the session's default isolation level, not the one in `TxOptions`.
* **Python:** `run_transaction` from [`sqlalchemy-cockroachdb`](https://github.com/cockroachdb/sqlalchemy-cockroachdb)
  works with the CockroachDB SQLAlchemy dialect. The [payments ledger project](https://github.com/cockroachlabs/cockroach-cookbook/tree/recipes/transaction-patterns/v1.0.0/blueprints/payments-ledger-fastapi) uses it.
* **Java and Node.js:** there's no Cockroach Labs helper; the docs' JDBC and node-postgres examples write a
  loop like this one.

## Get the code

The code is in the [Cockroach Cookbook](https://github.com/cockroachlabs/cockroach-cookbook) repository. To fetch only this project at the version this page describes:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
git clone --filter=blob:none --sparse https://github.com/cockroachlabs/cockroach-cookbook.git
cd cockroach-cookbook
git sparse-checkout set recipes/transaction-patterns
git checkout recipes/transaction-patterns/v1.0.0
cd recipes/transaction-patterns
```

## Run it locally

You need the [`cockroach` binary](https://docs.cockroachlabs.com/docs/stable/install-cockroachdb), v26.1 or
later, and the toolchain for the language you want.

```sh theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
sh scripts/local-db.sh     # starts an insecure local node and creates the txn_patterns database
export DATABASE_URL='postgresql://root@localhost:26257/txn_patterns?sslmode=disable'
```

Then, in the language's directory:

| Language | Install | Demo | Tests |
| - | - | - | - |
| Python | `python3 -m venv .venv && .venv/bin/pip install -r requirements.txt` | `.venv/bin/python demo.py` | `.venv/bin/pytest` |
| TypeScript | `npm ci` | `npm run demo` | `npm run typecheck && npm test` |
| Go | (none) | `go run ./cmd/demo` | `go test ./...` |
| Java | (none) | `mvn -q compile exec:java` | `mvn test` |

Each suite has 8 tests, including one that uses the `inject_retry_errors_enabled` session variable to check the
retry limit; Go's also runs the race through `crdbpgx.ExecuteTx`.

## Run it on CockroachDB Basic

> [!NOTE]
>
> These steps use a CockroachDB Basic cluster, which existing CockroachDB Cloud organizations can create. New organizations are on Cockroach Continuum: create a cluster with the [Continuum quickstart](https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart.md) and use its connection string in the same steps. Continuum pricing differs from the Basic prices on this page; see [Continuum pricing](https://docs.cockroachlabs.com/docs/continuum/pricing.md).

1. [Create a Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/create-a-basic-cluster.md) and a SQL
   user, then run `CREATE DATABASE txn_patterns;` in a SQL shell on it.
2. Set `DATABASE_URL` to that user's [connection string](https://docs.cockroachlabs.com/docs/cockroachcloud/connect-to-your-cluster.md)
   with `/txn_patterns` as the database and `sslmode=verify-full`, then run the demo and tests as above.

`READ COMMITTED` needs the `sql.txn.read_committed_isolation.enabled` cluster setting, which is `true` by
default; when it's `false`, `READ COMMITTED` transactions run as `SERIALIZABLE`.

## What it costs

CockroachDB Basic charges for Request Units (RUs) and storage, and scales to zero when idle: $0.20 per million
RUs and $0.50 per GiB-month, with a \$15 monthly allowance for pay-as-you-go organizations
([Plan a CockroachDB Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/plan-your-cluster-basic.md), October 2026).
A demo run is a few dozen short statements, and a test run a few hundred.

## Choosing an isolation level

* Start at `SERIALIZABLE`, CockroachDB's default, with the retry loop: it keeps rules like this one without any
  locking code, from the first deploy on a laptop node or a Basic cluster to a multi-region cluster.
* If your app was built for `READ COMMITTED` and you can't add retries, `READ COMMITTED` on CockroachDB is
  the documented choice, but then every read a decision depends on needs `FOR UPDATE` or `FOR SHARE`.

## License

The code is Apache-2.0 licensed.
