Re: Optimize LISTEN/NOTIFY - Mailing list pgsql-hackers

From Joel Jacobson
Subject Re: Optimize LISTEN/NOTIFY
Date
Msg-id 903ce8c3-d991-4855-a5a1-ec39c64f713f@app.fastmail.com
Whole thread Raw
In response to Re: Optimize LISTEN/NOTIFY  ("Joel Jacobson" <joel@compiler.org>)
Responses Re: Optimize LISTEN/NOTIFY
List pgsql-hackers
On Tue, Jan 13, 2026, at 06:46, Joel Jacobson wrote:
> On Wed, Jan 7, 2026, at 21:29, Tom Lane wrote:
>> That seems a little weird: surely such usage is not something we need
>> to optimize.  Maybe it can be justified because it makes the code
>> simpler, but that's not immediately obvious to me.
>
> The reason for not sticking to the two-boolean approach (staged/current)
> like in v32 was to minimize shared dshash operations in favor of local
> hash table operations.
...
> UNLISTEN during PreCommit doesn't touch the shared dshash at all, it
> just records the intent locally.  LISTEN pre-allocates once per channel.
> At commit we iterate the de-duplicated hash table, so we do one dshash
> operation per unique channel rather than per action.  That's 2 dshash
> operations in total.
>
> Since dshash operations involve shared memory access and potential
> contention, doing more work locally with a cheap hash table seemed like
> the right trade-off to me.

Correction to the above claims.
The per-action dshash reduction only applies to UNLISTEN, not LISTEN:

UNLISTEN: reduced from 2 to 1 dshash operation
  * v32: PreCommit dshash (set staged), AtCommit dshash (remove)
  * v34: PreCommit local hash only, AtCommit dshash (remove)

LISTEN: still 2 dshash operations (unchanged)
  * v32: PreCommit dshash (set staged), AtCommit dshash (set current)
  * v34: PreCommit dshash (find_or_insert), AtCommit dshash (set listening=true)

For LISTEN, the local hash table provides deduplication, not per-action
reduction.

For the admittedly silly `LISTEN foo; UNLISTEN foo; LISTEN foo;`
example, v34 does 3 dshash operations (not 2 as I stated): two
find_or_insert during PreCommit plus one find AtCommit.  Still better
than v32's 6.  I agree this isn't something we need to optimize for, but
it's a bonus we get for free thanks to the local hash table.

/Joel



pgsql-hackers by date:

Previous
From: John Naylor
Date:
Subject: Re: [PATCH} Move instrumentation structs
Next
From: Aleksander Alekseev
Date:
Subject: [PATCH] Refactor *_abbrev_convert() functions