Diagnosing and Resolving Deadlocks in PostgreSQL and MySQL: A Practical Guide to Lock Logs, Wait-For Graphs, and Safe Transactions

Database tutorial - IT technology blog
Database tutorial - IT technology blog

When Concurrent Queries Collide: The Deadlock Problem

Few production incidents disrupt a team quite like a sudden wave of database deadlocks. Throughput looks fine at 300 requests per second. Then an unexpected traffic surge hits 1,200 requests per second, and your APM starts firing alerts. PostgreSQL returns 40P01: deadlock detected, while MySQL throws ERROR 1213 (40001): Deadlock found when trying to get lock. In isolation, every query executed cleanly in under 4 milliseconds. Combined under load, they grind each other to a halt.

Relational engines enforce strict ACID guarantees through locking. When two or more concurrent transactions request exclusive access to the same records in an opposing order, progress stops. Neither transaction can yield, and neither can finish. To break the stall, the database engine steps in, designates one transaction as the victim, and rolls it back.

Patching over the symptom with blunt retry loops only hides underlying schema and query design flaws. Lasting fixes require understanding lock states, reading wait-for graphs, and ordering database mutations predictably from the start.

Core Concepts: Locks, Cyclic Dependencies, and Wait-For Graphs

Unraveling a deadlock begins with understanding how lock modes interact inside the engine.

Row Locks and Conflicting Modes

To maximize concurrency without locking whole tables on simple writes, relational databases separate read locks from write locks:

  • Shared Locks (S): Claimed during reads when explicit row stability is required, such as SELECT ... FOR SHARE. Multiple concurrent transactions can hold shared locks on the same record simultaneously without blocking one another.
  • Exclusive Locks (X): Acquired during row writes (UPDATE, DELETE, or SELECT ... FOR UPDATE). Only one transaction can hold an exclusive lock on a row at any time. Any other connection requesting either shared or exclusive access must wait.

The Classic Cross-Lock Scenario

Imagine a ledger table handling balance transfers between Account 101 and Account 202. Two transfers execute concurrently:

  1. Transaction 1 (Tx1): Updates Account 101, acquiring an exclusive lock on record 101.
  2. Transaction 2 (Tx2): Updates Account 202, acquiring an exclusive lock on record 202.
  3. Tx1: Attempts to update Account 202. The engine pauses Tx1 because Tx2 holds that record.
  4. Tx2: Attempts to update Account 101. The engine pauses Tx2 because Tx1 owns record 101.

Neither thread can proceed. Both are waiting on locks held by the other.

The Wait-For Graph (WFG)

To detect these dead-ends, database engines track active sessions using an internal directed graph called a Wait-For Graph. In this graph, vertices represent transactions and edges signify pending lock requests (for example, Tx1 → Tx2 means Tx1 is waiting for Tx2).

Engines resolve circular dependencies differently:

  • MySQL InnoDB: By default (innodb_deadlock_detect = ON), InnoDB checks the graph instantly whenever a transaction enters a lock wait. If a cycle forms (Tx1 → Tx2 → Tx1), it immediately aborts the transaction with the fewest modified rows.
  • PostgreSQL: Cycle checks are computationally expensive. Instead of running on every wait, PostgreSQL delays verification until deadlock_timeout expires (default: 1000ms). If the lock remains ungranted after one second, the engine scans the graph and cancels one of the blocked backends.

Hands-on Practice: Diagnosing Logs and Designing Safe Transactions

Tip 1: Inspecting Deadlock Reports in MySQL InnoDB

InnoDB saves its most recent deadlock trace in memory. Retrieve it immediately via the terminal:

SHOW ENGINE INNODB STATUS\G

Locate the LATEST DETECTED DEADLOCK block in the output:

------------------------
LATEST DETECTED DEADLOCK
------------------------
2026-11-25 10:15:32 0x7f9a14c2b700
*** (1) TRANSACTION:
TRANSACTION 189204, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 42, query id 8023 localhost app_user updating
UPDATE accounts SET balance = balance - 100 WHERE id = 202
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 45 page no 4 n bits 72 index PRIMARY of table `bank`.`accounts` 
trx id 189204 lock_mode X locks rec but not gap waiting
Record checksum: id=202

*** (2) TRANSACTION:
TRANSACTION 189205, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 43, query id 8027 localhost app_user updating
UPDATE accounts SET balance = balance + 100 WHERE id = 101
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 45 page no 4 n bits 72 index PRIMARY of table `bank`.`accounts` 
trx id 189205 lock_mode X locks rec but not gap
Record checksum: id=202
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 45 page no 4 n bits 72 index PRIMARY of table `bank`.`accounts` 
trx id 189205 lock_mode X locks rec but not gap waiting
Record checksum: id=101
*** WE ROLL BACK TRANSACTION (1)

Notice how Transaction 2 holds the lock on id=202 while waiting on id=101, and Transaction 1 holds id=101 while waiting on id=202. InnoDB chose Transaction 1 as the rollback victim.

Tip 2: Configuring PostgreSQL for Lock Diagnostics

