pg_metrics
pg_metrics · Collects named counters from PostgreSQL backends in shared memory and exposes them through SQL metric functions.
Overview
| ID | Extension | Package | Version | Category | License | Language |
|---|---|---|---|---|---|---|
| 100437 | pg_metrics | pg_metrics | 1.0 | STAT | Unknown | C |
Usage
Sources:
pg_metrics stores named integer counters in PostgreSQL shared memory. Backends can atomically add to a counter, while monitoring sessions enumerate current values and capacity. It is a small building block for custom in-database metrics, not a general time-series store.
Core Workflow
The library must be initialized during postmaster startup. Add it to shared_preload_libraries, optionally set the counter capacity, and restart PostgreSQL before creating the SQL extension.
counter_add returns the previous counter value and then applies the increment. Negative increments are accepted by the int8 signature and can reduce a counter.
User-Facing Objects
metric_type: enum currently containing onlyCOUNTER.counter_add(counter text, increment int8): creates a named counter on first use and atomically adds the increment.metrics(): returnsmetric_name,metric_type, andcounter_valuefor each shared counter.metrics_stats(): returnsmax_metricsandnum_metrics.pg_metrics.max: postmaster setting for the maximum number of counters; the source default is50, with a minimum of10.
Operational Notes
Preloading and a server restart are mandatory: without initialized shared memory, counter_add returns NULL. Names longer than 127 bytes are rejected, and adding a new counter after the shared hash reaches pg_metrics.max also returns NULL. Values live only in shared memory and are reset when the shared-memory state is recreated; there is no persistence or reset SQL API in version 1.0. The counters are shared across backends, while the SQL objects must exist in each database that calls them. Export or snapshot values externally if historical metrics are required.