How-To Guide

How to Handle Deadlocks and Retry Transactions

Recognize database deadlocks, reduce their likelihood with consistent lock order, and retry the losing transaction safely with backoff.

On this page

  1. Introduction
  2. Recognize retryable conditions
  3. Reduce the chance of a deadlock
  4. Retry the whole transaction with backoff
  5. Prefer non-blocking locking where it fits
  6. Test under contention
  7. Common pitfalls
  8. Conclusion

Introduction

A deadlock happens when two or more transactions each hold a lock the other needs, so none can proceed. The database detects the cycle and aborts one transaction, letting the rest finish. The aborted transaction is not a bug in your code; it is a normal contention event that the application must handle by retrying. An application that surfaces deadlock errors to users or crashes on them is treating a routine scheduling event as a failure.

This tutorial explains how to recognize a deadlock and a serialization failure, how to reduce their frequency by ordering locks and shortening transactions, how to retry the losing transaction correctly with backoff, and how to test the behavior under real contention. The examples use PostgreSQL error codes, but MySQL, SQL Server, and SQLite expose analogous retryable errors.

Recognize retryable conditions

Two database conditions are retryable by design. A deadlock surfaces as a specific error, deadlock_detected in PostgreSQL, and aborts the victim transaction. A serialization failure surfaces when a transaction at a stricter isolation level cannot be serialized, serialization_failure in PostgreSQL, and also aborts. Both mean the transaction was rolled back and should be retried; neither indicates a defect in the query.

Classify errors by code, not by message text, because messages differ across versions and locales. A retry policy that matches on the subclass code is stable; one that greps the message string breaks when the database is upgraded or the locale changes. Map the retryable codes to a single predicate and route every transaction through it.

-- PostgreSQL error codes that call for a retry of the whole transaction
-- 40P01  deadlock_detected
-- 40001  serialization_failure
-- 55P03  lock_not_available (FOR UPDATE NOWAIT / SKIP LOCKED contexts)

BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = $1 FOR UPDATE;
UPDATE accounts SET balance = balance - $2 WHERE id = $1;
COMMIT;

Reduce the chance of a deadlock

Most deadlocks come from inconsistent lock ordering. If transaction A locks row 1 then row 2, and transaction B locks row 2 then row 1, they can interleave into a cycle. Make every code path acquire locks in the same order, for example by sorting the ids before locking. A canonical order removes the cycle at the source, turning a potential deadlock into a short wait.

Keep transactions short. The longer a transaction holds locks, the wider the window for another to form a cycle. Do not perform network calls or expensive computation inside a transaction. Do not read user input mid-transaction. Acquire locks as late as possible and release them as soon as the work is done. Where a single statement can replace several, prefer it, because one statement takes its locks atomically.

-- consistent lock order: always lock the lower id first
BEGIN;
SELECT id FROM accounts WHERE id IN ($1, $2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance + $3 WHERE id = $1;
UPDATE accounts SET balance = balance - $3 WHERE id = $2;
COMMIT;

Retry the whole transaction with backoff

The retry must wrap the entire transaction, from BEGIN to COMMIT, not a single statement. On a retryable error, roll back, wait a short jittered interval, and run the transaction function again from the top, re-reading whatever it needs. Because the data it read may have changed, the retry must be able to recompute its decisions, which is why the transaction body should be a function with no hidden state.

Bound the retries and use jitter. A fixed number of attempts, each with exponential backoff plus random jitter, avoids the synchronized retry storm that a fleet of clients would otherwise produce. If the retries are exhausted, surface an error, because persistent contention usually means the workload is mis-designed or a lock is held too long, and hiding that behind unlimited retries masks the real problem.

const RETRYABLE = new Set(['40P01', '40001']);

async function withRetry<T>(run: () => Promise<T>, maxAttempts = 5): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    try {
      return await run();
    } catch (err: any) {
      const code = err?.code;
      if (!RETRYABLE.has(code) || attempt >= maxAttempts) throw err;
      const base = Math.min(2000, 50 * 2 ** attempt);
      await new Promise((r) => setTimeout(r, base / 2 + Math.random() * base));
    }
  }
}

Prefer non-blocking locking where it fits

Some workloads do not need to wait for a lock. FOR UPDATE SKIP LOCKED lets a worker claim the next available row without blocking on rows another worker holds, which suits job queues and work distributors. FOR UPDATE NOWAIT fails immediately instead of waiting, letting a caller move to another task. Both reduce the time transactions spend holding locks and therefore reduce contention.

Use these deliberately. SKIP LOCKED is correct for a queue where any worker may take any job, but wrong for a transfer where you must lock an exact pair of accounts. Match the locking mode to the semantic: block when correctness needs a specific row, skip when the row is interchangeable.

-- workers claim distinct jobs without blocking each other
WITH next AS (
  SELECT id FROM jobs
  WHERE status = 'queued'
  ORDER BY created_at
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
UPDATE jobs SET status = 'running', started_at = now()
WHERE id IN (SELECT id FROM next)
RETURNING id;

Test under contention

Reproduce contention deliberately. Spawn many concurrent clients that update an overlapping set of rows, and assert the workload completes and that no deadlock error reaches the caller. Then remove the lock ordering and assert that deadlocks do occur, which proves the test is capable of detecting them. A test that never triggers contention proves nothing about the retry path.

# hammer the transfer endpoint concurrently and assert all requests succeed
seq 1 50 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' \
  -X POST http://localhost:3000/transfer -d '{"from":1,"to":2,"amount":1}'
# expect all 200/204; a surfaced 500 with a deadlock code means the retry is missing

Common pitfalls

Retrying a single statement instead of the whole transaction, matching errors by message text, retrying without backoff or jitter, retrying non-retryable errors such as a constraint violation, holding locks across network calls, and testing only without contention are the recurring mistakes. Wrapping the transaction, classifying by code, adding jittered backoff, shortening the transaction, and testing under load address them.

Conclusion

A deadlock is a normal contention event, so the application must retry. Recognize the retryable codes, reduce their frequency with consistent lock ordering and short transactions, retry the whole transaction with bounded jittered backoff, and prefer non-blocking lock modes where the semantic allows. Self-check by hammering a contested workload concurrently and asserting no deadlock error reaches the caller. Handled this way, contention is absorbed instead of surfacing as a user-visible failure.

Sources: PostgreSQL: Explicit locking and deadlocks, PostgreSQL: Transaction isolation, SQLite: Locking and concurrency.

FAQ

Who is chosen as the deadlock victim?
The database picks one transaction to abort so the others can proceed. The victim receives an error and must be retried. You cannot choose the victim directly, which is why the retry must be automatic and safe.
Can I retry only the failed statement?
No. A deadlock aborts and rolls back the whole transaction. You must restart the transaction from the beginning, re-reading any state it depended on, because the rows it read may have changed.

Related Examples