Postgres “deadlock detected” (40P01) – read it, then remove the lock-order problem

By Abheesht Tripathi · Published

ERROR:  deadlock detected
DETAIL:  Process 4120 waits for ShareLock on transaction 9123; blocked by process 4188.
Process 4188 waits for ShareLock on transaction 9122; blocked by process 4120.
HINT:  See server log for query details.   (SQLSTATE 40P01)

What it means

Two transactions each hold a lock the other one needs. Neither can continue, so after deadlock_timeout (1 second by default) Postgres checks the wait graph, finds the cycle, and cancels one of them with 40P01. The other one then finishes normally. Nothing is corrupted: the cancelled transaction is rolled back completely. But your user sees an error, and under load it keeps happening.

“ShareLock on transaction N” means “waiting for transaction N to finish”, which almost always means waiting for a row that transaction N has updated or locked.

The usual cause: the same rows, locked in a different order

Transaction A updates account 1 then account 2. At the same moment transaction B updates account 2 then account 1. A holds 1 and waits for 2; B holds 2 and waits for 1. Common real versions:

Step 1: find the two statements

The client only gets the summary. The server log has a line per process with the query it was running. On Supabase, open the Postgres logs in the dashboard and search for deadlock detected; the entry includes both statements. Pair them with the code paths that issue them.

Step 2: lock rows in one fixed order

Before changing several rows, lock them all in a single statement sorted by primary key. Every transaction then queues in the same order and cannot form a cycle:

create or replace function public.transfer(from_id bigint, to_id bigint, amount numeric)
returns void
language plpgsql
set search_path = ''
as $$
begin
  -- lock both rows, lowest id first, before touching either
  perform 1 from public.accounts
  where id in (from_id, to_id)
  order by id
  for update;

  update public.accounts set balance = balance - amount where id = from_id;
  update public.accounts set balance = balance + amount where id = to_id;
end;
$$;

For batch writes, sort the rows by their key in your code before sending them, so every request inserts or updates in the same order.

Step 3: keep transactions short

Do API calls, file uploads and model calls before begin or after commit, never in between. The less time a transaction holds row locks, the smaller the window for a cycle. Index foreign key columns too: a delete or key update on a parent table must find the child rows, and a sequential scan makes that transaction much slower.

Step 4: retry the loser

Even with good ordering, a rare deadlock can still happen. Postgres has already rolled the transaction back, so retrying the whole transaction is safe. With supabase-js the SQLSTATE is in error.code; with node-postgres it's err.code:

const RETRYABLE = new Set(['40P01', '40001']);   // deadlock, serialization failure

async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
  for (let i = 1; ; i++) {
    try {
      return await fn();
    } catch (e: any) {
      if (!RETRYABLE.has(e?.code) || i >= attempts) throw e;
      await new Promise((r) => setTimeout(r, 50 * 2 ** i + Math.random() * 50));
    }
  }
}

await withRetry(async () => {
  const { error } = await supabase.rpc('transfer', { from_id: 7, to_id: 3, amount: 25 });
  if (error) throw error;
});

Retry only the whole unit of work, and only if it is safe to repeat (no email already sent from inside it).

How to verify

Reproduce with two psql sessions: in session 1 run begin; update accounts set balance = balance where id = 1;, in session 2 the same for id 2, then cross over. You get 40P01. Repeat through the transfer function in both directions: the second call simply waits for the first and both succeed. In production the Postgres logs should stop showing deadlock detected.

Related guides

More in Postgres errors and performance · all guides