Re: Guarantee order of batched pg_advisory_xact_lock

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Nico Heller <nico(dot)heller(at)posteo(dot)de>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Guarantee order of batched pg_advisory_xact_lock
Date: 2026-02-11 21:17:54
Message-ID: 14506.1770844674@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-general

Nico Heller <nico(dot)heller(at)posteo(dot)de> writes:
> We use the following bulk query as we sometimes need acquire multiple
> locks at the same time and want to avoid round-trips to the database:

> |WITH keys(key) AS (SELECT unnest(:keysToLock)) SELECT
> pg_advisory_xact_lock(hashtextextended(key, 0)) FROM keys|

> :keysToLock is a text[] parameter which is pre-sorted in our
> application. This pre-sorting is done to prevent dead locks when two
> concurrent transactions try acquire the same advisory locks (e.g.
> [a,b,c] [b,a,c] can easily deadlock).
> We thought this would be enough, but we occasionally still run into
> deadlocks.

Have you eliminated the possibility that you're getting hash
collisions? With or without that CTE, I can't see a reason for
PG to change the order in which the unnest() results are processed,
so I think you are barking up the wrong tree about where the
problem is.

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Nico Heller 2026-02-11 21:51:40 Re: Guarantee order of batched pg_advisory_xact_lock
Previous Message Nico Heller 2026-02-11 18:44:07 Guarantee order of batched pg_advisory_xact_lock