Sub topic 14
Retrying After Deadlocks and Serialization Failures
Assume you know basic SQL transactions and can run PostgreSQL-style SQL. This chapter focuses on application behavior when concurrent transactions cannot safely complete.
A deadlock occurs when transactions wait for one another forever. For example, Transaction A locks row 1 and waits for row 2, while Transaction B locks row 2 and waits for row 1. The database detects the cycle and aborts one transaction.
A serialization failure occurs when the database cannot make concurrent transactions appear as if they ran one at a time. This commonly happens at the SERIALIZABLE isolation level. PostgreSQL reports a serialization failure with SQLSTATE 40001.
Both errors mean the transaction did not commit. The usual response is to retry the entire transaction.
Retry the whole transaction
Do not retry only the statement that failed. Earlier reads may have influenced later writes, so repeating one statement can produce an incorrect result. Roll back, start a new transaction, and perform every read and write again.
A bounded retry loop prevents an overloaded system from retrying forever. Exponential backoff increases the delay after each failure. Jitter adds a small random value so many clients do not retry simultaneously.
import random
import time
import psycopg
RETRYABLE = {"40P01", "40001"} # deadlock_detected, serialization_failure
def transfer(conn, source_id, target_id, amount, attempts=4):
for attempt in range(attempts):
try:
with conn.transaction():
with conn.cursor() as cur:
cur.execute(
"UPDATE accounts SET balance = balance - %s "
"WHERE id = %s AND balance >= %s "
"RETURNING id",
(amount, source_id, amount),
)
if cur.fetchone() is None:
raise ValueError("insufficient funds or unknown source")
cur.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, target_id),
)
return
except psycopg.errors.DatabaseError as error:
if error.sqlstate not in RETRYABLE or attempt == attempts - 1:
raise
delay = 0.05 * (2 ** attempt) + random.uniform(0, 0.05)
time.sleep(delay)The transaction context rolls back when an exception escapes. The retryable SQLSTATE values identify conflicts that may succeed later. A constraint violation, invalid input, or insufficient funds is usually not transient and should not be retried automatically.
Design for predictable retries
Keep transactions short. Acquire locks in a consistent order, such as ascending account ID, to reduce deadlocks. Set a retry limit and record the final failure. Logs should include the operation, SQLSTATE, attempt number, and elapsed time, but never sensitive values.
Retries cannot fix a permanent conflict or a logic error. If all attempts fail, return a clear error so the caller can try later or ask the user to repeat the operation.
Exercise
Why must an application retry the complete transaction instead of only the failed SQL statement?
Show answer
Earlier reads and writes may have affected the failed statement, so only repeating that statement could use stale assumptions and create an incorrect result.