Re: Optimize LISTEN/NOTIFY

From: "Joel Jacobson" <joel(at)compiler(dot)org>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Cc: "Tom Lane" <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Subject: Re: Optimize LISTEN/NOTIFY
Date: 2026-01-13 12:10:20
Message-ID: 903ce8c3-d991-4855-a5a1-ec39c64f713f@app.fastmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: 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

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Aleksander Alekseev 2026-01-13 12:34:09 [PATCH] Refactor *_abbrev_convert() functions
Previous Message John Naylor 2026-01-13 11:54:03 Re: [PATCH} Move instrumentation structs