Sub topic 13
Handling Serialization Failures and Deadlocks
Assume you know basic SQL transactions, including BEGIN, COMMIT, and ROLLBACK. You should also know that multiple clients can update the same tables at the same time.
Concurrent transactions can fail even when every SQL statement is valid. A serialization failure means the database cannot make the transaction appear as if it ran alone. A deadlock means transactions are waiting for one another in a cycle, so none can continue. These are normal outcomes of concurrency control, not necessarily database defects.
Serialization failures
At the SERIALIZABLE isolation level, the database checks whether concurrent transactions could have produced an unsafe result. If they could, it aborts one transaction instead of allowing an inconsistent result.
PostgreSQL reports a serialization failure with SQLSTATE 40001. The application must roll back the failed transaction, wait briefly, and run the complete transaction again.
A retry must create a new transaction. Do not continue using a transaction after its database connection reports an error.
import random
import time
import psycopg
def transfer(conn, source_id, target_id, amount):
for attempt in range(5):
try:
with conn.transaction():
with conn.cursor() as cur:
cur.execute(
"UPDATE accounts SET balance = balance - %s "
"WHERE id = %s AND balance >= %s",
(amount, source_id, amount),
)
if cur.rowcount != 1:
raise ValueError("insufficient funds or missing source")
cur.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, target_id),
)
if cur.rowcount != 1:
raise ValueError("missing target account")
return
except psycopg.errors.SerializationFailure:
if attempt == 4:
raise
delay = 0.05 * (2 ** attempt) + random.uniform(0, 0.05)
time.sleep(delay)The increasing delay is exponential backoff. The random part is jitter. Together, they reduce the chance that several failed clients immediately collide again.
Retry only errors that are temporary and safe to retry. The operation should also be idempotent, or its effects should be fully contained inside the retried transaction. Do not send an email, charge a card, or publish an external message again unless that side effect has its own deduplication mechanism.
Deadlocks
A deadlock commonly occurs when transactions lock the same rows in different orders:
- Transaction A locks row 1 and waits for row 2.
- Transaction B locks row 2 and waits for row 1.
- The database detects the cycle and aborts one transaction.
The surviving transaction can continue. The aborted transaction must roll back and usually should be retried.
| Situation | Typical signal | Usual response |
|---|---|---|
| Serialization failure | PostgreSQL `40001` | Roll back, back off, retry |
| PostgreSQL deadlock | `40P01` | Roll back, back off, retry |
| MySQL InnoDB deadlock | Error `1213` | Roll back, back off, retry |
| SQL Server deadlock victim | Error `1205` | Roll back, back off, retry |
The best prevention is to acquire locks in a consistent order. For example, a transfer should lock the account with the smaller ID first, regardless of the transfer direction.
BEGIN;
-- Always lock accounts in ascending ID order.
SELECT id, balance
FROM accounts
WHERE id IN (10, 25)
ORDER BY id
FOR UPDATE;
UPDATE accounts SET balance = balance - 50 WHERE id = 10;
UPDATE accounts SET balance = balance + 50 WHERE id = 25;
COMMIT;Keep transactions short. Access rows through useful indexes, avoid waiting for user input while a transaction is open, and update only the rows needed.
A practical decision
Use retries for expected transient conflicts. Fix repeated deadlocks by examining the lock order, query plans, transaction length, and indexes. Use explicit locks such as FOR UPDATE when a read must remain valid until a later write. Choose SERIALIZABLE when correctness depends on a multi-row rule and retries are acceptable.
Exercise
Why must a retry start a new transaction instead of continuing the failed one?
Show answer
The failed transaction has been aborted, and its snapshot and locks are no longer valid. A new transaction gets a fresh view of the data.