skip to content

retrying serialization failures

SQLSTATE 40001 is not a bug, it's a request. the retry loop your app needs, and where it goes.

address
everything.transactions.retry_loops
part
part 11, transactions and isolation
chapter
chapter 9 of 11
reading time
8 min

SQLSTATE 40001 (serialization_failure) and 40P01 (deadlock_detected) don't mean your code is wrong. they mean "this transaction didn't happen; run it again". the retry loop goes around the whole transaction, from BEGIN to COMMIT, including the reads that decided what to write. it caps the attempts, waits a random, growing time between them (jitter), and keeps every side effect (emails, payments, HTTP calls) outside.

the picture

you know the error that shows up in the logs once a week under load, and goes away when you try again by hand? if it's a 40001, that's the design working. REPEATABLE READ and SERIALIZABLE stay correct by failing a transaction when concurrent work would have made it wrong, and they count on you to run it again.

think of a shop till that refuses your card because the price changed while you were in the queue. you don't argue with the till, and you don't re-swipe the same receipt. you go back to the shelf, check the new price, decide again, and queue again.

the transaction =
T1
snapshot 759:759:
T2
·
1
BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 1→ 100.00
committed in the database
idownerbalance
1alice100.00
2bob100.00

T1 deposits 10.00 at repeatable read: it reads 100.00.

step 1/12
real output, a postgres 18.6 server · retry-deposit
two captured retries. in each, T2's first attempt ends in 40001, it rolls back, and attempt 2 starts from BEGIN with a fresh snapshot. the deposit re-reads 110.00 and writes 130.00. the on-call retry re-checks the rule, sees only ben, and decides differently.

the second run is the one to remember. a retry is not a replay. the first attempt decided "2 on call, ben can go". that decision was based on data that's no longer true, which is why postgres refused it. the retry runs the check again, and the check now says no.

the errors to catch

these are the ones the postgres manual says to retry, as this book's captures got them:

what the client receives
  1. ERROR: could not serialize access due to concurrent update
  2. SQLSTATE 40001
  3. ERROR: could not serialize access due to read/write dependencies among transactions
  4. SQLSTATE 40001
  5. ERROR: deadlock detected
  6. SQLSTATE 40P01
three captured errors: a write conflict at repeatable read, a read/write cycle at serializable, a deadlock. different messages, two codes. catch the code, never the message.

match on the SQLSTATE: messages vary with the situation (the manual says the 40001 text will vary; it always has the code). the manual also mentions that a unique violation (23505) can be a serialization failure in disguise, say when two transactions pick the same "next free" key. retry that one only when you know that's what it is: a 23505 from a real duplicate will fail every time.

the loop

the shape, in three languages. the same five rules in each: the whole transaction inside, COMMIT inside (it can fail with 40001 too), only the two codes retried, a cap on attempts, and a random wait that grows.

python
import random, time
import psycopg
from psycopg import errors
 
RETRY = (errors.SerializationFailure, errors.DeadlockDetected)  # 40001, 40P01
 
def in_transaction(conn, work, attempts=5, base=0.05, cap=2.0):
    for attempt in range(1, attempts + 1):
        try:
            with conn.transaction():      # BEGIN ... COMMIT, or ROLLBACK on error
                return work(conn)         # every read and every write, in here
        except RETRY:
            if attempt == attempts:
                raise
            time.sleep(random.uniform(0, min(cap, base * 2 ** attempt)))
 
# conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
# total = in_transaction(conn, lambda c: go_off_call(c, "ben"))
predict the output
a loop that catches 40001 and re-runs only the failing UPDATE, without a ROLLBACK first. what does the retried UPDATE get?
python
cur.execute("BEGIN ISOLATION LEVEL REPEATABLE READ")
balance = cur.execute("SELECT balance FROM accounts WHERE id = 1").fetchone()[0]
for attempt in range(5):
    try:
        cur.execute("UPDATE accounts SET balance = %s WHERE id = 1", (balance + 20,))
        break
    except errors.SerializationFailure:
        continue   # ?

where the loop goes

around the unit of work, in your application's data layer, where the code that decides what to write lives. not around a single statement (the Predict above), not inside a database transaction (postgres can't restart a transaction from the inside), and not in the database: postgres has no automatic retry, because only your code knows how to recompute the decision. the manual says as much.

and keep side effects out of it. the work function may run five times; anything it does outside the database happens five times too:

  • emails, push notifications, webhooks: send them after the loop returns, or write them to an outbox table inside the transaction and let a worker send them (the outbox row commits or vanishes with the rest).
  • charging a card, calling another service: same. or give the call an idempotency key, so the second attempt is recognised as a repeat.
  • in-memory state: counters, caches, objects you mutate. build the result inside the function and return it; don't change anything shared until it's committed.

backoff and jitter

two transactions that collided once will collide again if they retry at the same instant. so wait before retrying, wait longer each time, and make the wait random:

jitter =
random =

every client waits exactly 100, then 200, then 400 ms. all four arrive together each time, and fight over the same rows again.

within 25 ms of another retryalonethe backoff ceiling
model: 4 clients that failed at the same moment, backoff 100 ms doubling, not postgres output
a model: four clients fail together at t = 0 and retry. with jitter none, all four wait the same time and arrive together again, every round. switch to full and roll a few times: they spread out.

cap the attempts (five is plenty for most apps) and let the last failure surface. if retries are routine, something is too contended: a hot row every request touches, or transactions held open too long. the cure is in the data model, not in a bigger retry count.

keylines

  • 40001 and 40P01 mean "nothing happened, try again". catch the code, not the message.
  • retry the whole transaction, reads included. a retry decides again, it doesn't replay.
  • COMMIT goes inside the loop: it can fail with 40001.
  • cap the attempts, back off, add jitter.
  • the body may run several times. side effects go after the commit, or into an outbox.