Clarification on when _PG_init() is invoked for extensions

From: Ayush Vatsa <ayushvatsa1810(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Clarification on when _PG_init() is invoked for extensions
Date: 2025-11-14 11:19:30
Message-ID: CACX+KaPSTwU50rhTcoKEBoRgnPUA=kTuZA_SgyDZTYKYSwFX5g@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello Hackers,

I’m working on a PostgreSQL extension that defines GUCs and initializes
hooks inside the _PG_init() function,
and I wanted to confirm my understanding of when _PG_init() is called and
whether the library remains loaded
across sessions.

Based on documentation and experimentation, I believe the behavior works as
follows, but I would appreciate
confirmation or corrections:

1/ When the extension is listed in shared_preload_libraries: _PG_init() is
executed before the server
starts accepting connections, and hooks are initialized for every backend
process. The downside is that this enables
hooks globally for all databases in the instance.

2/ When using LOAD 'extension': My understanding is that the library loads
only in the backend executing the LOAD
command, and _PG_init() runs just for that backend. I’m unsure whether this
affects existing and future backends for
the same database, or if it is strictly per-backend and non-persistent. I
also believe this mechanism cannot be used if
the extension needs to register a background worker.

3/ When running CREATE EXTENSION: Here the .so is loaded lazily when a
function defined with MODULE_PATHNAME is
first executed or defined. In this model, I’m unsure whether I need to
explicitly run LOAD 'extension' to ensure
_PG_init() runs for other existing and upcoming backends. Also wanted to
check if I need LOAD extname in my sql script?

*My use case:*
I would like the extension to initialize hooks automatically, but only for
all (existing and upcoming) backends of the specific
database where the extension is installed - not globally across all
databases.

If someone could confirm whether my understanding is correct
Thanks in advance for your guidance.
Regards,
Ayush

Browse pgsql-hackers by date

  From Date Subject
Next Message John Naylor 2025-11-14 11:34:37 Re: Proposal for enabling auto-vectorization for checksum calculations
Previous Message Amit Kapila 2025-11-14 11:15:23 Re: DOCS: Missing <structfield> tags for some SEQUENCE fields