# Postgres transaction isolation levels in practice: the bugs Read Committed lets through

Read Committed, Repeatable Read and Serializable in PostgreSQL, reproduced with two psql sessions: lost updates, write skew, phantoms and the 'could not serialize access' errors (SQLSTATE 40001). Includes the fix for each bug, a retry function, and how to set the isolation level behind a transaction-mode connection pool. Tested on Postgres 17.11.

**Most explanations of transaction isolation stop at a table of anomalies with "possible" and "not possible" in the cells. That table is correct, but it doesn't tell you what goes wrong in your app. This post does it the other way round. We open two `psql` sessions on PostgreSQL 17.11, the major version Relyt One runs, and make the bugs happen. Under the default Read Committed level, two checkouts each sell one unit and the stock count only goes down by one. Two doctors both go off call and nobody is left on call. Then we fix them: with a single atomic statement, a row lock, or a stricter isolation level with a retry loop. We also show the part people miss: Repeatable Read stops the first bug but not the second. At the end there is a retry function you can copy, and the right way to set an isolation level when you connect through a transaction-mode pooler. If you only need the definitions, our [glossary entry](/glossary/transaction-isolation) has them in one screen.**

## The short version

| Behavior                                | Read Committed (default)                          | Repeatable Read                  | Serializable                                          |
| --------------------------------------- | ------------------------------------------------- | -------------------------------- | ----------------------------------------------------- |
| Snapshot                                | New one for every statement                       | One for the whole transaction    | One for the whole transaction, plus conflict tracking |
| Same query twice in one transaction     | Can return different rows                         | Same result                      | Same result                                           |
| Lost update (read, compute, write back) | **Happens silently**                              | Second writer gets error `40001` | Second writer gets error `40001`                      |
| Write skew (check a rule, then write)   | **Happens silently**                              | **Happens silently**             | One transaction gets error `40001`                    |
| Phantom rows                            | Can appear                                        | Don't appear in Postgres         | Don't appear                                          |
| Your code must retry                    | Only deadlocks (`40P01`), which any level can hit | Yes, on `40001`                  | Yes, on `40001`                                       |

Postgres accepts all four standard level names, but `READ UNCOMMITTED` behaves exactly like `READ COMMITTED`. You can never read another transaction's uncommitted data in Postgres, at any level.

## A two-terminal lab

Everything below runs on a throwaway Postgres 17.11 in Docker. Start it once and open two terminals, which we'll call **A** and **B**:

```bash
docker run -d --name iso -e POSTGRES_PASSWORD=x postgres:17.11-alpine
docker exec -it iso psql -U postgres   # run this in terminal A and again in terminal B
```

Create the two tables the examples use. `stock` holds one product with five units; `on_call` holds two doctors who are both on call, and the rule is that at least one of them must stay on call.

```sql
SHOW default_transaction_isolation;
--  read committed

CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL CHECK (qty >= 0));
INSERT INTO stock VALUES ('A-1', 5);

CREATE TABLE on_call (doctor text PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO on_call VALUES ('alice', true), ('bob', true);
```

Each experiment below is a sequence of steps. Run them in the order shown, switching terminals as the step says, and reset the data between experiments with `UPDATE stock SET qty = 5; DELETE FROM on_call WHERE doctor = 'carol'; UPDATE on_call SET on_call = true;`.

## What Read Committed actually promises

