← Back to Backend, page 2

backend-0032 · Hard senior

What is a database deadlock, how does PostgreSQL detect and resolve it, and how do you prevent deadlocks in application code?

A deadlock is a cycle of transactions each waiting for a lock held by the next. PostgreSQL detects it after deadlock_timeout (one second by default), aborts one transaction with SQLSTATE 40P01 and lets the others continue. Prevent it by always taking locks in a consistent order (for example sort ids before updating), keeping transactions short, touching fewer rows, and retrying the aborted transaction.

Full answer

How it happens

  • Transaction 1 updates row A, then wants row B. Transaction 2 updated row B and now wants row A. Each waits for the other forever. The database cannot know which to cancel until it checks the wait graph.

Detection

  • A waiting session checks for cycles after deadlock_timeout. If it finds one, it aborts one transaction with ERROR 40P01 deadlock detected. The application must roll back (locks are released) and retry. Not every deadlock is a bug, but frequent ones are.

Prevention

  1. Consistent order: any code that locks several rows or tables does it in the same order, for example ORDER BY id with SELECT ... FOR UPDATE, or sort the ids in the application. This removes cycles.
  2. Short transactions: do slow work (network calls) outside the transaction. Lock late, commit early.
  3. Lock fewer things: update in one statement, use the right indexes (a missing index makes updates lock and scan more rows), avoid unnecessary SELECT ... FOR UPDATE.
  4. Use lock timeouts (lock_timeout) so waiting does not last forever.
  5. Retry on 40P01 and 40001 with a limit and jitter.

Diagnosis: the log shows both statements and processes. pg_locks and pg_stat_activity show who waits for whom.

javascript
const { Client } = require('pg');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

(async () => {
  const a = new Client(), b = new Client(), admin = new Client();
  await Promise.all([a.connect(), b.connect(), admin.connect()]);
  await a.query("SET deadlock_timeout = '100ms'");                       // detect quickly in this demo
  await admin.query(`DROP TABLE IF EXISTS bk32_rows; CREATE TABLE bk32_rows (id int PRIMARY KEY, n int); INSERT INTO bk32_rows VALUES (1, 0), (2, 0)`);

  const touch = (c, id) => c.query('UPDATE bk32_rows SET n = n + 1 WHERE id = $1', [id]);
  // Run a transaction that updates the rows in the given order, with a pause between the two updates.
  async function work(c, ids) {
    try {
      await c.query('BEGIN');
      await touch(c, ids[0]); await sleep(50); await touch(c, ids[1]);
      await c.query('COMMIT');
      return 'committed';
    } catch (err) { await c.query('ROLLBACK'); return err.code; }
  }

  const clash = await Promise.all([work(a, [1, 2]), work(b, [2, 1])]);            // opposite order
  console.log('opposite lock order :', clash.slice().sort().join(' and '), '(one transaction was chosen as the victim)');

  await admin.query('UPDATE bk32_rows SET n = 0');
  const ordered = await Promise.all([work(a, [1, 2].sort()), work(b, [2, 1].sort())]);   // same order for both
  console.log('same lock order     :', ordered.join(' and '));
  console.log('counters afterwards :', (await admin.query('SELECT n FROM bk32_rows ORDER BY id')).rows.map((r) => r.n).join(', '));

  await admin.query('DROP TABLE bk32_rows');
  await Promise.all([a.end(), b.end(), admin.end()]);
})();

Two sessions update the same two rows in opposite order. deadlock_timeout is set to 100 ms for the demo (the default is one second). Which of the two transactions is chosen as the victim can vary, so the output is sorted. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): opposite lock order : 40P01 and committed (one transaction was chosen as the victim) same lock order : committed and committed counters afterwards : 2, 2

Key points

  • A deadlock is a cycle of lock waits.
  • PostgreSQL aborts one transaction with 40P01.
  • Take locks in a fixed order.
  • Keep transactions short and use lock timeouts.
  • Retry the aborted transaction.

Common mistakes

  • Locking rows in an order that depends on user input.
  • Long transactions that call external services.
  • Not retrying after a deadlock error.
  • Missing indexes that make updates lock too many rows.
  • Treating a deadlock as a database bug.

Follow-ups

  • How do you find the statements involved in a deadlock?
  • What is lock_timeout?
  • How do foreign keys create locks between tables?

Tips

  • Describe the cycle with two rows.
  • State consistent order as the main fix.
  • Mention retry.