feat(database): publish pgxpool pool stats as metrics (#12737)

# Which Problems Are Solved

ZITADEL opens its Postgres connection pool via `pgxpool.NewWithConfig`
(`internal/database/postgres/pg.go`) but never reads
`pgxpool.Pool.Stat()`,
so operators have no way to observe pool saturation (acquired/idle/total
conns vs. `MaxConns`) or connection churn (acquire waits, canceled/empty
acquires, idle/lifetime destroys, new connections) through ZITADEL's
existing metrics pipeline.

# How the Problems Are Solved

- Adds `RegisterCounterObserver` (backed by an OTel
`Int64ObservableCounter`)
  to the `Metrics` interface, its implementation, and the test mock
  (`backend/v3/instrumentation/metric.go`,
  `backend/v3/instrumentation/metrics/metric.go`,
  `backend/v3/instrumentation/metrics/mock.go`), mirroring the existing
`RegisterValueObserver`/`RegisterUpDownSumObserver` — there was
previously
  no observable instrument for cumulative counters.
- Adds `database.RegisterPoolMetrics(ctx, pool)`
  (`internal/database/metrics.go`), which registers 5 observable gauges
  (`acquired_conns`, `constructing_conns`, `idle_conns`, `max_conns`,
  `total_conns`) and 7 observable counters (`acquire_count`,
  `acquire_duration_milliseconds`, `canceled_acquire_count`,
  `empty_acquire_count`, `max_idle_destroy_count`,
  `max_lifetime_destroy_count`, `new_conns_count`) sourced directly from
`pgxpool.Pool.Stat()`, published under `zitadel.database.pool.*` metric
  names.
- Wires the registration call into `cmd/start/start.go` right after the
  pool is created, so the running server process exposes these series on
  `/metrics`.

# Additional Changes

- Adds unit tests covering the new `RegisterCounterObserver` method
  (`backend/v3/instrumentation/metric_test.go`) and the pool metrics
  registration (`internal/database/metrics_test.go`).

# Additional Context

- Scope is intentionally limited to `cmd/start` (the long-running
process
  that serves `/metrics`); one-shot commands (`setup`, `mirror`,
`initialise`, `key`) are left untouched since an exporter running for a
  single command invocation wouldn't produce useful series.
- https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool#Stat
This commit is contained in:
Tim Möhlmann
2026-09-15 12:13:30 +02:00
committed by GitHub
parent 8ccd5b206f
commit 73de633c71
7 changed files with 223 additions and 0 deletions
+15
View File
@@ -33,6 +33,7 @@ type Meter struct {
Counters sync.Map
UpDownSumObserver sync.Map
ValueObservers sync.Map
CounterObservers sync.Map
Histograms sync.Map
}
@@ -136,6 +137,20 @@ func (m *Meter) RegisterValueObserver(name, description string, callbackFunc met
return nil
}
func (m *Meter) RegisterCounterObserver(name, description string, callbackFunc metric.Int64Callback) error {
if _, exists := m.CounterObservers.Load(name); exists {
return nil
}
counter, err := m.Meter.Int64ObservableCounter(name, metric.WithInt64Callback(callbackFunc), metric.WithDescription(description))
if err != nil {
return err
}
m.CounterObservers.Store(name, counter)
return nil
}
func MapToAddOption(labels map[string]attribute.Value) []metric.AddOption {
return []metric.AddOption{metric.WithAttributes(labelsToAttributes(labels)...)}
}
+48
View File
@@ -1,10 +1,15 @@
package instrumentation
import (
"context"
"slices"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/metric"
sdk_metric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
"go.opentelemetry.io/otel/sdk/resource"
)
@@ -201,6 +206,49 @@ func Test_newMeterProvider(t *testing.T) {
}
}
func TestMeter_RegisterCounterObserver(t *testing.T) {
reader := sdk_metric.NewManualReader()
provider := sdk_metric.NewMeterProvider(sdk_metric.WithReader(reader))
m := &Meter{Meter: provider.Meter(t.Name())}
callback := func(_ context.Context, o metric.Int64Observer) error {
o.Observe(42)
return nil
}
err := m.RegisterCounterObserver("test.counter.observer", "test counter observer", callback)
require.NoError(t, err)
// registering the same name again is a no-op, not an error.
err = m.RegisterCounterObserver("test.counter.observer", "test counter observer", callback)
require.NoError(t, err)
_, exists := m.CounterObservers.Load("test.counter.observer")
assert.True(t, exists)
var rm metricdata.ResourceMetrics
require.NoError(t, reader.Collect(t.Context(), &rm))
got := findMetric(t, rm, "test.counter.observer")
sum, ok := got.Data.(metricdata.Sum[int64])
require.True(t, ok, "expected an observable counter (Sum[int64]), got %T", got.Data)
assert.True(t, sum.IsMonotonic)
require.Len(t, sum.DataPoints, 1)
assert.Equal(t, int64(42), sum.DataPoints[0].Value)
}
// findMetric locates a metric by name across all scopes collected from a reader.
func findMetric(t *testing.T, rm metricdata.ResourceMetrics, name string) metricdata.Metrics {
t.Helper()
for _, sm := range rm.ScopeMetrics {
if i := slices.IndexFunc(sm.Metrics, func(m metricdata.Metrics) bool { return m.Name == name }); i >= 0 {
return sm.Metrics[i]
}
}
t.Fatalf("metric %q not found in collected data", name)
return metricdata.Metrics{}
}
func Test_newMeterProvider_autoexport(t *testing.T) {
resource, err := resource.New(t.Context())
require.NoError(t, err)
@@ -28,6 +28,7 @@ type Metrics interface {
AddHistogramMeasurement(ctx context.Context, name string, value float64, labels map[string]attribute.Value) error
RegisterUpDownSumObserver(name, description string, callbackFunc metric.Int64Callback) error
RegisterValueObserver(name, description string, callbackFunc metric.Int64Callback) error
RegisterCounterObserver(name, description string, callbackFunc metric.Int64Callback) error
RegisterHistogram(name, description, unit string, buckets []float64) error
}
@@ -69,3 +70,7 @@ func RegisterUpDownSumObserver(name, description string, callbackFunc metric.Int
func RegisterValueObserver(name, description string, callbackFunc metric.Int64Callback) error {
return globalMeter().RegisterValueObserver(name, description, callbackFunc)
}
func RegisterCounterObserver(name, description string, callbackFunc metric.Int64Callback) error {
return globalMeter().RegisterCounterObserver(name, description, callbackFunc)
}
@@ -66,6 +66,10 @@ func (m *MockMetrics) RegisterValueObserver(name, description string, callbackFu
return nil
}
func (m *MockMetrics) RegisterCounterObserver(name, description string, callbackFunc metric.Int64Callback) error {
return nil
}
func (m *MockMetrics) RegisterHistogram(name, description, unit string, buckets []float64) error {
return nil
}