Read Committed promises that every statement sees a snapshot of the data committed before **that statement** started. It does not promise that two statements in the same transaction see the same data. (`UPDATE`, `DELETE` and `SELECT … FOR UPDATE` have one twist, which we'll use below: if a row they target was changed by a concurrent transaction, they wait and then work on the newly committed version.)

| Step | Terminal A                                                  | Terminal B                                                  |
| ---- | ----------------------------------------------------------- | ----------------------------------------------------------- |
| 1    | `BEGIN;`  `SELECT qty FROM stock WHERE sku = 'A-1';` → `5`  |                                                             |
| 2    |                                                             | `UPDATE stock SET qty = 2 WHERE sku = 'A-1';` (autocommits) |
| 3    | `SELECT qty FROM stock WHERE sku = 'A-1';` → `2`  `COMMIT;` |                                                             |

The same query in the same transaction returned 5 and then 2. That is a **nonrepeatable read**. Run the same steps with `BEGIN ISOLATION LEVEL REPEATABLE READ;` in step 1 and the second `SELECT` returns 5 again: Repeatable Read takes one snapshot when the transaction runs its first statement and uses it until the end.

On its own, a nonrepeatable read is rarely a bug. It becomes one when your code reads a value, makes a decision in the application, and writes the result back. That's the next two experiments.

## Bug 1: the lost update

A checkout reads the stock, subtracts one in application code, and writes the new number back. Two checkouts run at the same time:

| Step | Terminal A                                                 | Terminal B                                                 |
| ---- | ---------------------------------------------------------- | ---------------------------------------------------------- |
| 1    | `BEGIN;`  `SELECT qty FROM stock WHERE sku = 'A-1';` → `5` |                                                            |
| 2    |                                                            | `BEGIN;`  `SELECT qty FROM stock WHERE sku = 'A-1';` → `5` |
| 3    | `UPDATE stock SET qty = 4 WHERE sku = 'A-1';`  `COMMIT;`   |                                                            |
| 4    |                                                            | `UPDATE stock SET qty = 4 WHERE sku = 'A-1';`  `COMMIT;`   |

```sql
SELECT * FROM stock;
--  sku | qty
-- -----+-----
--  A-1 |   4
```

Two units were sold and the count only went down by one. Both transactions committed, there was no error and nothing in the logs. Session B overwrote A's write with a value it computed from data that was already stale. This is the **lost update**, and Read Committed allows it because B's `UPDATE` is a new statement that simply writes the value it was given.

There are three ways to fix it. Pick the first one that fits.

### Fix 1: let the database do the arithmetic

If the new value can be computed in SQL, compute it in the `UPDATE`:

```sql
UPDATE stock SET qty = qty - 1 WHERE sku = 'A-1' AND qty > 0 RETURNING qty;
```

When two of these run at the same time, the second one waits for the first to commit. Then Postgres re-reads the row it was about to update, checks the `WHERE` clause again against the new version, and applies `qty - 1` to it. In our run, A's statement returned 4 and B's returned 3, and the final count was 3. The `qty > 0` condition means the statement updates zero rows instead of overselling when stock runs out. This needs no retry loop and works at the default isolation level. It's the best fix whenever it's possible.

### Fix 2: lock the row you are about to change

If the decision really has to happen in application code, read the row with `FOR UPDATE`:

| Step | Terminal A                                                            | Terminal B                                                              |
| ---- | --------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| 1    | `BEGIN;`  `SELECT qty FROM stock WHERE sku = 'A-1' FOR UPDATE;` → `5` |                                                                         |
| 2    |                                                                       | `BEGIN;`  `SELECT qty FROM stock WHERE sku = 'A-1' FOR UPDATE;` (waits) |
| 3    | `UPDATE stock SET qty = 4 WHERE sku = 'A-1';`  `COMMIT;`              |                                                                         |
| 4    |                                                                       | (returns `4`)  `UPDATE stock SET qty = 3 WHERE sku = 'A-1';`  `COMMIT;` |

B waits at step 2 until A commits, then sees A's result and writes 3. The cost is waiting: keep the time between `FOR UPDATE` and `COMMIT` short, and never call a slow external service while you hold the lock.

### Fix 3: raise the isolation level and retry

Run the original read-compute-write steps again, but start both transactions with `BEGIN ISOLATION LEVEL REPEATABLE READ;`. Step 4 now fails:

```text
ERROR:  could not serialize access due to concurrent update
```

B's snapshot was taken before A committed, so Postgres refuses to let B overwrite a row that changed after that snapshot. The error has SQLSTATE `40001` (`serialization_failure`). The transaction is now aborted: if you type `COMMIT`, Postgres answers `ROLLBACK`. The stock stays at A's value of 4, and B has to start over from `BEGIN`. When it does, it will read 4 and write 3. `SERIALIZABLE` gives the same error for this pattern.

The isolation level didn't make the conflict go away. It turned a silent wrong answer into an error, and your code has to retry. We'll write that retry function below.

## Bug 2: write skew, which Repeatable Read doesn't stop

Now a business rule that spans more than one row. Alice and Bob are both on call. The rule is "at least one doctor stays on call", and the app checks it before it lets a doctor leave:

| Step | Terminal A (Alice)                                                                            | Terminal B (Bob)                                                                              |
| ---- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| 1    | `BEGIN ISOLATION LEVEL REPEATABLE READ;`  `SELECT count(*) FROM on_call WHERE on_call;` → `2` |                                                                                               |
| 2    |                                                                                               | `BEGIN ISOLATION LEVEL REPEATABLE READ;`  `SELECT count(*) FROM on_call WHERE on_call;` → `2` |
| 3    | `UPDATE on_call SET on_call = false WHERE doctor = 'alice';`                                  |                                                                                               |
| 4    |                                                                                               | `UPDATE on_call SET on_call = false WHERE doctor = 'bob';`                                    |
| 5    | `COMMIT;`                                                                                     |                                                                                               |
| 6    |                                                                                               | `COMMIT;`                                                                                     |

```sql
SELECT * FROM on_call ORDER BY doctor;
--  doctor | on_call
-- --------+---------
--  alice  | f
--  bob    | f
```

Nobody is on call, and both transactions committed cleanly, under **Repeatable Read**. Each transaction checked the rule against its own snapshot, saw two doctors, and updated a different row. Because the two transactions never wrote the same row, there was no conflict for Repeatable Read to detect. This is **write skew**. The same steps give the same result under Read Committed.

![Two transactions read the same rule, each updates a different row, and only Serializable notices that the combined result is impossible in any serial order.](/blog/assets/bab5208b252fdd2c.svg)

The PostgreSQL documentation warns about exactly this: attempts to enforce business rules at Repeatable Read "are not likely to work correctly without careful use of explicit locks". You have two ways out.

### Fix 1: Serializable

Run the same six steps with `BEGIN ISOLATION LEVEL SERIALIZABLE;`. Steps 1 to 5 succeed, and Bob's `COMMIT` in step 6 fails:

```text
ERROR:  could not serialize access due to read/write dependencies among transactions
DETAIL:  Reason code: Canceled on identification as a pivot, during commit attempt.
HINT:  The transaction might succeed if retried.
```

Alice is off call, Bob is still on call, and Bob's retry reads a count of 1 and is refused. Serializable tracks what each transaction **read** as well as what it wrote. When two transactions each read something the other one then changed, the combined result could be one that no serial order would produce, so Postgres cancels one of them. It errs on the safe side: occasionally it cancels a transaction that would have been fine, which is one more reason the retry has to be automatic. It does this without blocking: nobody waited at any step, and the error arrived at commit time. The SQLSTATE is `40001` again, so the same retry function handles both bugs.

Serializable's guarantee covers transactions that run at Serializable. The documentation's advice is to use it "for all writes and for all reads which need a consistent view of the data". A Read Committed transaction that changes `on_call` from another code path isn't checked.

### Fix 2: lock every row the rule depends on

At Read Committed, lock the rows you count before you decide:

| Step | Terminal A (Alice)                                                                                | Terminal B (Bob)                                                                         |
| ---- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| 1    | `BEGIN;`  `SELECT doctor FROM on_call WHERE on_call ORDER BY doctor FOR UPDATE;` → `alice`, `bob` |                                                                                          |
| 2    |                                                                                                   | `BEGIN;`  `SELECT doctor FROM on_call WHERE on_call ORDER BY doctor FOR UPDATE;` (waits) |
| 3    | `UPDATE on_call SET on_call = false WHERE doctor = 'alice';`  `COMMIT;`                           |                                                                                          |
| 4    |                                                                                                   | (returns only `bob`, so the app refuses)  `ROLLBACK;`                                    |

When B's wait ends, Postgres checks the `WHERE on_call` condition against the newly committed version of Alice's row, finds that it no longer matches, and leaves her out. B sees one doctor and refuses. This works, but only because the rule's rows already exist. A lock can't cover a row that hasn't been inserted yet. For a rule like "no two bookings for the same room overlap", where the conflict is a new row, use Serializable, a constraint (an exclusion constraint does exactly this job for overlapping ranges), or lock something that does exist, such as the room's own row with `SELECT … FROM rooms WHERE id = … FOR UPDATE`.

## Phantoms: Postgres is stricter than the standard

The SQL standard allows **phantom reads** at Repeatable Read: you run the same query with a `WHERE` clause twice and new rows that match appear. Postgres doesn't allow them. Its Repeatable Read is snapshot isolation, so a query sees only rows committed before the transaction's first statement:

| Step | Terminal A                                                                      | Terminal B                                    |
| ---- | ------------------------------------------------------------------------------- | --------------------------------------------- |
| 1    | `BEGIN ISOLATION LEVEL REPEATABLE READ;`  `SELECT count(*) FROM on_call;` → `2` |                                               |
| 2    |                                                                                 | `INSERT INTO on_call VALUES ('carol', true);` |
| 3    | `SELECT count(*) FROM on_call;` → `2`  `COMMIT;`                                |                                               |

That's why the anomaly table in the [PostgreSQL documentation](https://www.postgresql.org/docs/17/transaction-iso.html) says "Allowed, but not in PG" for phantoms at Repeatable Read. If an article tells you that you need Serializable to avoid phantoms in Postgres, it's describing the standard, not Postgres. What you need Serializable for is write skew, including its insert form: two Repeatable Read transactions that each check that a booking slot is free and then insert a booking for it will both commit.

## Retrying 40001 the right way

Once you use Repeatable Read or Serializable, a `40001` error is a normal result, not an outage. The documentation is specific about how to handle it: retry the **complete** transaction, "including all logic that decides which SQL to issue and/or which values to use". Re-running only the failed statement would re-apply a decision made from stale data. That's also why Postgres doesn't retry for you.

Here is a small wrapper for Node.js with `node-postgres`. It retries `40001` and deadlocks (`40P01`, which the documentation says it "may also be advisable" to retry), backs off with a random delay so retries that collided once are unlikely to collide again, and gives up after five attempts:

```js
// npm install pg@8.16.3
import pg from "pg";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

const RETRYABLE = new Set(["40001", "40P01"]); // serialization_failure, deadlock_detected
const LEVELS = new Set(["READ COMMITTED", "REPEATABLE READ", "SERIALIZABLE"]);

export async function inTransaction(fn, { isolation = "SERIALIZABLE", maxAttempts = 5 } = {}) {
  if (!LEVELS.has(isolation)) throw new Error(`unknown isolation level: ${isolation}`);
  for (let attempt = 1; ; attempt++) {
    const client = await pool.connect();
    try {
      await client.query(`BEGIN ISOLATION LEVEL ${isolation}`);
      const result = await fn(client);
      await client.query("COMMIT");
      client.release();
      return result;
    } catch (err) {
      // If ROLLBACK fails, the connection is unusable: release(error) makes the pool discard it.
      const broken = await client.query("ROLLBACK").then(() => undefined, (e) => e);
      client.release(broken);
      if (!RETRYABLE.has(err.code) || attempt >= maxAttempts) throw err;
      const delay = Math.random() * 20 * 2 ** attempt; // random backoff: up to 40, 80, 160 ms…
      console.log(`attempt ${attempt} failed with ${err.code}, retrying in ${delay.toFixed(0)} ms`);
      await new Promise((r) => setTimeout(r, delay));
    }
  }
}

// Two doctors ask to go off call at the same time.
async function leaveShift(doctor) {
  return inTransaction(async (tx) => {
    const { rows } = await tx.query("SELECT count(*)::int AS n FROM on_call WHERE on_call");
    if (rows[0].n < 2) return `${doctor}: refused, last doctor on call`;
    await tx.query("SELECT pg_sleep(0.5)"); // widen the race window for the demo
    await tx.query("UPDATE on_call SET on_call = false WHERE doctor = $1", [doctor]);
    return `${doctor}: off call`;
  });
}

console.log(await Promise.all([leaveShift("alice"), leaveShift("bob")]));
const { rows } = await pool.query("SELECT doctor, on_call FROM on_call ORDER BY doctor");
console.table(rows);
await pool.end();
```

Run it with both doctors on call and `DATABASE_URL` pointing at the lab database. One of the two calls fails once, retries, sees that it would be the last doctor and is refused. Which doctor wins varies from run to run. In each of our three runs exactly one call retried once, and the output looked like this:

```text
attempt 1 failed with 40001, retrying in 8 ms
[ 'alice: off call', 'bob: refused, last doctor on call' ]
```

Three rules for the function you pass in:

- **Everything that decides what to write goes inside it.** If you read the count outside the callback and pass it in, the retry reuses a stale number and the bug is back.
- **No side effects you can't undo.** Don't send email or call a payment API inside the callback; it may run more than once. Write an outbox row instead and send after the commit.
- **Don't retry other errors blindly.** The documentation says a unique violation (`23505`) or an exclusion constraint violation (`23P01`) is sometimes a disguised serialization failure, for example when the app picks a new key after reading the existing ones. It can also be a permanent error, so only retry it where you know which case you're in.

## Setting the isolation level behind a connection pool

Relyt One gives every compute a direct connection string and a pooled one. The pooled one goes through PgBouncer in transaction mode, which hands your transaction whichever server connection is free and resets nothing between clients ([what else that breaks](/blog/pgbouncer-transaction-pooling)). That changes how you should set the isolation level. We tested the three usual ways with a local Postgres 17.11 behind PgBouncer 1.26.1 in transaction mode, with the pool limited to one server connection so the results are deterministic:

| How you set it                                                                                                     | What happened behind the pooler                                                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE` (or `SET default_transaction_isolation`) | The setting stayed on the server connection. The **next client** ran `SHOW transaction_isolation` and got `serializable`.                                                                               |
| `BEGIN ISOLATION LEVEL REPEATABLE READ`                                                                            | Applied to that transaction only. The next client got `read committed`.                                                                                                                                 |
| `ALTER ROLE app SET default_transaction_isolation = 'repeatable read'`                                             | The next client still got `read committed`: the pooler reused a server connection that had logged in before the change. After the pooler opened a new server connection, clients got `repeatable read`. |

So:

- **Put the level on the transaction.** `BEGIN ISOLATION LEVEL …` (or `SET TRANSACTION ISOLATION LEVEL …` as the first statement after `BEGIN`) is the only form that behaves the same on the direct and the pooled connection. The `inTransaction` function above does this.
- **Never use session-level `SET` for it on a pooled connection.** It leaks to other clients, and your own next transaction may not get it.
- **Role and database defaults work, but only for new server connections.** `ALTER ROLE` reaches a server connection only when it logs in, so connections already in the pool keep the old default until they're replaced. Ordinary roles can change their own defaults; `ALTER DATABASE … SET` needs the database owner (or a superuser).

## Which level should you use?

| Situation                                                                      | Use                                                                            |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| Single-row changes you can express in SQL (`qty = qty - 1`, upserts, counters) | Read Committed and one atomic statement                                        |
| Read, decide in code, write back one row you know in advance                   | Read Committed and `SELECT … FOR UPDATE`                                       |
| A rule across several rows, or rows that may not exist yet                     | Serializable and a retry wrapper, or a constraint if one can express the rule  |
| A report or export that must see one consistent moment                         | `BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE` (or Repeatable Read) |
| Everything else                                                                | The default, Read Committed                                                    |

Read Committed isn't wrong. It's a sensible default because most statements are single, self-contained writes. It goes wrong in one specific shape of code: **read, decide outside the database, write**. When you see that shape, pick one of the fixes above on purpose.

If you move a busy write path to Serializable, the documentation's performance advice is worth reading in full. The points that matter most:

- Declare read-only transactions `READ ONLY`. For long reports, `SERIALIZABLE READ ONLY DEFERRABLE` waits until it can take a safe snapshot, then runs without serialization overhead and can't be cancelled by a serialization failure.
- Keep transactions short, and don't leave sessions "idle in transaction". Set `idle_in_transaction_session_timeout` to catch the ones that do.
- Make the queries inside use indexes. A sequential scan takes a predicate lock on the whole table, which makes serialization failures more likely.
- Once every writer on a code path runs at Serializable, remove the `FOR UPDATE` locks it no longer needs.

## Try it on a branch

All of this is plain PostgreSQL 17 with no extensions, so the same steps work on Relyt One. Isolation bugs only show up under concurrency, which makes them awkward to test against a shared database. Create a branch of your production data, point two terminals or a load test at it, and try your real checkout or booking code at each isolation level. When you're done, delete the branch.

Every output in this post comes from scripted replays of these steps on PostgreSQL 17.11 (the scripts use psql variables and `pg_sleep` to force the step order), and the results were the same on every run. To check a definition quickly, the glossary has [isolation levels](/glossary/transaction-isolation), [MVCC](/glossary/mvcc) and [deadlocks](/glossary/deadlock).

[Start for free](/auth/signin?ref=blog-postgres-transaction-isolation-levels)
