Sphere
Log in Join

Postgres 'could not serialize access due to concurrent update' in REPEATABLE READ

We turned up transaction isolation to fix one bug and got a new one. Raising the default to REPEATABLE READ stopped a read-modify-write race in our invoicing job, and immediately gave us about 40 errors a night:

ERROR:  could not serialize access due to concurrent update
CONTEXT: SQL statement "UPDATE invoices SET status = $1 WHERE id = $2"
PL/pgSQL function close_invoice(integer) line 12 at SQL statement

It only happened when two workers touched the same invoice at nearly the same time, which is exactly what REPEATABLE READ is supposed to catch. I just didn't expect to see it on an UPDATE.

## Why an UPDATE fails under REPEATABLE READ

In REPEATABLE READ, a transaction sees a snapshot fixed at the first non-transaction statement. If another committed transaction updates a row after your snapshot was taken, your transaction can't update that same row — letting it through would mean writing a change based on stale data. Postgres throws the serialization error instead.

This is different from SERIALIZABLE, which adds predicate-level conflict detection and can fail on reads too. For plain row-level conflicts, REPEATABLE READ is enough and cheaper.

Reproduce it in two psql sessions:

sql
-- session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- 100

-- session B
BEGIN;
UPDATE accounts SET balance = 80 WHERE id = 1;
COMMIT;

-- back in session A
UPDATE accounts SET balance = 90 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update

Session A can keep reading the old value of 100 all it wants; it just can't write over B's change.

## Retrying is the intended response

There's no lock you can take at the start that makes this go away cleanly, and SELECT ... FOR UPDATE before the snapshot won't help because the snapshot is already set. The documented answer is to retry the whole transaction from the beginning. In Python with psycopg2:

python
import psycopg2

def with_retry(conn, fn, attempts=5):
for n in range(attempts):
try:
with conn:
with conn.cursor() as cur:
return fn(cur)
except psycopg2.errors.SerializationFailure:
if n == attempts - 1:
raise
continue

psycopg2.errors.SerializationFailure maps to SQLSTATE 40001, which covers both the could not serialize access due to concurrent update case and the SERIALIZABLE variant. If you're catching by string, catch 40001 instead.

## The part that surprised me

Our first retry loop retried only the failing UPDATE, not the transaction. That's wrong — the snapshot is still the old one, so it fails again every time until you hit the attempt limit. Retry has to start a new transaction so it gets a fresh snapshot.

We also added a tiny jittered backoff. Five immediate retries in a tight loop just make two workers take turns failing:

python
import random, time
time.sleep(random.uniform(0.01, 0.05) (2 * n))

## When not to bother

If your conflicts are rare and the operation is idempotent, sometimes a plain UPDATE ... WHERE status = 'open' with a check on cur.rowcount is simpler than any of this. We kept that for the two call sites where a no-op was acceptable, and used the retry wrapper for the rest.

Turns out the error was telling us the truth: two jobs genuinely wanted the same row. I still don't love how much code that takes to handle, but it beats silently clobbering an invoice.