Full answer
Classic case: a transfer between two wallets. Transaction 1 moves money from A to B (locks A, then B). Transaction 2 moves money from B to A (locks B, then A). Each waits for the other, so neither can proceed. PostgreSQL notices after deadlock_timeout (1 second by default), cancels one transaction and the other continues.
Prevention:
- Lock in a deterministic order:
list(Wallet.objects.select_for_update().filter(pk__in=[a, b]).order_by("pk"))locks both rows in ID order, whichever direction the transfer goes. Both transactions then queue on the lower ID first, and no cycle can form. - Keep transactions short: no network calls, emails or slow computation while holding locks.
- Touch tables in a consistent order across code paths.
- Use
F()expressions for single-row atomic updates; they take one row lock briefly. - Prefer
select_for_update(skip_locked=True)for work queues andnowait=Trueto fail fast.
Retry:
- Deadlocks (
40P01) and serialization failures at SERIALIZABLE or REPEATABLE READ (40001) are transient. The right response is to roll back and run the entire transaction again from the start, not only the failed statement. - In Django, the error appears as
django.db.OperationalErrorwith the driver error in__cause__(psycopg.errors.DeadlockDetected,.sqlstate). Retry the outermostatomic()block, never from inside a nested block. Use a few attempts with exponential backoff and jitter. - The unit of work must be idempotent or contain only database effects that roll back; do not retry code that has already sent an email.
- Log retries and alert when they spike: frequent deadlocks mean an ordering problem.
Diagnosis: PostgreSQL logs the two statements involved; log_lock_waits and pg_locks show waiters.
import os
import sys
import types
import django
from django.conf import settings
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("PGDATABASE", "school"),
"USER": os.environ.get("PGUSER", "postgres"),
"PASSWORD": os.environ.get("PGPASSWORD", ""),
"HOST": os.environ.get("PGHOST", "localhost"),
"PORT": os.environ.get("PGPORT", "5432"),
}},
)
django.setup()
import threading
import time
from django.db import models, connection, transaction, OperationalError
class Wallet(models.Model):
balance = models.IntegerField()
class Meta:
app_label = "school"
with connection.cursor() as cur:
cur.execute("DROP TABLE IF EXISTS school_wallet")
with connection.schema_editor() as editor:
editor.create_model(Wallet)
a = Wallet.objects.create(balance=100).pk
b = Wallet.objects.create(balance=100).pk
def transfer(src, dst, amount, ordered, gate=None):
with transaction.atomic():
ids = sorted([src, dst]) if ordered else [src, dst]
for pk in ids: # lock the rows one by one
Wallet.objects.select_for_update().get(pk=pk)
if gate is not None and pk == ids[0]:
gate.wait(timeout=5) # make both transactions hold their first lock
Wallet.objects.filter(pk=src).update(balance=models.F("balance") - amount)
Wallet.objects.filter(pk=dst).update(balance=models.F("balance") + amount)
def with_retry(fn, attempts=4):
for attempt in range(attempts):
try:
return fn(attempt)
except OperationalError as exc:
sqlstate = getattr(exc.__cause__, "sqlstate", None)
if sqlstate not in ("40P01", "40001") or attempt == attempts - 1:
raise
time.sleep(0.05 * 2 ** attempt) # backoff (add jitter in production)
def run(ordered, retry):
outcome = {"deadlocks": 0, "retries": 0, "ok": 0}
gate = threading.Barrier(2)
def worker(src, dst):
try:
def job(attempt):
if attempt:
outcome["retries"] += 1
return transfer(src, dst, 10, ordered, gate if attempt == 0 and not ordered else None)
(with_retry if retry else (lambda f: f(0)))(job)
outcome["ok"] += 1
except OperationalError as exc:
if getattr(exc.__cause__, "sqlstate", None) == "40P01":
outcome["deadlocks"] += 1
finally:
connection.close()
threads = [threading.Thread(target=worker, args=(a, b)), threading.Thread(target=worker, args=(b, a))]
for t in threads:
t.start()
for t in threads:
t.join()
return outcome
print("opposite order, no retry:", run(ordered=False, retry=False))
print("opposite order, with retry:", run(ordered=False, retry=True))
print("consistent order:", run(ordered=True, retry=False))
print("total balance preserved:", sum(Wallet.objects.values_list("balance", flat=True)))
with connection.cursor() as cur:
cur.execute("DROP TABLE school_wallet")
Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. The demo forces a deadlock with a barrier; PostgreSQL takes about a second (deadlock_timeout) to detect it, so the snippet takes a few seconds. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): opposite order, no retry: {'deadlocks': 1, 'retries': 0, 'ok': 1} opposite order, with retry: {'deadlocks': 0, 'retries': 1, 'ok': 2} consistent order: {'deadlocks': 0, 'retries': 0, 'ok': 2} total balance preserved: 200
Key points
- Deadlock is a cycle of lock waits; PostgreSQL aborts one transaction (40P01)
- Lock rows in a consistent order, such as order_by('pk')
- Keep transactions short and free of external calls
- Retry the whole outer transaction with backoff for 40P01 and 40001
- Make the retried unit idempotent; log retries
Common mistakes
- Locking rows in different orders in different code paths
- Retrying only the failed statement instead of the whole transaction
- Retrying work that already has external side effects
- Holding transactions open across network calls
- Ignoring deadlock log lines that point to an ordering bug
Follow-ups
- How does SERIALIZABLE isolation produce 40001 errors and how do you retry them?
- What do skip_locked and nowait do?
- How do you find which queries deadlocked?
Tips
- Explain the cycle with two transfers
- Give the ordering fix
- Say retry the outermost transaction