Skip to content

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

Go

fix(migrate): serialize startup migrations with pg advisory lock (#3658)

LinYushen24ea169d8966
diff --git a/deploy/helm/multica/templates/backend.yaml b/deploy/helm/multica/templates/backend.yaml
index d3e2566785..a34ad330f1 100644
--- a/deploy/helm/multica/templates/backend.yaml
+++ b/deploy/helm/multica/templates/backend.yaml
@@ -26,8 +26,10 @@ metadata:
{{- include "multica.labels" . | nindent 4 }}
app.kubernetes.io/component: backend
spec:
- # The backend entrypoint runs migrations before starting. Keep replicas at 1
- # so two pods don't race on startup migrations.
+ # The backend entrypoint runs migrations before starting. Concurrent
+ # runs are protected by a Postgres advisory lock in cmd/migrate (see
+ # GitHub multica-ai/multica#3647), so multiple replicas no longer race;
+ # 1 is still the chart default (strategy: Recreate, no leader split).
replicas: {{ .Values.backend.replicas }}
strategy:
type: Recreate
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index 409d509136..1d3f35ca9d 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -56,6 +56,13 @@ postgres:
# Backend (Go API + WS server)
# -----------------------------------------------------------------------------
backend:
+ # Concurrent backend pods are now safe to start: cmd/migrate uses a
+ # Postgres session-level advisory lock to serialize the startup
+ # `migrate up` run, so late-arriving pods queue and then no-op (see
+ # GitHub multica-ai/multica#3647). 1 is still the recommended default
+ # because the chart Deployment uses strategy: Recreate and there is no
+ # leader-elected workload split — increase this only if you actually
+ # need horizontal scale of the API/WS server.
replicas: 1
uploads:
persistence:
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 1b7c0fccc9..fb1b7d8d75 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -11,6 +11,14 @@ import (
"github.com/multica-ai/multica/server/internal/migrations"
)
+// migrationAdvisoryLockKey is the int64 identifier used with Postgres
+// pg_advisory_lock to serialize the migration loop across concurrent
+// runners (multi-replica backend Deployment, scale-up, or a manual
+// `migrate up` overlapping with pod startup). The exact value is
+// arbitrary — it just needs to be stable across every process that runs
+// migrations against the same database. See GitHub multica-ai/multica#3647.
+const migrationAdvisoryLockKey int64 = 7244554146635925501
+
func main() {
logger.Init()
@@ -43,8 +51,42 @@ func main() {
os.Exit(1)
}
+ // Serialize the entire migration run with a Postgres session-level
+ // advisory lock. pg_advisory_lock is scoped to a single session, so we
+ // must pin one *pgxpool.Conn for the whole run — calling pool.Exec
+ // would attach the lock to a random connection that pgxpool could
+ // hand back out before the loop finishes, making the lock effectively
+ // a no-op. We use the blocking pg_advisory_lock (not pg_try_*) so a
+ // late-arriving pod queues behind the current runner instead of
+ // crash-looping; once it acquires the lock the EXISTS checks below
+ // turn into a no-op skip. See GitHub multica-ai/multica#3647.
+ //
+ // We deliberately do NOT wrap the loop in a single transaction: the
+ // repo already ships migrations using CREATE INDEX CONCURRENTLY,
+ // which Postgres rejects inside a transaction block.
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ slog.Error("unable to acquire migration connection", "error", err)
+ os.Exit(1)
+ }
+ defer conn.Release()
+
+ if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock($1)", migrationAdvisoryLockKey); err != nil {
+ slog.Error("failed to acquire migration advisory lock", "error", err)
+ os.Exit(1)
+ }
+ // Best-effort explicit unlock on the success path. On os.Exit error
+ // paths this defer does not run, but session-level advisory locks are
+ // released automatically when the connection closes at process exit,
+ // so the next runner is never permanently blocked.
+ defer func() {
+ if _, err := conn.Exec(ctx, "SELECT pg_advisory_unlock($1)", migrationAdvisoryLockKey); err != nil {
+ slog.Warn("failed to release migration advisory lock", "error", err)
+ }
+ }()
+
// Create migrations tracking table
- _, err = pool.Exec(ctx, `
+ _, err = conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
@@ -67,7 +109,7 @@ func main() {
if direction == "up" {
// Check if already applied
var exists bool
- err := pool.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", version).Scan(&exists)
+ err := conn.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", version).Scan(&exists)
if err != nil {
slog.Error("failed to check migration status", "version", version, "error", err)
os.Exit(1)
@@ -79,7 +121,7 @@ func main() {
} else {
// Check if applied (only rollback applied ones)
var exists bool
- err := pool.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", version).Scan(&exists)
+ err := conn.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", version).Scan(&exists)
if err != nil {
slog.Error("failed to check migration status", "version", version, "error", err)
os.Exit(1)
@@ -96,16 +138,16 @@ func main() {
os.Exit(1)
}
- _, err = pool.Exec(ctx, string(sql))
+ _, err = conn.Exec(ctx, string(sql))
if err != nil {
slog.Error("failed to run migration", "file", file, "error", err)
os.Exit(1)
}
if direction == "up" {
- _, err = pool.Exec(ctx, "INSERT INTO schema_migrations (version) VALUES ($1)", version)
+ _, err = conn.Exec(ctx, "INSERT INTO schema_migrations (version) VALUES ($1)", version)
} else {
- _, err = pool.Exec(ctx, "DELETE FROM schema_migrations WHERE version = $1", version)
+ _, err = conn.Exec(ctx, "DELETE FROM schema_migrations WHERE version = $1", version)
}
if err != nil {
slog.Error("failed to record migration", "version", version, "error", err)