Sub topic 14
Retrying after deadlocks and serialization failures
This chapter assumes you know BEGIN, COMMIT and ROLLBACK, the four isolation levels, row locks with SELECT ... FOR UPDATE, and how a deadlock arises. Examples use PostgreSQL and Python with the psycopg driver (version 3). The ideas carry over to other databases and drivers, but error codes differ.
Why some failures are meant to be retried
Some transaction failures say nothing about your SQL being wrong. The database aborts a transaction to protect correctness, and the same transaction would probably succeed if you ran it again. Two cases matter most:
- Deadlock. Two transactions each hold a lock the other needs. The database detects the cycle and aborts one of them (the victim). PostgreSQL reports SQLSTATE
40P01(deadlock_detected). - Serialization failure. Under REPEATABLE READ or SERIALIZABLE, the database finds that committing your transaction would produce a result no serial ordering could explain, or that your snapshot is stale for a row you tried to change. PostgreSQL reports SQLSTATE
40001(serialization_failure).
Both belong to SQLSTATE class 40, "transaction rollback". The database has already rolled the transaction back, and no partial work remains. Your job is to run the whole transaction again from BEGIN.
Which errors are retryable
Retry only errors that are transient. Retrying a permanent error wastes time and hides a bug.
| SQLSTATE | Name | Retry? | Notes |
|---|---|---|---|
| `40001` | serialization_failure | Yes | Also raised under REPEATABLE READ when you update a row changed after your snapshot began. |
| `40P01` | deadlock_detected | Yes | PostgreSQL specific code. MySQL uses error 1213 with SQLSTATE `40001`. |
| `55P03` | lock_not_available | Sometimes | Raised by `NOWAIT` or `lock_timeout`. Retry only if waiting is acceptable. |
| `23505` | unique_violation | Usually no | Retry only for deliberate patterns such as insert-if-absent races. |
| `23514` | check_violation | No | The data breaks a rule, and a retry fails again. |
| `42601` | syntax_error | No | A bug in the code. |
Match on the SQLSTATE code, not on the message text. Messages vary by version and language setting.
A retry wrapper
The wrapper below runs a function that contains the whole transaction. It retries on the two retryable codes, waits with exponential backoff plus random jitter, and gives up after a limit.
import random
import time
import psycopg
from psycopg import errors
RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected)
def run_transaction(conninfo, work, max_attempts=5, base_delay=0.05):
"""Run work(conn) in a transaction, retrying on transient conflicts."""
for attempt in range(1, max_attempts + 1):
try:
with psycopg.connect(conninfo) as conn:
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
with conn.transaction():
return work(conn)
except RETRYABLE:
if attempt == max_attempts:
raise
delay = base_delay * (2 ** (attempt - 1))
time.sleep(random.uniform(0, delay))
def transfer(conn, src, dst, amount):
conn.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, src),
)
conn.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, dst),
)
if __name__ == "__main__":
run_transaction(
"dbname=bank",
lambda conn: transfer(conn, 1, 2, 30),
)Several details in this code matter.
- The retry wraps the whole transaction. Retrying a single statement inside an aborted transaction fails, because PostgreSQL rejects all further commands until rollback. The
with conn.transaction()block rolls back when an exception leaves it, so each attempt starts clean. - A new attempt re-reads everything. The function
workmust fetch its inputs again inside the transaction. Values read in the failed attempt may be stale. The failed attempt's snapshot is gone. - Jitter prevents lockstep retries. If two transactions collide and both wait exactly 50 ms, they collide again.
random.uniform(0, delay)spreads them out. - The attempt limit bounds the damage. Without a cap, a persistent conflict can loop forever and add load to an already busy database.
The error can also appear at COMMIT. Under SERIALIZABLE, PostgreSQL may let every statement succeed and then fail the commit. That is why the with block, which includes the commit, sits inside the try. Code that catches errors only around individual statements misses this case.
Make the transaction safe to run twice
A retry runs the transaction body again, so the body must not have effects outside the database that survive a rollback. Look for these hazards:
- External side effects. Sending an email, calling a payment API or publishing a message inside the transaction can happen several times if the transaction is retried. Do these after a successful commit, or record the intent in a table (an outbox) and send it from a separate process.
- Application state. A counter, a list or a generated ID kept in Python variables is not rolled back. Create such values inside the function, so each attempt starts fresh.
- Non-idempotent inputs. If the caller generates a request ID once and passes it in, the retried transaction reuses it, which is usually what you want. A unique constraint on that ID turns a duplicate submission into a clean
23505error instead of a double charge.
A failure at COMMIT has one more trap. If the connection drops while the commit is in flight, you cannot tell whether the commit happened. That is not a 40001 error, and blind retry risks applying the change twice. Protect against it with an idempotency key stored in the same transaction, then check for the key before retrying.
Reducing how often conflicts occur
Retries handle conflicts, but fewer conflicts cost less. These habits help:
- Lock rows in a consistent order. If every transfer updates the lower account ID first, two transfers cannot form a cycle. This prevents most deadlocks outright.
- Keep transactions short. A transaction that holds locks or a snapshot for seconds invites conflicts. Do slow work, such as network calls and user input, outside it.
- Take the strongest lock first. If you read a row and later update it, use
SELECT ... FOR UPDATEat the read. This avoids a lock upgrade in the middle of the transaction, which is a common deadlock source. - Touch fewer rows. Narrow
WHEREclauses and good indexes reduce the rows and predicates that SERIALIZABLE must track. A full table scan can cause false-positive serialization failures.
-- Deadlock-prone: opposite order in two sessions
-- Session A: UPDATE accounts ... WHERE id = 1; then id = 2
-- Session B: UPDATE accounts ... WHERE id = 2; then id = 1
-- Safer: both sessions lock in ascending id order up front
BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;ORDER BY id together with FOR UPDATE makes the locks arrive in the same sequence in every session. Because ORDER BY alone does not guarantee the lock order in every plan shape, keep such queries simple.
Common mistakes
- Retrying inside the transaction. After an error, the transaction is aborted. Roll back first, or use a savepoint, then start over.
- Retrying everything. A
23514check violation or a syntax error will fail every time. Catch only the retryable codes. - No limit and no backoff. Tight loops turn a short conflict into a load spike.
- Reusing stale values. Computing a value before the transaction and using it in the retry bypasses the protection that SERIALIZABLE gives.
- Assuming READ COMMITTED never needs retries. It rarely raises
40001, but deadlocks still occur at every isolation level. - Hiding the final failure. After the last attempt, raise the error so callers and monitoring see it. Also log each retry with its SQLSTATE, since a rising retry rate is an early sign of contention.
Exercises
Exercise
Your Python code runs BEGIN, then executes three statements. The second one fails with SQLSTATE 40001. A teammate proposes catching the error and re-running only the second statement. Why does this not work, and what should the code do instead?
Show answer
The database has already aborted the transaction, so the first statement's changes are rolled back and PostgreSQL rejects further commands until the rollback completes. Re-running only the second statement would either fail or run outside the original transaction. The code must roll back and run the whole transaction again from BEGIN, re-reading any data it depends on, with a limited number of attempts and a random backoff delay between them.
Exercise
A transaction sends a confirmation email and then updates an order row. Under SERIALIZABLE it sometimes fails with 40001 and is retried, and customers receive duplicate emails. How do you fix it?
Show answer
Move the email out of the retried transaction. Either send it after the commit returns successfully, or insert a row into an outbox table inside the transaction and let a separate process send the email after the commit. The outbox row is rolled back with the transaction, so only the committed attempt produces an email.
Exercise
Two sessions run transfers between accounts 1 and 2 in opposite directions and occasionally hit 40P01. Name a change that removes most of these deadlocks without retries.
Show answer
Make every transaction lock the rows in the same order, for example by always updating the lower account ID first, or by running SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE at the start. With one global lock order, two transactions cannot each hold a lock the other wants. Keep the retry wrapper anyway for the cases that remain.