Sub topic 13
Handling serialization failures and deadlocks
This chapter assumes you know basic SQL, how BEGIN, COMMIT and ROLLBACK work, and the anomalies from earlier chapters: lost update, write skew, and the difference between locking and MVCC. It covers what happens when the database refuses to let a transaction finish, and how your application should respond.
Why the database aborts transactions
Stronger isolation levels protect you in one of two ways. The database can make a transaction wait, or it can abort it. Both mechanisms have failure cases that your application code must handle.
- A serialization failure means the database detected that committing your transaction would produce a result no serial ordering of the transactions could produce. It aborts one transaction to keep the data correct.
- A deadlock means two or more transactions each hold a lock that another one needs. None of them can proceed, so the database picks a victim and aborts it.
- A lock timeout means a transaction waited too long for a lock and gave up. No cycle is required.
In all three cases the database has rolled back your transaction, or is about to. Nothing the transaction did is saved. The error is a normal outcome of running concurrent work, not a bug in your SQL.
Error codes by engine
Your code needs to recognise these errors reliably. Match on the error code, not on the message text.
| Situation | PostgreSQL | MySQL (InnoDB) | SQL Server |
|---|---|---|---|
| Serialization failure | SQLSTATE `40001` | SQLSTATE `40001` (error 1213 is reported for deadlocks) | Error 3960 (snapshot update conflict) |
| Deadlock | SQLSTATE `40P01` | Error 1213, SQLSTATE `40001` | Error 1205 |
| Lock wait timeout | `55P03` (lock not available, with `lock_timeout` or `NOWAIT`) | Error 1205, SQLSTATE `HY000` | Error 1222 |
The SQL standard reserves the SQLSTATE class 40 for "transaction rollback". PostgreSQL uses 40001 for serialization failures and 40P01 for deadlocks. In practice, treat both as retryable.
MySQL has a trap: error number 1205 is a lock wait timeout, but SQL Server uses 1205 for deadlocks. The numbers are per engine, so keep one mapping per driver.
Retry the whole transaction
The rule for handling these errors is simple: roll back, then run the entire transaction again from the first statement. Do not retry only the failed statement.
The reason is that the transaction's earlier reads may no longer be valid. In the write skew example from the previous chapters, the transaction read a count of on-duty doctors and then decided to update a row. If it is aborted and you resume at the UPDATE, you are using a decision based on stale data. A full retry re-reads the data and re-evaluates the decision.
This has a consequence for how you structure code. The transaction body must be a function you can call again. It must not carry state from a previous attempt, and it must not perform side effects that cannot be undone, such as sending an email or calling a payment API, until after the commit succeeds.
A retry loop in Python
The following example uses psycopg 3 with PostgreSQL. It retries on serialization failures and deadlocks, uses exponential backoff with jitter, and gives up after a fixed number of attempts.
import random
import time
import psycopg
from psycopg import errors
RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected)
def run_in_transaction(conninfo, work, max_attempts=5):
"""Run work(cursor) in a SERIALIZABLE transaction, retrying on 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():
with conn.cursor() as cur:
return work(cur)
except RETRYABLE:
if attempt == max_attempts:
raise
# Exponential backoff with jitter: 20 ms, 40 ms, 80 ms, ... plus noise
delay = 0.02 * (2 ** (attempt - 1))
time.sleep(delay + random.uniform(0, delay))
def go_off_duty(cur, doctor):
cur.execute("SELECT count(*) FROM on_call WHERE on_duty")
on_duty = cur.fetchone()[0]
if on_duty < 2:
raise ValueError("at least one doctor must stay on duty")
cur.execute(
"UPDATE on_call SET on_duty = false WHERE doctor = %s", (doctor,)
)
if __name__ == "__main__":
run_in_transaction(
"dbname=hospital",
lambda cur: go_off_duty(cur, "alice"),
)Several details matter here:
- Each attempt opens a fresh transaction. The
with conn.transaction()block rolls back automatically if an exception escapes it. - The business rule check (
ValueError) is not retried. It is a real failure, not a conflict. - The jitter spreads out retries. Without it, two transactions that collided once will often wake at the same time and collide again.
- After the final attempt the error is re-raised, so the caller learns that the work did not happen.
What can be retried safely
A retry is safe when the transaction touches only the database, because the rollback erased every effect of the failed attempt. It is not automatically safe when the transaction also did something outside the database.
- Send emails, publish messages and call external APIs after the commit, or use an outbox table written inside the same transaction.
- Generate identifiers such as order numbers inside the retried function, or make them idempotent keys that stay the same across attempts.
- If the connection drops during
COMMIT, you do not know whether the commit happened. Retrying blindly can apply the work twice. An idempotency key or a unique constraint lets you detect the earlier success.
How deadlocks form
A deadlock needs two transactions that take locks in opposite orders.
-- Session A -- Session B
BEGIN; BEGIN;
UPDATE accounts SET balance = balance - 10
WHERE id = 1; -- locks row 1
UPDATE accounts SET balance = balance - 10
WHERE id = 2; -- locks row 2
UPDATE accounts SET balance = balance + 10
WHERE id = 2; -- waits for B
UPDATE accounts SET balance = balance + 10
WHERE id = 1; -- waits for A: deadlockSession A waits for B, and B waits for A. The database finds the cycle and aborts one of them. PostgreSQL checks for deadlocks after a transaction has waited for deadlock_timeout, which defaults to one second. InnoDB checks immediately and typically rolls back the transaction that has changed the fewest rows. SQL Server picks the victim by DEADLOCK_PRIORITY, then by the cost of rollback.
Reducing deadlocks
Retries are the safety net, but you can make deadlocks rarer.
- Lock in a consistent order. If every transfer updates the lower account id first, the cycle above cannot form.
- Keep transactions short. Do not wait for user input or remote calls while holding locks.
- Lock early. Use
SELECT ... FOR UPDATEat the start for rows you will certainly change, instead of reading first and upgrading later. - Touch fewer rows. Narrow
WHEREclauses and good indexes mean fewer locks. In InnoDB, an unindexed update can lock many more rows than it changes. - Avoid mixed access patterns. Different code paths that update the same tables in different orders are the usual source of deadlocks.
The following SQL shows the consistent-order fix for a transfer between two accounts:
BEGIN;
-- Always lock the lower id first, whichever direction the money moves
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;ORDER BY id makes the lock acquisition order deterministic. Most engines lock rows in the order they return them, though this is not a formal guarantee in every case, so test it on your engine.
Controlling waits
Waiting is the third source of failure. A transaction that waits forever ties up a connection and blocks others behind it.
-- PostgreSQL: fail fast instead of waiting
SET lock_timeout = '2s';
SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; -- error at once if locked
SELECT * FROM jobs WHERE state = 'queued'
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- take an unlocked row
-- MySQL 8: the same row-level options exist
SET SESSION innodb_lock_wait_timeout = 2;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;NOWAIT raises an error immediately if the row is locked. SKIP LOCKED ignores locked rows, which makes it a good fit for job queues where several workers pull work. Both are application-level choices. A timeout error is retryable in the same way as a deadlock, but if timeouts are frequent, the real problem is that something holds locks too long.
Serialization failures under snapshot isolation
At REPEATABLE READ in PostgreSQL, a transaction that tries to update a row changed by another transaction since its snapshot fails with 40001 ("could not serialize access due to concurrent update"). This is how PostgreSQL prevents lost updates at that level. At SERIALIZABLE, PostgreSQL also uses predicate tracking (Serializable Snapshot Isolation) to detect write skew, and may abort a transaction even when no single row conflicted.
This leads to two practical points:
- False positives happen. SSI is conservative, so it can abort a transaction that would have been fine. The rate depends on how much data your transactions read. Indexed, narrow reads produce fewer false aborts than table scans.
- The failure can arrive at any statement, including
COMMIT. Your retry logic must wrap the commit too. In the Python example above, thewith conn.transaction()exit performs the commit inside thetry, so it is covered.
MySQL's SERIALIZABLE works differently. It turns plain reads into locking reads, so you see more waits and deadlocks, and fewer serialization failures.
Monitoring and tuning
A retry loop hides problems if you never look at how often it fires. Track these:
- The number of retries per transaction type. A rate that rises over time points to growing contention.
- Retry exhaustion, meaning the transactions that failed all attempts.
- In PostgreSQL,
pg_stat_database.deadlocksandpg_stat_database.conflicts, pluslog_lock_waits = onto log waits longer thandeadlock_timeout. - In MySQL,
SHOW ENGINE INNODB STATUSshows the latest deadlock, andinnodb_print_all_deadlocks = ONlogs every one. - In SQL Server, the
xml_deadlock_reportevent in Extended Events captures the full deadlock graph.
If retries are common for one transaction, shorten it, narrow the rows it reads, change its lock order, or move that case to an explicit lock such as SELECT ... FOR UPDATE so conflicts become waits instead of aborts.
Common mistakes
- Retrying only some errors. Retrying every exception can repeat a constraint violation forever. Retry the specific codes above.
- No retry limit. An unbounded loop under heavy contention keeps the system busy and makes the contention worse.
- No backoff. Immediate retries collide again.
- Side effects inside the transaction. A retry sends the email twice.
- Assuming
READ COMMITTEDnever fails. It can still deadlock and time out.
Exercise
Two sessions run at SERIALIZABLE in PostgreSQL. One receives SQLSTATE 40001 on its COMMIT. A developer proposes catching the error and re-running only the final UPDATE, because "the earlier SELECTs already succeeded." Why is this wrong, and what should the code do instead?
Show answer
The transaction was rolled back as a whole, so its earlier statements have no effect, and its earlier SELECTs may have returned data that is no longer current. The decision to run the UPDATE was based on that stale data, which is exactly what the serialization failure flagged. The code should roll back, then rerun the entire transaction function from the first statement so it re-reads the data, re-checks the rule, and writes again. It should retry a limited number of times with backoff and jitter.
Exercise
Two transfer functions deadlock occasionally. One moves money from account 1 to 2, the other from 2 to 1, each updating the source row first. Give one change that prevents the deadlock without relying on retries.
Show answer
Make both functions lock the rows in the same order, for example by running SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE at the start of the transaction. With a consistent order, one transaction waits for the other instead of forming a cycle.