Skip to content
mentoor

Topic 4 of 5 · 5 min read

Row locks, deadlocks and lock timeouts

Goal: Read a deadlock log, explain the lock order that caused it and change the code so it cannot happen again.

A deadlock happens when two transactions each hold a lock the other needs, and the cure is to make every code path take locks in the same order and keep transactions short. PostgreSQL detects the cycle after deadlock_timeout (one second by default) and aborts one transaction.

Check yourself · 1 of 3

What happens when a second transaction updates a row that another open transaction has already updated?

Choose one answer

Why it matters

Locks are how the database keeps writers from clobbering each other. Usually you never see them. When a slow transaction sits on a row, every request that needs that row queues behind it, and the symptom is a slow or frozen endpoint, not an error.

How locks behave

  • An UPDATE, DELETE or SELECT ... FOR UPDATE takes a row lock that lasts until commit or rollback. Plain reads do not block on it.
  • A second writer on the same row waits. It does not fail.
  • Many schema changes take a table lock. ALTER TABLE can wait behind a long transaction, and then everything else queues behind the ALTER.
  • FOR UPDATE SKIP LOCKED lets workers pick different rows from a job queue. NOWAIT fails at once instead of waiting.

A deadlock, step by step

Transfer A to B and B to A at the same time:

  1. Transaction 1 locks account 1.
  2. Transaction 2 locks account 2.
  3. Transaction 1 asks for account 2 and waits.
  4. Transaction 2 asks for account 1 and waits.

Neither can move. PostgreSQL aborts one with SQLSTATE 40P01 and logs both queries and the process ids.

Fixing it

  1. Consistent order. Always lock the lower id first: sort the ids, then lock them in that order, whatever the direction of the transfer.
  2. Short transactions. Less time holding locks means fewer collisions.
  3. Retry on 40P01. The aborted transaction did nothing; run it again.
  4. Fail fast. SET LOCAL lock_timeout = '2s' makes a transaction give up instead of queuing without limit. Add idle_in_transaction_session_timeout to kill sessions that opened a transaction and went quiet.

Finding who is blocking

SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, state, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;

pg_locks shows each lock and whether it is granted. A row with granted = false is a waiter.

Before and after

# Before: lock order follows the direction of the transfer
lock(src); lock(dst)
# After: lock order is always by id
for acct_id in sorted([src, dst]):
    lock(acct_id)

What goes wrong

  • Locking rows in a loop in whatever order a query returned them.
  • Running a migration during peak traffic without lock_timeout.
  • Treating a deadlock error as a database fault instead of an ordering bug.

Examples

Reading a deadlock log

ERROR: deadlock detected
DETAIL: Process 5121 waits for ShareLock on transaction 9042; blocked by process 5130.
Process 5130 waits for ShareLock on transaction 9041; blocked by process 5121.
Process 5121: UPDATE accounts SET balance = balance - 50 WHERE id = 2
Process 5130: UPDATE accounts SET balance = balance + 50 WHERE id = 1

Each process holds one account and wants the other. Both updates touch accounts 1 and 2 in opposite order. Sorting the ids before updating removes the cycle.

The migration that froze the site

An ALTER TABLE orders ADD COLUMN note text waited behind a report query that had been open for 20 minutes. Every new request on orders then queued behind the ALTER. Running it with SET lock_timeout = '3s' and retrying later would have caused a failed migration, not an outage.

Key points

  • A row lock is held until commit or rollback, and other writers on that row wait rather than fail.
  • A deadlock is a cycle of waits; PostgreSQL aborts one transaction with SQLSTATE 40P01 and logs the queries involved.
  • Taking locks in one agreed order, such as ascending id, makes the cycle impossible.
  • lock_timeout makes a statement give up after a set time instead of queuing behind a long transaction.
  • pg_blocking_pids and pg_locks show which session holds the lock a stuck query is waiting for.

Common mistakes

  • Locking rows in the order a query happens to return them.
  • Waiting for a lock with no timeout in a request handler.
  • Running ALTER TABLE during traffic with no lock_timeout.
  • Blaming the database for deadlocks that an ordering change would remove.

Check yourself · 2 of 3

Transfers lock the source account then the destination, and deadlocks appear when two opposite transfers overlap. Which change removes them?

Choose one answer

Check yourself · 3 of 3

A deploy runs ALTER TABLE on a busy table and the site stalls. Which setting would have made the ALTER give up instead of stalling everything?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic