Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7016: Add read replica infrastructure (#7979)

Multica Eve6a65922ef76e
diff --git a/.env.example b/.env.example
index 1aa488b979..84269a52f1 100644
--- a/.env.example
+++ b/.env.example
@@ -9,6 +9,17 @@ DATABASE_URL=postgres://multica:multica@localhost:5432/multica?sslmode=disable
# DATABASE_URL; env vars below take precedence over URL params.
# DATABASE_MAX_CONNS=25
# DATABASE_MIN_CONNS=5
+# Optional PostgreSQL read replica. The API keeps all existing reads on primary
+# until a business explicitly opts into eventual-consistency routing in code.
+# Every new replica connection is required to be read-only and is recycled
+# after 5m by default so a promoted node is revalidated promptly. Replica
+# failures fall back to primary and open a short passive circuit; no background
+# database probe is added. Replica reads may return stale data without a bound.
+# DATABASE_REPLICA_URL=postgres://multica:multica@replica:5432/multica?sslmode=require&target_session_attrs=read-only
+# Replica pool sizing is independent so enabling it does not clone the primary
+# pool's 25 / 5 connection budget per API process.
+# DATABASE_REPLICA_MAX_CONNS=10
+# DATABASE_REPLICA_MIN_CONNS=0
# Retry transient database failures for up to this duration across the image
# entrypoint's migration and API startup phases. Set to 0 for a single
# fail-fast attempt per phase. Each connection attempt is separately bounded
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index a56dd14626..9173776fee 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -16,12 +16,17 @@ All configuration is done via environment variables. Copy `.env.example` as a st
### Database Pool Tuning (Optional)
-These have sensible defaults and only need to be set when tuning a large or constrained deployment. Precedence (highest first): env var → `pool_*` query params on `DATABASE_URL` → built-in default.
+These have sensible defaults and only need to be set when tuning a large or constrained deployment. For each pool, precedence is: its environment variable → `pool_*` query parameters on that pool's URL → built-in default.
| Variable | Description | Default |
|----------|-------------|---------|
| `DATABASE_MAX_CONNS` | pgxpool max connections per pod. `pod_count × DATABASE_MAX_CONNS` should stay well below the Postgres `max_connections` ceiling. With a connection pooler (PgBouncer / RDS Proxy / Supavisor) in front, this can be raised significantly. | `25` |
| `DATABASE_MIN_CONNS` | pgxpool warm baseline connections per pod. Auto-clamped to `DATABASE_MAX_CONNS`. | `5` |
+| `DATABASE_REPLICA_URL` | Optional PostgreSQL read-only replica connection string. New connections are validated as read-only, but no business traffic uses the replica until a read path explicitly opts in. | - |
+| `DATABASE_REPLICA_MAX_CONNS` | Maximum replica connections per pod. This budget is independent of `DATABASE_MAX_CONNS`. | `10` |
+| `DATABASE_REPLICA_MIN_CONNS` | Warm replica connections per pod. | `0` |
+
+Budget the sum of primary and replica pool limits across every API pod against the PostgreSQL cluster connection ceiling. The replica pool defaults to a five-minute connection lifetime (overridable with the `pool_max_conn_lifetime` URL parameter) so read-only validation is refreshed after promotion. Replica configuration is non-critical: invalid configuration or runtime connection failure makes explicitly opted-in reads fall back to primary, with a short passive circuit preventing every request from paying the connection timeout. Existing read paths remain primary-only until migrated individually. Replica reads have no application-enforced staleness bound; monitor replication lag in the database layer and keep consistency-sensitive reads on primary.
### Email (Required for Authentication)
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index dd4bba1f96..779f94b0d3 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -33,6 +33,9 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `DATABASE_URL` | ローカルの `multica` データベース | PostgreSQL 接続文字列 |
| `DATABASE_MAX_CONNS` | `25` | API プロセスあたりの最大データベース接続数 |
| `DATABASE_MIN_CONNS` | `5` | API プロセスが保持する最小接続数 |
+| `DATABASE_REPLICA_URL` | 空 | オプションの PostgreSQL 読み取り専用レプリカ接続文字列。新しい接続では読み取り専用状態が検証され、各機能はコードで結果整合性読み取りを明示的に選択する必要があります |
+| `DATABASE_REPLICA_MAX_CONNS` | `10` | API プロセスあたりの最大レプリカ接続数 |
+| `DATABASE_REPLICA_MIN_CONNS` | `0` | API プロセスが保持する最小レプリカ接続数 |
| `MULTICA_DATABASE_STARTUP_TIMEOUT` | `3m` | コンテナ起動時に migration と API が共有する、一時的なデータベース障害への再試行時間。`0` にすると各フェーズで 1 回だけ試行します |
| `MULTICA_DATABASE_CONNECT_TIMEOUT` | `5s` | 起動時の接続試行ごとのフォールバックタイムアウト。pgx ネイティブの `connect_timeout`、`PGCONNECT_TIMEOUT`、service 設定が優先されます |
| `PORT` | `8080` | API のリッスンポート |
@@ -45,6 +48,8 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
Kubernetes で shutdown hold を設定する場合、`terminationGracePeriodSeconds` は hold と実際のシャットダウンにかかる時間の合計より大きくしてください。
+primary とレプリカの接続上限は独立しています。全 API プロセスの合計が PostgreSQL クラスターの接続上限に収まるように設定してください。レプリカ接続はデフォルトで 5 分後に再作成され、昇格後に読み取り専用状態を再検証します。接続失敗時はインフラストラクチャが透過的に primary へフォールバックし、短時間のパッシブサーキットを開きます。バックグラウンドのデータベースプローブは追加されません。アプリケーションはレプリカデータの最大経過時間を保証しないため、データベース層でレプリケーション遅延を監視し、整合性が必要な読み取りは primary に残してください。
+
## 公開アドレスとブラウザアクセス
| 変数 | デフォルト | 説明 |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 1785d19048..60dd8827bd 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -33,6 +33,9 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `DATABASE_URL` | 로컬 `multica` 데이터베이스 | PostgreSQL 연결 주소 |
| `DATABASE_MAX_CONNS` | `25` | API 프로세스 하나의 최대 데이터베이스 연결 수 |
| `DATABASE_MIN_CONNS` | `5` | API 프로세스 하나가 유지하는 최소 연결 수 |
+| `DATABASE_REPLICA_URL` | 비어 있음 | 선택적 PostgreSQL 읽기 전용 복제본 연결 주소. 새 연결은 읽기 전용 상태를 검증하며 각 기능은 코드에서 최종 일관성 읽기를 명시적으로 선택해야 함 |
+| `DATABASE_REPLICA_MAX_CONNS` | `10` | API 프로세스당 최대 복제본 연결 수 |
+| `DATABASE_REPLICA_MIN_CONNS` | `0` | API 프로세스가 유지하는 최소 복제본 연결 수 |
| `MULTICA_DATABASE_STARTUP_TIMEOUT` | `3m` | 컨테이너 시작 중 migration과 API가 공유하는 일시적인 데이터베이스 장애 재시도 시간. `0`으로 설정하면 각 단계에서 한 번만 시도 |
| `MULTICA_DATABASE_CONNECT_TIMEOUT` | `5s` | 시작 중 각 연결 시도의 폴백 제한 시간. pgx 기본 `connect_timeout`, `PGCONNECT_TIMEOUT` 또는 service 설정이 우선 적용됨 |
| `PORT` | `8080` | API listen port |
@@ -45,6 +48,8 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
Kubernetes에서 shutdown hold를 설정하면 `terminationGracePeriodSeconds`가 hold와 실제 종료에 필요한 시간의 합보다 커야 합니다.
+primary와 복제본의 연결 한도는 서로 독립적입니다. 모든 API 프로세스의 연결 합계가 PostgreSQL 클러스터 연결 한도 내에 있도록 설정해야 합니다. 복제본 연결은 기본적으로 5분 후 재생성되어 승격 뒤 읽기 전용 상태를 다시 검증합니다. 연결 실패 시 인프라가 투명하게 primary로 폴백하고 짧은 수동 회로 차단기를 열며, 백그라운드 데이터베이스 점검은 추가하지 않습니다. 애플리케이션은 복제본 데이터의 최대 지연을 보장하지 않으므로 데이터베이스 계층에서 복제 지연을 모니터링하고 일관성이 중요한 읽기는 primary에 유지하십시오.
+
## 공개 주소와 브라우저 접근
| 변수 | 기본값 | 설명 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 713d7705de..78d67c3859 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -33,6 +33,9 @@ You also need to pick an email service, otherwise verification codes and invitat
| `DATABASE_URL` | local `multica` database | PostgreSQL connection string |
| `DATABASE_MAX_CONNS` | `25` | Maximum database connections per API process |
| `DATABASE_MIN_CONNS` | `5` | Minimum connections each API process keeps |
+| `DATABASE_REPLICA_URL` | empty | Optional PostgreSQL read-only replica connection string; new connections are validated as read-only, while businesses must explicitly opt into eventual-consistency reads in code |
+| `DATABASE_REPLICA_MAX_CONNS` | `10` | Maximum replica connections per API process |
+| `DATABASE_REPLICA_MIN_CONNS` | `0` | Minimum replica connections each API process keeps |
| `MULTICA_DATABASE_STARTUP_TIMEOUT` | `3m` | Container-level retry budget shared by migration and API startup; set to `0` for one fail-fast attempt per phase |
| `MULTICA_DATABASE_CONNECT_TIMEOUT` | `5s` | Fallback timeout for each startup connection attempt; native pgx `connect_timeout`, `PGCONNECT_TIMEOUT`, or service settings take precedence |
| `PORT` | `8080` | API listen port |
@@ -45,6 +48,8 @@ You also need to pick an email service, otherwise verification codes and invitat
When setting a shutdown hold on Kubernetes, `terminationGracePeriodSeconds` must exceed the hold plus the time the actual shutdown needs.
+The primary and replica connection limits are independent. Budget their sum across every API process against the PostgreSQL cluster's connection ceiling. Replica connections are recycled after five minutes by default to refresh read-only validation after promotion. Replica connection failures transparently fall back to primary and open a short passive circuit; no background database probe is added. Replica reads have no application-enforced staleness bound, so monitor lag in the database layer and keep consistency-sensitive reads on primary.
+
## Public URLs and browser access
| Variable | Default | Description |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index a24d04d0e4..253f7bfdb4 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -33,6 +33,9 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `DATABASE_URL` | 本地 `multica` 数据库 | PostgreSQL 连接地址 |
| `DATABASE_MAX_CONNS` | `25` | 单个 API 进程的最大数据库连接数 |
| `DATABASE_MIN_CONNS` | `5` | 单个 API 进程保留的最小连接数 |
+| `DATABASE_REPLICA_URL` | 空 | 可选的 PostgreSQL 只读从库连接地址;新连接会强制校验只读状态,业务仍需在代码中显式选择最终一致读取 |
+| `DATABASE_REPLICA_MAX_CONNS` | `10` | 单个 API 进程的最大从库连接数 |
+| `DATABASE_REPLICA_MIN_CONNS` | `0` | 单个 API 进程保留的最小从库连接数 |
| `MULTICA_DATABASE_STARTUP_TIMEOUT` | `3m` | 容器启动过程中,migration 与 API 共享的暂时性数据库故障重试时长;设为 `0` 时每个阶段只尝试一次 |
| `MULTICA_DATABASE_CONNECT_TIMEOUT` | `5s` | 启动期间单次数据库连接的兜底超时;pgx 原生 `connect_timeout`、`PGCONNECT_TIMEOUT` 或 service 配置优先 |
| `PORT` | `8080` | API 监听端口 |
@@ -45,6 +48,8 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
在 Kubernetes 中设置 shutdown hold 时,`terminationGracePeriodSeconds` 要大于 hold 与实际退出所需时间之和。
+主库与从库的连接上限彼此独立,需要按全部 API 进程的连接数总和预留 PostgreSQL 集群连接额度。从库连接默认五分钟回收一次,以便在提升后重新校验只读状态。从库连接失败时,基础设施会透明回退主库并短暂打开被动熔断器,不会增加后台数据库探测。应用不保证从库数据的最大陈旧时间;请在数据库层监控复制延迟,一致性敏感的读取继续走主库。
+
## 对外地址与浏览器访问
| 变量 | 默认值 | 说明 |
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 5bfe06c579..052fe2efce 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -63,6 +63,9 @@ services:
- backend_uploads:/app/data/uploads
environment:
DATABASE_URL: postgres://${POSTGRES_USER:-multica}:${POSTGRES_PASSWORD:-multica}@postgres:5432/${POSTGRES_DB:-multica}?sslmode=disable
+ DATABASE_REPLICA_URL: ${DATABASE_REPLICA_URL:-}
+ DATABASE_REPLICA_MAX_CONNS: ${DATABASE_REPLICA_MAX_CONNS:-}
+ DATABASE_REPLICA_MIN_CONNS: ${DATABASE_REPLICA_MIN_CONNS:-}
PORT: "8080"
METRICS_ADDR: ${METRICS_ADDR:-}
JWT_SECRET: ${JWT_SECRET:?JWT_SECRET must be set to a strong random value — generate one with 'openssl rand -hex 32'}
diff --git a/scripts/selfhost-config.test.sh b/scripts/selfhost-config.test.sh
index 5c921828b6..2c11ed2ac3 100755
--- a/scripts/selfhost-config.test.sh
+++ b/scripts/selfhost-config.test.sh
@@ -42,6 +42,7 @@ trap 'rm -f "$tmp_env"; rm -rf "$tmp_dir"' EXIT
sed 's/^FRONTEND_PORT=.*/FRONTEND_PORT=3100/' .env.example >"$tmp_env"
printf '\nBACKEND_PORT=9100\[email protected]\n' >>"$tmp_env"
printf 'MULTICA_LLM_API_KEY=llm-key-from-env\nMULTICA_LLM_BASE_URL=http://gateway.example/v1\nMULTICA_LLM_DEFAULT_MODEL=model-from-env\nMULTICA_LLM_MAX_RETRIES=3\n' >>"$tmp_env"
+printf 'DATABASE_REPLICA_URL=postgres://reader:[email protected]:5432/multica?sslmode=require\nDATABASE_REPLICA_MAX_CONNS=12\nDATABASE_REPLICA_MIN_CONNS=1\n' >>"$tmp_env"
config="$(
docker compose \
@@ -58,6 +59,9 @@ require_config "$config" 'MULTICA_APP_URL: http://localhost:3100'
require_config "$config" 'SMTP_FROM_EMAIL: [email protected]'
require_config "$config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: 3m'
require_config "$config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: 5s'
+require_config "$config" 'DATABASE_REPLICA_URL: postgres://reader:[email protected]:5432/multica?sslmode=require'
+require_config "$config" 'DATABASE_REPLICA_MAX_CONNS: "12"'
+require_config "$config" 'DATABASE_REPLICA_MIN_CONNS: "1"'
# The backend environment is an explicit allowlist, so a variable documented in
# .env.example but missing here silently never reaches the container: the
diff --git a/server/cmd/server/dbstats.go b/server/cmd/server/dbstats.go
index 5b5f82107d..fbcb208566 100644
--- a/server/cmd/server/dbstats.go
+++ b/server/cmd/server/dbstats.go
@@ -5,9 +5,11 @@ import (
"log/slog"
"net/url"
"os"
+ "reflect"
"strconv"
"time"
+ "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/dbstartup"
)
@@ -35,6 +37,46 @@ const (
// Both values are overridable via DATABASE_MAX_CONNS / DATABASE_MIN_CONNS.
defaultMaxConns int32 = 25
defaultMinConns int32 = 5
+
+ // The optional replica has its own connection budget. Ten connections allow
+ // a small burst of the first Dashboard aggregation workload without cloning
+ // the primary's 25-connection ceiling. MinConns=0 avoids idle connections
+ // before any business opts into replica reads.
+ defaultReplicaMaxConns int32 = 10
+ defaultReplicaMinConns int32 = 0
+
+ // pgx validates target_session_attrs only when a connection is established.
+ // Five minutes bounds how long a pooled replica connection can survive a
+ // promotion without being revalidated, instead of pgx's one-hour default.
+ defaultReplicaMaxConnLifetime = 5 * time.Minute
+)
+
+type dbPoolSizing struct {
+ maxConnsEnv string
+ minConnsEnv string
+ defaultMaxConns int32
+ defaultMinConns int32
+ defaultMaxConnLifetime time.Duration
+ allowZeroMin bool
+ requireReadOnly bool
+}
+
+var (
+ primaryPoolSizing = dbPoolSizing{
+ maxConnsEnv: "DATABASE_MAX_CONNS",
+ minConnsEnv: "DATABASE_MIN_CONNS",
+ defaultMaxConns: defaultMaxConns,
+ defaultMinConns: defaultMinConns,
+ }
+ replicaPoolSizing = dbPoolSizing{
+ maxConnsEnv: "DATABASE_REPLICA_MAX_CONNS",
+ minConnsEnv: "DATABASE_REPLICA_MIN_CONNS",
+ defaultMaxConns: defaultReplicaMaxConns,
+ defaultMinConns: defaultReplicaMinConns,
+ defaultMaxConnLifetime: defaultReplicaMaxConnLifetime,
+ allowZeroMin: true,
+ requireReadOnly: true,
+ }
)
// newDBPool builds a pgxpool with sane production defaults and env overrides.
@@ -53,34 +95,73 @@ const (
// pgx's own built-in default (max(4, NumCPU)) is intentionally NOT used as a
// fallback — it is the value that caused the prod incident.
func newDBPool(ctx context.Context, dbURL string, connectTimeout time.Duration) (*pgxpool.Pool, error) {
+ return newSizedDBPool(ctx, dbURL, connectTimeout, primaryPoolSizing)
+}
+
+func newReplicaDBPool(ctx context.Context, dbURL string, connectTimeout time.Duration) (*pgxpool.Pool, error) {
+ return newSizedDBPool(ctx, dbURL, connectTimeout, replicaPoolSizing)
+}
+
+func newSizedDBPool(ctx context.Context, dbURL string, connectTimeout time.Duration, sizing dbPoolSizing) (*pgxpool.Pool, error) {
cfg, err := dbstartup.ParsePoolConfig(dbURL, connectTimeout)
if err != nil {
return nil, err
}
+ applyPoolSizing(cfg, dbURL, sizing)
+ return pgxpool.NewWithConfig(ctx, cfg)
+}
+func applyPoolSizing(cfg *pgxpool.Config, dbURL string, sizing dbPoolSizing) {
urlParams := poolParamsFromURL(dbURL)
+ if sizing.requireReadOnly {
+ // Standby validation is stricter than read-only validation, so preserve
+ // an operator's explicit target_session_attrs=standby. Every other value
+ // is replaced with read-only to keep the replica contract fail-closed.
+ if !sameValidateConnect(
+ cfg.ConnConfig.Config.ValidateConnect,
+ pgconn.ValidateConnectTargetSessionAttrsStandby,
+ ) {
+ cfg.ConnConfig.Config.ValidateConnect = pgconn.ValidateConnectTargetSessionAttrsReadOnly
+ }
+ }
+ if sizing.defaultMaxConnLifetime > 0 && !urlParams["pool_max_conn_lifetime"] {
+ cfg.MaxConnLifetime = sizing.defaultMaxConnLifetime
+ }
// Compute the non-env fallback first: honor URL pool_* params if the
// operator set them, otherwise use our code default. This fallback is
// also what an *invalid* env value falls back to — never pgx's built-in
// default of 4/0, which is the value that caused the prod incident.
- maxFallback := defaultMaxConns
+ maxFallback := sizing.defaultMaxConns
if urlParams["pool_max_conns"] {
maxFallback = cfg.MaxConns
}
- cfg.MaxConns = envInt32("DATABASE_MAX_CONNS", maxFallback)
+ cfg.MaxConns = envInt32(sizing.maxConnsEnv, maxFallback)
- minFallback := defaultMinConns
+ minFallback := sizing.defaultMinConns
if urlParams["pool_min_conns"] {
minFallback = cfg.MinConns
}
- cfg.MinConns = envInt32("DATABASE_MIN_CONNS", minFallback)
+ if sizing.allowZeroMin {
+ cfg.MinConns = envNonNegativeInt32(sizing.minConnsEnv, minFallback)
+ } else {
+ cfg.MinConns = envInt32(sizing.minConnsEnv, minFallback)
+ }
if cfg.MinConns > cfg.MaxConns {
cfg.MinConns = cfg.MaxConns
}
+}
- return pgxpool.NewWithConfig(ctx, cfg)
+func sameValidateConnect(got, want pgconn.ValidateConnectFunc) bool {
+ if got == nil || want == nil {
+ return got == nil && want == nil
+ }
+ // pgx exposes its parsed target_session_attrs choice only as this callback.
+ // Comparing the URL would miss PGTARGETSESSIONATTRS and service-file input.
+ // Value.Pointer is not a general unique function identity guarantee; use it
+ // narrowly for pgx's distinct package-level validator functions.
+ return reflect.ValueOf(got).Pointer() == reflect.ValueOf(want).Pointer()
}
// poolParamsFromURL returns the set of pool_* query params present on the
@@ -115,13 +196,28 @@ func envInt32(name string, def int32) int32 {
return int32(v)
}
+func envNonNegativeInt32(name string, def int32) int32 {
+ raw := os.Getenv(name)
+ if raw == "" {
+ return def
+ }
+ v, err := strconv.ParseInt(raw, 10, 32)
+ if err != nil || v < 0 {
+ slog.Warn("invalid env var, using default",
+ "name", name, "value", raw, "default", def, "error", err)
+ return def
+ }
+ return int32(v)
+}
+
// logPoolConfig prints the effective pgxpool configuration once at startup.
// Surfacing this is critical because pgxpool defaults are surprisingly small
// (MaxConns = max(4, NumCPU)) — without seeing the value in the log it's
// easy to mistake pool exhaustion for "the database is slow".
-func logPoolConfig(pool *pgxpool.Pool) {
+func logPoolConfig(role string, pool *pgxpool.Pool) {
cfg := pool.Config()
slog.Info("db pool config",
+ "role", role,
"max_conns", cfg.MaxConns,
"min_conns", cfg.MinConns,
"max_conn_lifetime", cfg.MaxConnLifetime.String(),
@@ -136,7 +232,7 @@ func logPoolConfig(pool *pgxpool.Pool) {
// exhaustion (a request had to wait because no idle conn was available) and
// the smoking gun we're looking for to confirm the slow /tasks/claim
// hypothesis.
-func runDBStatsLogger(ctx context.Context, pool *pgxpool.Pool) {
+func runDBStatsLogger(ctx context.Context, role string, pool *pgxpool.Pool) {
ticker := time.NewTicker(dbStatsInterval)
defer ticker.Stop()
@@ -168,6 +264,7 @@ func runDBStatsLogger(ctx context.Context, pool *pgxpool.Pool) {
}
fields := []any{
+ "role", role,
"max_conns", s.MaxConns(),
"total_conns", s.TotalConns(),
"acquired_conns", s.AcquiredConns(),
diff --git a/server/cmd/server/dbstats_test.go b/server/cmd/server/dbstats_test.go
index 30608180fb..45a10d38bb 100644
--- a/server/cmd/server/dbstats_test.go
+++ b/server/cmd/server/dbstats_test.go
@@ -2,48 +2,42 @@ package main
import (
"testing"
+ "time"
+ "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
-// applyPoolSizing mirrors the env+URL precedence logic in newDBPool but
-// without actually opening a connection, so the resolution rules can be
-// asserted in unit tests.
-func applyPoolSizing(t *testing.T, dbURL string, envMax, envMin string) (max, min int32) {
+// resolvedPoolConfig runs the production pool policy without opening a
+// connection.
+func resolvedPoolConfig(t *testing.T, dbURL, envMax, envMin string, sizing dbPoolSizing) *pgxpool.Config {
t.Helper()
cfg, err := pgxpool.ParseConfig(dbURL)
if err != nil {
t.Fatalf("ParseConfig: %v", err)
}
- urlParams := poolParamsFromURL(dbURL)
-
- maxFallback := defaultMaxConns
- if urlParams["pool_max_conns"] {
- maxFallback = cfg.MaxConns
- }
if envMax != "" {
- t.Setenv("DATABASE_MAX_CONNS", envMax)
- }
- cfg.MaxConns = envInt32("DATABASE_MAX_CONNS", maxFallback)
-
- minFallback := defaultMinConns
- if urlParams["pool_min_conns"] {
- minFallback = cfg.MinConns
+ t.Setenv(sizing.maxConnsEnv, envMax)
}
if envMin != "" {
- t.Setenv("DATABASE_MIN_CONNS", envMin)
+ t.Setenv(sizing.minConnsEnv, envMin)
}
- cfg.MinConns = envInt32("DATABASE_MIN_CONNS", minFallback)
+ applyPoolSizing(cfg, dbURL, sizing)
+ return cfg
+}
- if cfg.MinConns > cfg.MaxConns {
- cfg.MinConns = cfg.MaxConns
- }
+func resolvedPoolSizing(t *testing.T, dbURL, envMax, envMin string, sizing dbPoolSizing) (max, min int32) {
+ cfg := resolvedPoolConfig(t, dbURL, envMax, envMin, sizing)
return cfg.MaxConns, cfg.MinConns
}
+func resolvedPrimaryPoolSizing(t *testing.T, dbURL, envMax, envMin string) (max, min int32) {
+ return resolvedPoolSizing(t, dbURL, envMax, envMin, primaryPoolSizing)
+}
+
func TestPoolSizing_URLParamsHonoredWhenEnvUnset(t *testing.T) {
url := "postgres://u:p@h/db?sslmode=disable&pool_max_conns=40&pool_min_conns=8"
- max, min := applyPoolSizing(t, url, "", "")
+ max, min := resolvedPrimaryPoolSizing(t, url, "", "")
if max != 40 || min != 8 {
t.Fatalf("URL params should win when env unset; got max=%d min=%d", max, min)
}
@@ -51,7 +45,7 @@ func TestPoolSizing_URLParamsHonoredWhenEnvUnset(t *testing.T) {
func TestPoolSizing_EnvOverridesURL(t *testing.T) {
url := "postgres://u:p@h/db?sslmode=disable&pool_max_conns=40&pool_min_conns=8"
- max, min := applyPoolSizing(t, url, "100", "20")
+ max, min := resolvedPrimaryPoolSizing(t, url, "100", "20")
if max != 100 || min != 20 {
t.Fatalf("env should win over URL; got max=%d min=%d", max, min)
}
@@ -61,7 +55,7 @@ func TestPoolSizing_PartialURLParam(t *testing.T) {
// Only pool_max_conns is set in URL — pool_min_conns should fall back to
// the code default, not pgx's built-in default (which would be 0).
url := "postgres://u:p@h/db?sslmode=disable&pool_max_conns=40"
- max, min := applyPoolSizing(t, url, "", "")
+ max, min := resolvedPrimaryPoolSizing(t, url, "", "")
if max != 40 {
t.Fatalf("URL pool_max_conns should be honored; got max=%d", max)
}
@@ -74,7 +68,7 @@ func TestPoolSizing_InvalidEnvFallsBackToCodeDefault(t *testing.T) {
// Invalid env value with no URL pool param → code default, NOT pgx's
// built-in 4. This is the regression that was fixed; pinning it here
// so we don't silently fall back to the bad value again.
- max, min := applyPoolSizing(t, "postgres://u:p@h/db?sslmode=disable", "not-a-number", "")
+ max, min := resolvedPrimaryPoolSizing(t, "postgres://u:p@h/db?sslmode=disable", "not-a-number", "")
if max != defaultMaxConns {
t.Fatalf("invalid env should fall back to code default; got max=%d, want %d", max, defaultMaxConns)
}
@@ -88,8 +82,114 @@ func TestPoolSizing_InvalidEnvFallsBackToURLParam(t *testing.T) {
// default. This is what makes the precedence chain end at "URL or code
// default" rather than at "pgx default" on misconfiguration.
url := "postgres://u:p@h/db?sslmode=disable&pool_max_conns=40"
- max, _ := applyPoolSizing(t, url, "not-a-number", "")
+ max, _ := resolvedPrimaryPoolSizing(t, url, "not-a-number", "")
if max != 40 {
t.Fatalf("invalid env should fall back to URL param; got max=%d, want 40", max)
}
}
+
+func TestReplicaPoolSizingHasIndependentSafeDefaults(t *testing.T) {
+ max, min := resolvedPoolSizing(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable",
+ "",
+ "",
+ replicaPoolSizing,
+ )
+ if max != defaultReplicaMaxConns || min != 0 {
+ t.Fatalf("replica defaults = %d/%d, want %d/0", max, min, defaultReplicaMaxConns)
+ }
+}
+
+func TestReplicaPoolSizingAllowsExplicitZeroMinimum(t *testing.T) {
+ max, min := resolvedPoolSizing(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable&pool_max_conns=12&pool_min_conns=3",
+ "8",
+ "0",
+ replicaPoolSizing,
+ )
+ if max != 8 || min != 0 {
+ t.Fatalf("replica sizing = %d/%d, want 8/0", max, min)
+ }
+}
+
+func TestReplicaPoolEnforcesReadOnlyAndShortConnectionLifetime(t *testing.T) {
+ cfg := resolvedPoolConfig(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable",
+ "",
+ "",
+ replicaPoolSizing,
+ )
+ if !sameValidateConnect(
+ cfg.ConnConfig.Config.ValidateConnect,
+ pgconn.ValidateConnectTargetSessionAttrsReadOnly,
+ ) {
+ t.Fatal("replica ValidateConnect does not enforce target_session_attrs=read-only")
+ }
+ if cfg.MaxConnLifetime != defaultReplicaMaxConnLifetime {
+ t.Fatalf("replica max lifetime = %s, want %s", cfg.MaxConnLifetime, defaultReplicaMaxConnLifetime)
+ }
+}
+
+func TestReplicaPoolPreservesStricterStandbyValidation(t *testing.T) {
+ cfg := resolvedPoolConfig(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable&target_session_attrs=standby",
+ "",
+ "",
+ replicaPoolSizing,
+ )
+ if !sameValidateConnect(
+ cfg.ConnConfig.Config.ValidateConnect,
+ pgconn.ValidateConnectTargetSessionAttrsStandby,
+ ) {
+ t.Fatal("replica ValidateConnect replaced target_session_attrs=standby")
+ }
+}
+
+func TestReplicaPoolOverridesWritableValidation(t *testing.T) {
+ cfg := resolvedPoolConfig(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable&target_session_attrs=read-write",
+ "",
+ "",
+ replicaPoolSizing,
+ )
+ if !sameValidateConnect(
+ cfg.ConnConfig.Config.ValidateConnect,
+ pgconn.ValidateConnectTargetSessionAttrsReadOnly,
+ ) {
+ t.Fatal("replica ValidateConnect accepted target_session_attrs=read-write")
+ }
+}
+
+func TestReplicaPoolOverridesPreferStandbyValidation(t *testing.T) {
+ cfg := resolvedPoolConfig(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable&target_session_attrs=prefer-standby",
+ "",
+ "",
+ replicaPoolSizing,
+ )
+ if !sameValidateConnect(
+ cfg.ConnConfig.Config.ValidateConnect,
+ pgconn.ValidateConnectTargetSessionAttrsReadOnly,
+ ) {
+ t.Fatal("replica ValidateConnect accepted target_session_attrs=prefer-standby")
+ }
+}
+
+func TestReplicaPoolHonorsExplicitConnectionLifetime(t *testing.T) {
+ cfg := resolvedPoolConfig(
+ t,
+ "postgres://u:p@replica/db?sslmode=disable&pool_max_conn_lifetime=11m",
+ "",
+ "",
+ replicaPoolSizing,
+ )
+ if cfg.MaxConnLifetime != 11*time.Minute {
+ t.Fatalf("replica max lifetime = %s, want 11m", cfg.MaxConnLifetime)
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 524edce0ba..b6168fa281 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -13,9 +13,11 @@ import (
"syscall"
"time"
+ "github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/daemonws"
+ "github.com/multica-ai/multica/server/internal/dbreader"
"github.com/multica-ai/multica/server/internal/dbstartup"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
@@ -365,7 +367,24 @@ func main() {
}
stopStartup()
slog.Info("connected to database")
- logPoolConfig(pool)
+ logPoolConfig("primary", pool)
+
+ // The replica is an optional capacity optimization, never a startup
+ // dependency. Invalid configuration preserves primary-only behavior. New
+ // replica connections are validated as read-only by the pool configuration,
+ // while request-driven fallback and a passive circuit breaker handle runtime
+ // failures without background SQL.
+ var replicaPool *pgxpool.Pool
+ if replicaURL := strings.TrimSpace(os.Getenv("DATABASE_REPLICA_URL")); replicaURL != "" {
+ replicaPool, err = newReplicaDBPool(context.Background(), replicaURL, startupSettings.ConnectTimeout)
+ if err != nil {
+ slog.Warn("database replica configuration is invalid; using primary for reads", "error", err)
+ replicaPool = nil
+ } else {
+ defer replicaPool.Close()
+ logPoolConfig("replica", replicaPool)
+ }
+ }
bus := events.New()
hub := realtime.NewHub()
@@ -558,19 +577,22 @@ func main() {
var channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetrics
var channelLeaseMetrics *obsmetrics.ChannelLeaseMetrics
var wecomMetrics *obsmetrics.WecomMetrics
+ var dbRoutingMetrics *obsmetrics.DBRoutingMetrics
if metricsConfig.Enabled() {
metricsRegistry := obsmetrics.NewRegistry(obsmetrics.RegistryOptions{
- Pool: pool,
- Realtime: realtime.M,
- DaemonWS: daemonws.M,
- Version: version,
- Commit: commit,
+ Pool: pool,
+ ReplicaPool: replicaPool,
+ Realtime: realtime.M,
+ DaemonWS: daemonws.M,
+ Version: version,
+ Commit: commit,
})
httpMetrics = metricsRegistry.HTTP
businessMetrics = metricsRegistry.Business
channelMediaMetrics = metricsRegistry.ChannelMedia
channelLeaseMetrics = metricsRegistry.ChannelLease
wecomMetrics = metricsRegistry.Wecom
+ dbRoutingMetrics = metricsRegistry.DBRouting
// Forward inbound daemon WS frames into the per-kind counter so
// dashboards can split heartbeat / unknown / invalid traffic.
if daemonHub != nil {
@@ -598,6 +620,10 @@ func main() {
slog.Error("invalid MULTICA_LLM_MAX_RETRIES", "error", err)
os.Exit(1)
}
+ var readRecorder dbreader.Recorder
+ if dbRoutingMetrics != nil {
+ readRecorder = dbRoutingMetrics
+ }
r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{
HTTPMetrics: httpMetrics,
@@ -613,6 +639,13 @@ func main() {
HeartbeatScheduler: heartbeatScheduler,
LLMMaxRetries: llmMaxRetries,
})
+ var replicaQueries *db.Queries
+ if replicaPool != nil {
+ replicaQueries = db.New(replicaPool)
+ }
+ // Reuse the handler's primary Queries handle so replica routing does not
+ // create a second wrapper around the same primary pool.
+ h.ReadSelector = dbreader.New(h.Queries, replicaQueries, readRecorder)
srv := newMainHTTPServer(":"+port, r)
profilingServer := profiling.NewServer()
@@ -663,7 +696,10 @@ func main() {
if autopilotSvc.QuotaEnabled() {
go runAutopilotQuotaReconciler(autopilotCtx, autopilotSvc)
}
- go runDBStatsLogger(sweepCtx, pool)
+ go runDBStatsLogger(sweepCtx, "primary", pool)
+ if replicaPool != nil {
+ go runDBStatsLogger(sweepCtx, "replica", replicaPool)
+ }
if h.WebhookDeliveryWorker != nil {
go h.WebhookDeliveryWorker.Run(sweepCtx)
}
diff --git a/server/internal/dbreader/selector.go b/server/internal/dbreader/selector.go
new file mode 100644
index 0000000000..6c215af31f
--- /dev/null
+++ b/server/internal/dbreader/selector.go
@@ -0,0 +1,360 @@
+package dbreader
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgconn"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// A two-second cooldown caps failed replica connection attempts at one per API
+// process per interval while restoring replica traffic quickly. One
+// availability failure opens the circuit because it already proves that the
+// replica cannot serve the request. Recovery is driven by one half-open
+// business read, not a background database query.
+const defaultReplicaCircuitCooldown = 2 * time.Second
+
+// Business is opaque so callers cannot create unbounded metric labels. Add a
+// package value for each opted-in business; the value itself is the only
+// registry that needs updating.
+type Business struct {
+ label string
+}
+
+var (
+ BusinessDashboard = Business{label: "dashboard"}
+ businessUnknown = Business{label: "unknown"}
+)
+
+type Consistency string
+
+const (
+ StrongConsistency Consistency = "strong"
+ EventualConsistency Consistency = "eventual"
+)
+
+type Role string
+
+const (
+ RolePrimary Role = "primary"
+ RoleReplica Role = "replica"
+)
+
+type Reason string
+
+const (
+ ReasonStrongConsistency Reason = "strong_consistency"
+ ReasonReplicaDisabled Reason = "replica_disabled"
+ ReasonReplicaSelected Reason = "replica_selected"
+ ReasonCircuitOpen Reason = "circuit_open"
+ ReasonConnectionFailed Reason = "connection_failed"
+ ReasonRecoveryConflict Reason = "recovery_conflict"
+)
+
+// Recorder is implemented by the optional Prometheus metrics sink. The
+// selector stays usable when metrics are disabled by accepting nil.
+type Recorder interface {
+ RecordReadRoute(business, role, reason string)
+}
+
+// Selector keeps primary as the safe default. Existing handlers continue to
+// use their primary *db.Queries directly; an eventual-consistency read must
+// explicitly use Read, which owns replica selection, fallback, and recovery.
+type Selector struct {
+ primary *db.Queries
+ replica *db.Queries
+ recorder Recorder
+ logger *slog.Logger
+ now func() time.Time
+ circuit replicaCircuit
+}
+
+type replicaCircuit struct {
+ mu sync.Mutex
+ generation uint64
+ openUntil time.Time
+ halfOpenInFlight bool
+}
+
+type selection struct {
+ queries *db.Queries
+ role Role
+ reason Reason
+ generation uint64
+ halfOpen bool
+}
+
+type fallbackDecision struct {
+ retry bool
+ openCircuit bool
+ reason Reason
+}
+
+func New(primary, replica *db.Queries, recorder Recorder) *Selector {
+ return newSelector(primary, replica, recorder, slog.Default())
+}
+
+func NewPrimaryOnly(primary *db.Queries) *Selector {
+ return newSelector(primary, nil, nil, slog.Default())
+}
+
+func newSelector(primary, replica *db.Queries, recorder Recorder, logger *slog.Logger) *Selector {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &Selector{
+ primary: primary,
+ replica: replica,
+ recorder: recorder,
+ logger: logger,
+ now: time.Now,
+ }
+}
+
+// Read executes one explicitly idempotent read. Strong-consistency and
+// unconfigured reads use primary. Eventual-consistency reads use replica when
+// its passive circuit permits, then retry once on primary for connection,
+// transport, server-availability, or standby recovery-conflict errors. SQL,
+// permission, and caller-cancellation errors are returned unchanged.
+func Read[T any](
+ ctx context.Context,
+ selector *Selector,
+ business Business,
+ consistency Consistency,
+ query func(context.Context, *db.Queries) (T, error),
+) (T, error) {
+ selected := selector.selectForRead(business, consistency)
+ if selected.halfOpen {
+ // Normal returns finish the trial through succeed, fail, or
+ // abandonTrial. This defer is the panic-safe liveness backstop.
+ defer selector.circuit.releaseTrial(selected.generation)
+ }
+ result, err := query(ctx, selected.queries)
+ if selected.role != RoleReplica {
+ return result, err
+ }
+ if err == nil {
+ selector.replicaSucceeded(selected)
+ return result, nil
+ }
+
+ decision := fallbackFor(ctx, err)
+ if !decision.retry {
+ selector.replicaDidNotProveAvailability(selected, err)
+ return result, err
+ }
+ if decision.openCircuit {
+ selector.replicaFailed(selected, decision.reason, err)
+ } else {
+ // A structured server response proves the connection is usable. A
+ // recovery conflict affects only this query and must not eject the
+ // replica globally.
+ selector.replicaSucceeded(selected)
+ }
+
+ selector.recordRoute(business, RolePrimary, decision.reason)
+ return query(ctx, selector.primary)
+}
+
+func (s *Selector) selectForRead(business Business, consistency Consistency) selection {
+ if consistency != EventualConsistency {
+ return s.route(business, s.primary, RolePrimary, ReasonStrongConsistency, 0, false)
+ }
+ if s.replica == nil {
+ return s.route(business, s.primary, RolePrimary, ReasonReplicaDisabled, 0, false)
+ }
+
+ allowed, generation, halfOpen := s.circuit.allow(s.now())
+ if !allowed {
+ return s.route(business, s.primary, RolePrimary, ReasonCircuitOpen, generation, false)
+ }
+ return s.route(business, s.replica, RoleReplica, ReasonReplicaSelected, generation, halfOpen)
+}
+
+func (s *Selector) route(
+ business Business,
+ queries *db.Queries,
+ role Role,
+ reason Reason,
+ generation uint64,
+ halfOpen bool,
+) selection {
+ s.recordRoute(business, role, reason)
+ return selection{
+ queries: queries,
+ role: role,
+ reason: reason,
+ generation: generation,
+ halfOpen: halfOpen,
+ }
+}
+
+func (s *Selector) recordRoute(business Business, role Role, reason Reason) {
+ if s.recorder != nil {
+ s.recorder.RecordReadRoute(business.metricLabel(), string(role), string(reason))
+ }
+}
+
+func (b Business) metricLabel() string {
+ if b.label == "" {
+ return businessUnknown.label
+ }
+ return b.label
+}
+
+func fallbackFor(ctx context.Context, err error) fallbackDecision {
+ if err == nil || ctx.Err() != nil {
+ return fallbackDecision{}
+ }
+
+ // ConnectError covers the failures that happen before PostgreSQL can emit
+ // a SQLSTATE: refused connections, DNS, authentication, and TLS errors.
+ // The query cannot have executed, so retrying an idempotent read is safe.
+ var connectErr *pgconn.ConnectError
+ if errors.As(err, &connectErr) {
+ return fallbackDecision{retry: true, openCircuit: true, reason: ReasonConnectionFailed}
+ }
+ // A bare context error belongs to a narrower operation inside the callback,
+ // not the replica connection. ConnectError is checked first because pgx may
+ // wrap its own connection timeout with context.DeadlineExceeded.
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return fallbackDecision{}
+ }
+ var netErr net.Error
+ if errors.As(err, &netErr) {
+ return fallbackDecision{retry: true, openCircuit: true, reason: ReasonConnectionFailed}
+ }
+ if pgconn.SafeToRetry(err) {
+ return fallbackDecision{retry: true, openCircuit: true, reason: ReasonConnectionFailed}
+ }
+
+ var pgErr *pgconn.PgError
+ if !errors.As(err, &pgErr) {
+ return fallbackDecision{}
+ }
+ if strings.HasPrefix(pgErr.Code, "08") {
+ return fallbackDecision{retry: true, openCircuit: true, reason: ReasonConnectionFailed}
+ }
+ switch pgErr.Code {
+ case "40001":
+ return fallbackDecision{retry: true, reason: ReasonRecoveryConflict}
+ case "57P01", "57P02", "57P03":
+ return fallbackDecision{retry: true, openCircuit: true, reason: ReasonConnectionFailed}
+ default:
+ return fallbackDecision{}
+ }
+}
+
+func shouldFallback(ctx context.Context, err error) bool {
+ return fallbackFor(ctx, err).retry
+}
+
+func (s *Selector) replicaSucceeded(selected selection) {
+ if s.circuit.succeed(selected.generation, selected.halfOpen) {
+ s.logger.Info("database replica circuit closed after successful read")
+ }
+}
+
+func (s *Selector) replicaFailed(selected selection, reason Reason, err error) {
+ if s.circuit.fail(
+ selected.generation,
+ s.now(),
+ defaultReplicaCircuitCooldown,
+ ) {
+ s.logger.Warn("database replica circuit opened; using primary",
+ "reason", reason,
+ "cooldown", defaultReplicaCircuitCooldown.String(),
+ "error", err,
+ )
+ }
+}
+
+func (s *Selector) replicaDidNotProveAvailability(selected selection, err error) {
+ if !selected.halfOpen {
+ return
+ }
+ if isPostgresResponse(err) {
+ s.replicaSucceeded(selected)
+ return
+ }
+ s.circuit.abandonTrial(selected.generation, s.now(), defaultReplicaCircuitCooldown)
+}
+
+func isPostgresResponse(err error) bool {
+ var pgErr *pgconn.PgError
+ return errors.As(err, &pgErr)
+}
+
+func (c *replicaCircuit) allow(now time.Time) (allowed bool, generation uint64, halfOpen bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if c.openUntil.IsZero() {
+ return true, c.generation, false
+ }
+ if now.Before(c.openUntil) || c.halfOpenInFlight {
+ return false, c.generation, false
+ }
+ c.halfOpenInFlight = true
+ return true, c.generation, true
+}
+
+func (c *replicaCircuit) succeed(generation uint64, halfOpen bool) (closed bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if generation != c.generation {
+ return false
+ }
+ if c.openUntil.IsZero() {
+ return false
+ }
+ if !halfOpen || !c.halfOpenInFlight {
+ return false
+ }
+ c.generation++
+ c.openUntil = time.Time{}
+ c.halfOpenInFlight = false
+ return true
+}
+
+func (c *replicaCircuit) fail(generation uint64, now time.Time, cooldown time.Duration) (opened bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if generation != c.generation {
+ return false
+ }
+ wasOpen := !c.openUntil.IsZero()
+ c.generation++
+ c.openUntil = now.Add(cooldown)
+ c.halfOpenInFlight = false
+ return !wasOpen
+}
+
+func (c *replicaCircuit) releaseTrial(generation uint64) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if generation == c.generation {
+ c.halfOpenInFlight = false
+ }
+}
+
+func (c *replicaCircuit) abandonTrial(generation uint64, now time.Time, cooldown time.Duration) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if generation != c.generation || !c.halfOpenInFlight {
+ return
+ }
+ c.generation++
+ c.openUntil = now.Add(cooldown)
+ c.halfOpenInFlight = false
+}
diff --git a/server/internal/dbreader/selector_test.go b/server/internal/dbreader/selector_test.go
new file mode 100644
index 0000000000..498fd2c308
--- /dev/null
+++ b/server/internal/dbreader/selector_test.go
@@ -0,0 +1,350 @@
+package dbreader
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+var testBusiness = BusinessDashboard
+
+type recorderStub struct {
+ routes []selection
+ labels []string
+}
+
+func (r *recorderStub) RecordReadRoute(business, role, reason string) {
+ r.routes = append(r.routes, selection{role: Role(role), reason: Reason(reason)})
+ r.labels = append(r.labels, business)
+}
+
+func testSelector() (*Selector, *db.Queries, *db.Queries, *recorderStub) {
+ primary := &db.Queries{}
+ replica := &db.Queries{}
+ recorder := &recorderStub{}
+ selector := newSelector(
+ primary,
+ replica,
+ recorder,
+ slog.New(slog.NewTextHandler(io.Discard, nil)),
+ )
+ return selector, primary, replica, recorder
+}
+
+func TestNewKeepsProvidedQueryHandles(t *testing.T) {
+ primary := &db.Queries{}
+ replica := &db.Queries{}
+ selector := New(primary, replica, nil)
+
+ if selector.primary != primary || selector.replica != replica {
+ t.Fatal("New replaced the provided query handles")
+ }
+}
+
+func TestPrimaryOnlySelectorPreservesExistingRouting(t *testing.T) {
+ primary := &db.Queries{}
+ selector := NewPrimaryOnly(primary)
+
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (*db.Queries, error) {
+ return queries, nil
+ })
+ if err != nil || got != primary {
+ t.Fatalf("Read = %#v, %v; want primary", got, err)
+ }
+}
+
+func TestStrongConsistencyAlwaysUsesPrimary(t *testing.T) {
+ selector, primary, _, _ := testSelector()
+
+ got, err := Read(context.Background(), selector, testBusiness, StrongConsistency,
+ func(_ context.Context, queries *db.Queries) (*db.Queries, error) {
+ return queries, nil
+ })
+ if err != nil || got != primary {
+ t.Fatalf("Read = %#v, %v; want primary", got, err)
+ }
+}
+
+func TestEventualConsistencyUsesConfiguredReplica(t *testing.T) {
+ selector, _, replica, recorder := testSelector()
+
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (*db.Queries, error) {
+ return queries, nil
+ })
+ if err != nil || got != replica {
+ t.Fatalf("Read = %#v, %v; want replica", got, err)
+ }
+ if len(recorder.routes) != 1 || recorder.routes[0].role != RoleReplica {
+ t.Fatalf("routes = %#v, want one replica route", recorder.routes)
+ }
+}
+
+func TestUnknownBusinessUsesBoundedMetricLabel(t *testing.T) {
+ selector, _, _, recorder := testSelector()
+
+ _, err := Read(context.Background(), selector, Business{}, EventualConsistency,
+ func(_ context.Context, _ *db.Queries) (string, error) {
+ return "replica result", nil
+ })
+ if err != nil {
+ t.Fatalf("Read: %v", err)
+ }
+ if len(recorder.labels) != 1 || recorder.labels[0] != businessUnknown.label {
+ t.Fatalf("business labels = %#v, want bounded unknown label", recorder.labels)
+ }
+}
+
+func TestReadFallsBackOnceForServerConnectionError(t *testing.T) {
+ selector, primary, replica, recorder := testSelector()
+ var calls []*db.Queries
+
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (string, error) {
+ calls = append(calls, queries)
+ if queries == replica {
+ return "", &pgconn.PgError{Code: "08006", Message: "connection failure"}
+ }
+ return "primary result", nil
+ })
+ if err != nil || got != "primary result" {
+ t.Fatalf("Read = %q, %v; want primary result", got, err)
+ }
+ if len(calls) != 2 || calls[0] != replica || calls[1] != primary {
+ t.Fatalf("calls = %#v, want replica then primary", calls)
+ }
+ if len(recorder.routes) != 2 || recorder.routes[1].role != RolePrimary || recorder.routes[1].reason != ReasonConnectionFailed {
+ t.Fatalf("routes = %#v, want replica then connection-failed primary", recorder.routes)
+ }
+}
+
+func TestConnectErrorFallsBackToPrimary(t *testing.T) {
+ pool, err := pgxpool.New(context.Background(), "postgres://multica:[email protected]:1/multica?sslmode=disable&connect_timeout=1")
+ if err != nil {
+ t.Fatalf("create unreachable pool: %v", err)
+ }
+ defer pool.Close()
+ connectErr := pool.Ping(context.Background())
+ if connectErr == nil {
+ t.Fatal("unreachable pool unexpectedly connected")
+ }
+ var typedConnectErr *pgconn.ConnectError
+ if !errors.As(connectErr, &typedConnectErr) {
+ t.Fatalf("Ping error = %T, want *pgconn.ConnectError", connectErr)
+ }
+ if !shouldFallback(context.Background(), connectErr) {
+ t.Fatalf("shouldFallback(%T) = false, want true", connectErr)
+ }
+
+ selector, primary, replica, _ := testSelector()
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (string, error) {
+ if queries == replica {
+ return "", connectErr
+ }
+ if queries != primary {
+ t.Fatalf("unexpected queries handle: %#v", queries)
+ }
+ return "primary result", nil
+ })
+ if err != nil || got != "primary result" {
+ t.Fatalf("Read = %q, %v; want primary result", got, err)
+ }
+}
+
+func TestCircuitSkipsReplicaThenClosesAfterHalfOpenSuccess(t *testing.T) {
+ selector, primary, replica, recorder := testSelector()
+ now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC)
+ selector.now = func() time.Time { return now }
+ replicaFailures := 1
+ var calls []*db.Queries
+ query := func(_ context.Context, queries *db.Queries) (string, error) {
+ calls = append(calls, queries)
+ if queries == replica && replicaFailures > 0 {
+ replicaFailures--
+ return "", &pgconn.PgError{Code: "08006", Message: "connection failure"}
+ }
+ if queries == replica {
+ return "replica result", nil
+ }
+ return "primary result", nil
+ }
+
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency, query)
+ if err != nil || got != "primary result" {
+ t.Fatalf("failed replica read = %q, %v", got, err)
+ }
+ calls = nil
+ got, err = Read(context.Background(), selector, testBusiness, EventualConsistency, query)
+ if err != nil || got != "primary result" || len(calls) != 1 || calls[0] != primary {
+ t.Fatalf("open-circuit read = %q, %v, calls=%#v; want direct primary", got, err, calls)
+ }
+
+ now = now.Add(defaultReplicaCircuitCooldown)
+ calls = nil
+ got, err = Read(context.Background(), selector, testBusiness, EventualConsistency, query)
+ if err != nil || got != "replica result" || len(calls) != 1 || calls[0] != replica {
+ t.Fatalf("half-open read = %q, %v, calls=%#v; want replica", got, err, calls)
+ }
+ calls = nil
+ got, err = Read(context.Background(), selector, testBusiness, EventualConsistency, query)
+ if err != nil || got != "replica result" || len(calls) != 1 || calls[0] != replica {
+ t.Fatalf("closed-circuit read = %q, %v, calls=%#v; want replica", got, err, calls)
+ }
+
+ foundCircuitRoute := false
+ for _, route := range recorder.routes {
+ if route.role == RolePrimary && route.reason == ReasonCircuitOpen {
+ foundCircuitRoute = true
+ }
+ }
+ if !foundCircuitRoute {
+ t.Fatalf("routes = %#v, want circuit-open primary route", recorder.routes)
+ }
+}
+
+func TestCircuitAllowsOnlyOneHalfOpenTrial(t *testing.T) {
+ var circuit replicaCircuit
+ now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC)
+ allowed, generation, halfOpen := circuit.allow(now)
+ if !allowed || halfOpen {
+ t.Fatalf("initial allow = %v, halfOpen=%v; want normal replica read", allowed, halfOpen)
+ }
+ if !circuit.fail(generation, now, defaultReplicaCircuitCooldown) {
+ t.Fatal("first availability failure did not open circuit")
+ }
+ if allowed, _, _ := circuit.allow(now); allowed {
+ t.Fatal("open circuit allowed replica before cooldown")
+ }
+
+ now = now.Add(defaultReplicaCircuitCooldown)
+ allowed, _, halfOpen = circuit.allow(now)
+ if !allowed || !halfOpen {
+ t.Fatalf("first post-cooldown allow = %v, halfOpen=%v; want one trial", allowed, halfOpen)
+ }
+ if allowed, _, _ := circuit.allow(now); allowed {
+ t.Fatal("circuit allowed a second concurrent half-open trial")
+ }
+}
+
+func TestPanicReleasesHalfOpenTrial(t *testing.T) {
+ selector, _, replica, _ := testSelector()
+ now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC)
+ selector.now = func() time.Time { return now }
+
+ _, err := Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (string, error) {
+ if queries == replica {
+ return "", &pgconn.PgError{Code: "08006", Message: "connection failure"}
+ }
+ return "primary result", nil
+ })
+ if err != nil {
+ t.Fatalf("open circuit: %v", err)
+ }
+ now = now.Add(defaultReplicaCircuitCooldown)
+
+ func() {
+ defer func() {
+ if recovered := recover(); recovered != "boom" {
+ t.Fatalf("recovered = %#v, want boom", recovered)
+ }
+ }()
+ _, _ = Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (string, error) {
+ if queries != replica {
+ t.Fatalf("half-open trial used %#v, want replica", queries)
+ }
+ panic("boom")
+ })
+ }()
+
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency,
+ func(_ context.Context, queries *db.Queries) (*db.Queries, error) {
+ return queries, nil
+ })
+ if err != nil || got != replica {
+ t.Fatalf("read after panic = %#v, %v; want a new replica trial", got, err)
+ }
+}
+
+func TestRecoveryConflictFallsBackWithoutOpeningCircuit(t *testing.T) {
+ selector, primary, replica, _ := testSelector()
+ replicaCalls := 0
+ query := func(_ context.Context, queries *db.Queries) (string, error) {
+ if queries == replica {
+ replicaCalls++
+ if replicaCalls == 1 {
+ return "", &pgconn.PgError{Code: "40001", Message: "conflict with recovery"}
+ }
+ return "replica result", nil
+ }
+ if queries != primary {
+ t.Fatalf("unexpected queries handle: %#v", queries)
+ }
+ return "primary result", nil
+ }
+
+ got, err := Read(context.Background(), selector, testBusiness, EventualConsistency, query)
+ if err != nil || got != "primary result" {
+ t.Fatalf("conflicted read = %q, %v; want primary result", got, err)
+ }
+ got, err = Read(context.Background(), selector, testBusiness, EventualConsistency, query)
+ if err != nil || got != "replica result" || replicaCalls != 2 {
+ t.Fatalf("next read = %q, %v, replicaCalls=%d; want replica", got, err, replicaCalls)
+ }
+}
+
+func TestReadDoesNotHideApplicationOrCancellationErrors(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ ctx func() (context.Context, context.CancelFunc)
+ err error
+ }{
+ {
+ name: "application error",
+ ctx: func() (context.Context, context.CancelFunc) {
+ return context.WithCancel(context.Background())
+ },
+ err: &pgconn.PgError{Code: "42703", Message: "undefined column"},
+ },
+ {
+ name: "caller cancellation",
+ ctx: func() (context.Context, context.CancelFunc) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ return ctx, func() {}
+ },
+ err: context.Canceled,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ selector, _, _, recorder := testSelector()
+ ctx, cancel := tt.ctx()
+ defer cancel()
+ calls := 0
+ _, err := Read(ctx, selector, testBusiness, EventualConsistency,
+ func(context.Context, *db.Queries) (string, error) {
+ calls++
+ return "", tt.err
+ })
+ if !errors.Is(err, tt.err) || calls != 1 || len(recorder.routes) != 1 {
+ t.Fatalf("err=%v calls=%d routes=%#v", err, calls, recorder.routes)
+ }
+ })
+ }
+}
+
+func TestBareContextDeadlineDoesNotFallback(t *testing.T) {
+ if shouldFallback(context.Background(), context.DeadlineExceeded) {
+ t.Fatal("bare operation deadline should not fall back")
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 7772cfbc47..56ff747495 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -22,6 +22,7 @@ import (
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/cloudruntime"
"github.com/multica-ai/multica/server/internal/daemonws"
+ "github.com/multica-ai/multica/server/internal/dbreader"
"github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
@@ -181,6 +182,7 @@ type RuntimeGoneNotifier interface {
type Handler struct {
Queries *db.Queries
+ ReadSelector *dbreader.Selector
DB dbExecutor
TxStarter txStarter
Hub *realtime.Hub
@@ -455,6 +457,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
taskSvc.QuickActions = llmClient
h := &Handler{
Queries: queries,
+ ReadSelector: dbreader.NewPrimaryOnly(queries),
DB: executor,
TxStarter: txStarter,
Hub: hub,
diff --git a/server/internal/metrics/db.go b/server/internal/metrics/db.go
index 8a84588e2b..56f6983190 100644
--- a/server/internal/metrics/db.go
+++ b/server/internal/metrics/db.go
@@ -6,7 +6,7 @@ import (
)
type DBCollector struct {
- pool *pgxpool.Pool
+ pools []namedDBPool
acquiredConns *prometheus.Desc
idleConns *prometheus.Desc
@@ -23,28 +23,40 @@ type DBCollector struct {
maxLifetimeDestroyCnt *prometheus.Desc
}
-func NewDBCollector(pool *pgxpool.Pool) *DBCollector {
+type namedDBPool struct {
+ role string
+ pool *pgxpool.Pool
+}
+
+func NewDBCollector(primary, replica *pgxpool.Pool) *DBCollector {
+ pools := make([]namedDBPool, 0, 2)
+ if primary != nil {
+ pools = append(pools, namedDBPool{role: "primary", pool: primary})
+ }
+ if replica != nil {
+ pools = append(pools, namedDBPool{role: "replica", pool: replica})
+ }
return &DBCollector{
- pool: pool,
+ pools: pools,
- acquiredConns: newDBDesc("acquired_conns", "Currently acquired PostgreSQL connections."),
- idleConns: newDBDesc("idle_conns", "Currently idle PostgreSQL connections."),
- maxConns: newDBDesc("max_conns", "Maximum PostgreSQL connections allowed by the pool."),
- totalConns: newDBDesc("total_conns", "Total PostgreSQL connections currently in the pool."),
- constructingConns: newDBDesc("constructing_conns", "PostgreSQL connections currently being established."),
- acquireCount: newDBDesc("acquire_count", "Total successful PostgreSQL connection acquires."),
- acquireDuration: newDBDesc("acquire_duration_seconds_total", "Total time spent acquiring PostgreSQL connections."),
- emptyAcquireCount: newDBDesc("empty_acquire_count", "Total acquires that waited because the PostgreSQL pool was empty."),
- emptyAcquireWaitTime: newDBDesc("empty_acquire_wait_seconds_total", "Total time spent waiting for PostgreSQL connections when the pool was empty."),
- canceledAcquireCount: newDBDesc("canceled_acquire_count", "Total canceled PostgreSQL connection acquires."),
- newConnsCount: newDBDesc("new_conns_count", "Total PostgreSQL connections created by the pool."),
- maxIdleDestroyCount: newDBDesc("max_idle_destroy_count", "Total PostgreSQL connections destroyed due to idle limits."),
- maxLifetimeDestroyCnt: newDBDesc("max_lifetime_destroy_count", "Total PostgreSQL connections destroyed due to max lifetime."),
+ acquiredConns: newDBDesc("acquired_conns", "Number of acquired connections in each PostgreSQL pool."),
+ idleConns: newDBDesc("idle_conns", "Number of idle connections in each PostgreSQL pool."),
+ maxConns: newDBDesc("max_conns", "Maximum connections configured for each PostgreSQL pool."),
+ totalConns: newDBDesc("total_conns", "Number of current connections in each PostgreSQL pool."),
+ constructingConns: newDBDesc("constructing_conns", "Number of connections being established in each PostgreSQL pool."),
+ acquireCount: newDBDesc("acquire_count", "Total successful connection acquisitions from each PostgreSQL pool."),
+ acquireDuration: newDBDesc("acquire_duration_seconds_total", "Total time spent acquiring connections from each PostgreSQL pool."),
+ emptyAcquireCount: newDBDesc("empty_acquire_count", "Total acquisitions that waited for an available connection in each PostgreSQL pool."),
+ emptyAcquireWaitTime: newDBDesc("empty_acquire_wait_seconds_total", "Total time spent waiting for an available connection in each PostgreSQL pool."),
+ canceledAcquireCount: newDBDesc("canceled_acquire_count", "Total canceled connection acquisitions from each PostgreSQL pool."),
+ newConnsCount: newDBDesc("new_conns_count", "Total connections created in each PostgreSQL pool."),
+ maxIdleDestroyCount: newDBDesc("max_idle_destroy_count", "Total connections destroyed by each PostgreSQL pool after exceeding the idle limit."),
+ maxLifetimeDestroyCnt: newDBDesc("max_lifetime_destroy_count", "Total connections destroyed by each PostgreSQL pool after exceeding the maximum lifetime."),
}
}
func newDBDesc(name, help string) *prometheus.Desc {
- return prometheus.NewDesc("multica_db_pool_"+name, help, nil, nil)
+ return prometheus.NewDesc("multica_db_pool_"+name, help, []string{"role"}, nil)
}
func (c *DBCollector) Describe(ch chan<- *prometheus.Desc) {
@@ -68,21 +80,23 @@ func (c *DBCollector) Describe(ch chan<- *prometheus.Desc) {
}
func (c *DBCollector) Collect(ch chan<- prometheus.Metric) {
- if c.pool == nil {
- return
+ for _, namedPool := range c.pools {
+ collectDBPool(ch, namedPool.role, namedPool.pool.Stat(), c)
}
- stat := c.pool.Stat()
- ch <- prometheus.MustNewConstMetric(c.acquiredConns, prometheus.GaugeValue, float64(stat.AcquiredConns()))
- ch <- prometheus.MustNewConstMetric(c.idleConns, prometheus.GaugeValue, float64(stat.IdleConns()))
- ch <- prometheus.MustNewConstMetric(c.maxConns, prometheus.GaugeValue, float64(stat.MaxConns()))
- ch <- prometheus.MustNewConstMetric(c.totalConns, prometheus.GaugeValue, float64(stat.TotalConns()))
- ch <- prometheus.MustNewConstMetric(c.constructingConns, prometheus.GaugeValue, float64(stat.ConstructingConns()))
- ch <- prometheus.MustNewConstMetric(c.acquireCount, prometheus.CounterValue, float64(stat.AcquireCount()))
- ch <- prometheus.MustNewConstMetric(c.acquireDuration, prometheus.CounterValue, stat.AcquireDuration().Seconds())
- ch <- prometheus.MustNewConstMetric(c.emptyAcquireCount, prometheus.CounterValue, float64(stat.EmptyAcquireCount()))
- ch <- prometheus.MustNewConstMetric(c.emptyAcquireWaitTime, prometheus.CounterValue, stat.EmptyAcquireWaitTime().Seconds())
- ch <- prometheus.MustNewConstMetric(c.canceledAcquireCount, prometheus.CounterValue, float64(stat.CanceledAcquireCount()))
- ch <- prometheus.MustNewConstMetric(c.newConnsCount, prometheus.CounterValue, float64(stat.NewConnsCount()))
- ch <- prometheus.MustNewConstMetric(c.maxIdleDestroyCount, prometheus.CounterValue, float64(stat.MaxIdleDestroyCount()))
- ch <- prometheus.MustNewConstMetric(c.maxLifetimeDestroyCnt, prometheus.CounterValue, float64(stat.MaxLifetimeDestroyCount()))
+}
+
+func collectDBPool(ch chan<- prometheus.Metric, role string, stat *pgxpool.Stat, c *DBCollector) {
+ ch <- prometheus.MustNewConstMetric(c.acquiredConns, prometheus.GaugeValue, float64(stat.AcquiredConns()), role)
+ ch <- prometheus.MustNewConstMetric(c.idleConns, prometheus.GaugeValue, float64(stat.IdleConns()), role)
+ ch <- prometheus.MustNewConstMetric(c.maxConns, prometheus.GaugeValue, float64(stat.MaxConns()), role)
+ ch <- prometheus.MustNewConstMetric(c.totalConns, prometheus.GaugeValue, float64(stat.TotalConns()), role)
+ ch <- prometheus.MustNewConstMetric(c.constructingConns, prometheus.GaugeValue, float64(stat.ConstructingConns()), role)
+ ch <- prometheus.MustNewConstMetric(c.acquireCount, prometheus.CounterValue, float64(stat.AcquireCount()), role)
+ ch <- prometheus.MustNewConstMetric(c.acquireDuration, prometheus.CounterValue, stat.AcquireDuration().Seconds(), role)
+ ch <- prometheus.MustNewConstMetric(c.emptyAcquireCount, prometheus.CounterValue, float64(stat.EmptyAcquireCount()), role)
+ ch <- prometheus.MustNewConstMetric(c.emptyAcquireWaitTime, prometheus.CounterValue, stat.EmptyAcquireWaitTime().Seconds(), role)
+ ch <- prometheus.MustNewConstMetric(c.canceledAcquireCount, prometheus.CounterValue, float64(stat.CanceledAcquireCount()), role)
+ ch <- prometheus.MustNewConstMetric(c.newConnsCount, prometheus.CounterValue, float64(stat.NewConnsCount()), role)
+ ch <- prometheus.MustNewConstMetric(c.maxIdleDestroyCount, prometheus.CounterValue, float64(stat.MaxIdleDestroyCount()), role)
+ ch <- prometheus.MustNewConstMetric(c.maxLifetimeDestroyCnt, prometheus.CounterValue, float64(stat.MaxLifetimeDestroyCount()), role)
}
diff --git a/server/internal/metrics/db_routing.go b/server/internal/metrics/db_routing.go
new file mode 100644
index 0000000000..790a61dd5a
--- /dev/null
+++ b/server/internal/metrics/db_routing.go
@@ -0,0 +1,30 @@
+package metrics
+
+import "github.com/prometheus/client_golang/prometheus"
+
+type DBRoutingMetrics struct {
+ readRoutes *prometheus.CounterVec
+}
+
+func NewDBRoutingMetrics() *DBRoutingMetrics {
+ return &DBRoutingMetrics{
+ readRoutes: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Name: "multica_db_read_routes_total",
+ Help: "Routing decisions by business, role, and reason; a replica fallback records both the replica selection and primary retry.",
+ }, []string{"business", "role", "reason"}),
+ }
+}
+
+func (m *DBRoutingMetrics) Collectors() []prometheus.Collector {
+ if m == nil {
+ return nil
+ }
+ return []prometheus.Collector{m.readRoutes}
+}
+
+func (m *DBRoutingMetrics) RecordReadRoute(business, role, reason string) {
+ if m == nil {
+ return
+ }
+ m.readRoutes.WithLabelValues(business, role, reason).Inc()
+}
diff --git a/server/internal/metrics/db_test.go b/server/internal/metrics/db_test.go
index 2a0e6ca8c4..daff22559a 100644
--- a/server/internal/metrics/db_test.go
+++ b/server/internal/metrics/db_test.go
@@ -11,13 +11,18 @@ import (
)
func TestDBCollectorExposesPoolStats(t *testing.T) {
- pool, err := pgxpool.New(context.Background(), "postgres://multica:[email protected]:1/multica?sslmode=disable")
+ pool, err := pgxpool.New(context.Background(), "postgres://multica:[email protected]:1/multica?sslmode=disable&pool_max_conns=13")
if err != nil {
t.Fatalf("create pool: %v", err)
}
defer pool.Close()
+ replicaPool, err := pgxpool.New(context.Background(), "postgres://multica:[email protected]:2/multica?sslmode=disable&pool_max_conns=7")
+ if err != nil {
+ t.Fatalf("create replica pool: %v", err)
+ }
+ defer replicaPool.Close()
- registry := NewRegistry(RegistryOptions{Pool: pool})
+ registry := NewRegistry(RegistryOptions{Pool: pool, ReplicaPool: replicaPool})
rec := httptest.NewRecorder()
NewHandler(registry.Gatherer).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
body := rec.Body.String()
@@ -32,4 +37,36 @@ func TestDBCollectorExposesPoolStats(t *testing.T) {
t.Fatalf("metrics body missing %q\n%s", want, body)
}
}
+ for _, want := range []string{
+ `multica_db_pool_max_conns{role="primary"} 13`,
+ `multica_db_pool_max_conns{role="replica"} 7`,
+ } {
+ if !strings.Contains(body, want) {
+ t.Fatalf("metrics body missing %q\n%s", want, body)
+ }
+ }
+}
+
+func TestDBRoutingMetricsExposeOnlyReadRoutes(t *testing.T) {
+ registry := NewRegistry(RegistryOptions{})
+ registry.DBRouting.RecordReadRoute("dashboard", "primary", "connection_failed")
+
+ rec := httptest.NewRecorder()
+ NewHandler(registry.Gatherer).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
+ body := rec.Body.String()
+ if want := `multica_db_read_routes_total{business="dashboard",reason="connection_failed",role="primary"} 1`; !strings.Contains(body, want) {
+ t.Fatalf("metrics body missing %q\n%s", want, body)
+ }
+ for _, removed := range []string{
+ "multica_db_replica_configured",
+ "multica_db_replica_healthy",
+ "multica_db_replica_lag_bytes",
+ "multica_db_replica_replay_lag_seconds",
+ "multica_db_replica_probes_total",
+ "multica_db_replica_fallbacks_total",
+ } {
+ if strings.Contains(body, removed) {
+ t.Fatalf("metrics body contains removed metric %q\n%s", removed, body)
+ }
+ }
}
diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.go
index 6c49d24d80..7604cd489c 100644
--- a/server/internal/metrics/registry.go
+++ b/server/internal/metrics/registry.go
@@ -12,11 +12,12 @@ import (
)
type RegistryOptions struct {
- Pool *pgxpool.Pool
- Realtime *realtime.Metrics
- DaemonWS *daemonws.Metrics
- Version string
- Commit string
+ Pool *pgxpool.Pool
+ ReplicaPool *pgxpool.Pool
+ Realtime *realtime.Metrics
+ DaemonWS *daemonws.Metrics
+ Version string
+ Commit string
}
type Registry struct {
@@ -26,6 +27,7 @@ type Registry struct {
ChannelMedia *ChannelMediaReconcilerMetrics
ChannelLease *ChannelLeaseMetrics
Wecom *WecomMetrics
+ DBRouting *DBRoutingMetrics
}
func NewRegistry(opts RegistryOptions) *Registry {
@@ -54,9 +56,11 @@ func NewRegistry(opts RegistryOptions) *Registry {
wecomMetrics := NewWecomMetrics()
reg.MustRegister(wecomMetrics.Collectors()...)
+ dbRoutingMetrics := NewDBRoutingMetrics()
+ reg.MustRegister(dbRoutingMetrics.Collectors()...)
if opts.Pool != nil {
- reg.MustRegister(NewDBCollector(opts.Pool))
+ reg.MustRegister(NewDBCollector(opts.Pool, opts.ReplicaPool))
}
if opts.Realtime != nil {
reg.MustRegister(NewRealtimeCollector(opts.Realtime))
@@ -72,6 +76,7 @@ func NewRegistry(opts RegistryOptions) *Registry {
ChannelMedia: channelMedia,
ChannelLease: channelLease,
Wecom: wecomMetrics,
+ DBRouting: dbRoutingMetrics,
}
}