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.
| id | owner | balance |
|---|---|---|
| 1 | alice | 100.00 |
| 2 | bob | 100.00 |
T1 deposits 10.00 at repeatable read: it reads 100.00.
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:
- ERROR: could not serialize access due to concurrent update
- SQLSTATE 40001
- ERROR: could not serialize access due to read/write dependencies among transactions
- SQLSTATE 40001
- ERROR: deadlock detected
- SQLSTATE 40P01
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.
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"))interface Work<T> { T run(Connection c) throws SQLException; }
static <T> T inTransaction(Connection c, Work<T> work) throws SQLException, InterruptedException {
c.setAutoCommit(false);
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
for (int attempt = 1; ; attempt++) {
try {
T result = work.run(c); // every read and every write
c.commit(); // COMMIT can fail with 40001 too
return result;
} catch (SQLException e) {
c.rollback();
String state = e.getSQLState();
boolean retry = "40001".equals(state) || "40P01".equals(state);
if (!retry || attempt == 5) throw e;
long ceil = Math.min(2_000, 50L << attempt);
Thread.sleep(ThreadLocalRandom.current().nextLong(ceil));
}
}
}func inTx(ctx context.Context, pool *pgxpool.Pool, work func(pgx.Tx) error) error {
opts := pgx.TxOptions{IsoLevel: pgx.Serializable}
for attempt := 1; ; attempt++ {
// BeginTxFunc: BEGIN, work, COMMIT, or ROLLBACK if anything failed
err := pgx.BeginTxFunc(ctx, pool, opts, work)
var pgErr *pgconn.PgError
retry := errors.As(err, &pgErr) && (pgErr.Code == "40001" || pgErr.Code == "40P01")
if !retry || attempt == 5 {
return err
}
ceil := min(2*time.Second, 50*time.Millisecond<<attempt)
time.Sleep(time.Duration(rand.Int64N(int64(ceil))))
}
}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:
every client waits exactly 100, then 200, then 400 ms. all four arrive together each time, and fight over the same rows again.
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.