PostgreSQL routes deadlock details directly to server log files. Update postgresql.conf to make lock contention visible:

# postgresql.conf
log_min_messages = warning
log_min_error_statement = error
deadlock_timeout = 1000ms
log_lock_waits = on

Setting log_lock_waits = on creates an audit trail whenever a query waits longer than 1,000 milliseconds for a lock, even if it clears without deadlocking. When a cycle triggers, the log entry looks like this:

ERROR:  deadlock detected
DETAIL:  Process 21455 waits for ShareLock on transaction 89104; blocked by process 21458.
Process 21458 waits for ShareLock on transaction 89103; blocked by process 21455.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "accounts"
STATEMENT:  UPDATE accounts SET balance = balance + 50 WHERE id = 202;

For active stalls, inspect blocking sessions live using pg_stat_activity and pg_locks:

SELECT 
    blocked.pid              AS blocked_pid,
    blocked.usename          AS blocked_user,
    blocking.pid             AS blocking_pid,
    blocking.usename         AS blocking_user,
    blocked.query            AS blocked_statement,
    blocking.query           AS blocking_statement,
    now() - blocked.query_start AS waiting_duration
FROM pg_catalog.pg_locks         bl_locks
JOIN pg_catalog.pg_stat_activity blocked  ON blocked.pid = bl_locks.pid
JOIN pg_catalog.pg_locks         bk_locks 
    ON  bk_locks.locktype = bl_locks.locktype
    AND bk_locks.database IS NOT DISTINCT FROM bl_locks.database
    AND bk_locks.relation IS NOT DISTINCT FROM bl_locks.relation
    AND bk_locks.page IS NOT DISTINCT FROM bl_locks.page
    AND bk_locks.tuple IS NOT DISTINCT FROM bl_locks.tuple
    AND bk_locks.virtualxid IS NOT DISTINCT FROM bl_locks.virtualxid
    AND bk_locks.transactionid IS NOT DISTINCT FROM bl_locks.transactionid
    AND bk_locks.pid != bl_locks.pid
JOIN pg_catalog.pg_stat_activity blocking ON blocking.pid = bk_locks.pid
WHERE NOT bl_locks.granted;

Tip 3: Enforce Consistent Resource Ordering

Deterministic locking stops deadlocks cold. If every transaction acquires locks in an identical numerical or alphabetical sequence, cyclic dependency cannot occur.

When transferring money between two accounts, sort the primary keys before acquiring row locks:

def transfer_funds(connection, from_account_id: int, to_account_id: int, amount: float):
    # Sort IDs so every worker locks rows in identical order
    first_id, second_id = sorted([from_account_id, to_account_id])
    
    with connection.cursor() as cursor:
        # Acquire exclusive locks deterministically (e.g., 101, then 202)
        cursor.execute(
            "SELECT id, balance FROM accounts WHERE id IN (%s, %s) ORDER BY id FOR UPDATE",
            (first_id, second_id)
        )
        
        cursor.execute(
            "UPDATE accounts SET balance = balance - %s WHERE id = %s",
            (amount, from_account_id)
        )
        cursor.execute(
            "UPDATE accounts SET balance = balance + %s WHERE id = %s",
            (amount, to_account_id)
        )
    connection.commit()

Because all concurrent workers lock lower IDs before higher IDs, thread A will never wait on thread B while thread B waits on thread A.

Tip 4: Keep Transactions Short and Indexes Sharp

Lock duration directly influences collision frequency:

  • Move external I/O out of transactions: Never trigger payment gateway calls, email deliveries, or S3 uploads between BEGIN and COMMIT. A 250ms HTTP latency can hold database locks 50 times longer than necessary.
  • Index every foreign key: Unindexed foreign keys in MySQL force parent-table checks to escalate into wide gap locks or whole-table index scans, locking far more records than intended.
  • Pre-compute before opening transactions: Run validations, hashing, and read-only lookups before opening your write transaction.

Tip 5: Implement Exponential Backoff with Jitter for Retries

Even well-architected systems can encounter rare transient lock conflicts under massive concurrency. Gracefully retry transaction victims using exponential backoff with randomized jitter:

import time
import random
import psycopg2

def execute_with_retry(operation_func, max_retries=3, base_delay=0.05):
    for attempt in range(max_retries):
        try:
            return operation_func()
        except psycopg2.errors.DeadlockDetected:
            if attempt == max_retries - 1:
                raise
            # Exponential backoff (50ms, 100ms, 200ms) plus 10-40ms random jitter
            delay = (base_delay * (2 ** attempt)) + random.uniform(0.01, 0.04)
            time.sleep(delay)

Jitter disperses retry bursts, preventing conflicting transactions from repeatedly colliding at identical time intervals.

Practical Wrap-Up

Deadlocks are rarely random server glitches. They reveal non-deterministic resource access under concurrent pressure. Once you configure SHOW ENGINE INNODB STATUS and PostgreSQL wait logging, lock conflicts become straightforward to trace. Sort your primary keys before locking, keep transactions tightly bounded, and your database will remain resilient under peak traffic.

Share: