Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: add advisory lock to database migrations (#18833)

p0ny06f52236a5b5
diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.go
index 487e9570c9..74bb263645 100644
--- a/backend/migrator/migrator.go
+++ b/backend/migrator/migrator.go
@@ -15,6 +15,8 @@ import (
"github.com/blang/semver/v4"
"github.com/lib/pq"
"github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/store"
)
const latestSchemaFileName = "migration/LATEST.sql"
@@ -38,6 +40,14 @@ var goMigrations = map[string]GoMigrationFunc{
// MigrateSchema migrates the schema for metadata database.
func MigrateSchema(ctx context.Context, db *sql.DB) error {
+ // Acquire advisory lock to ensure only one replica runs migrations.
+ // This blocks until the lock is available.
+ release, err := store.AcquireAdvisoryLock(ctx, db, store.AdvisoryLockKeyMigration)
+ if err != nil {
+ return errors.Wrap(err, "failed to acquire migration lock")
+ }
+ defer release()
+
files, err := getSortedVersionedFiles()
if err != nil {
return err
diff --git a/backend/store/advisory_lock.go b/backend/store/advisory_lock.go
index d4b198f07a..edb6daa3cc 100644
--- a/backend/store/advisory_lock.go
+++ b/backend/store/advisory_lock.go
@@ -13,6 +13,9 @@ const (
// AdvisoryLockKeyPendingScheduler is used by the pending task run scheduler
// to ensure only one replica promotes PENDING → AVAILABLE at a time.
AdvisoryLockKeyPendingScheduler AdvisoryLockKey = 1001
+ // AdvisoryLockKeyMigration is used by the schema migrator to ensure only
+ // one replica runs database migrations at a time.
+ AdvisoryLockKeyMigration AdvisoryLockKey = 1002
)
// AdvisoryLock holds a dedicated connection for a session-level advisory lock.
@@ -53,3 +56,25 @@ func (l *AdvisoryLock) Release() error {
_, _ = l.conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", int64(l.key))
return l.conn.Close()
}
+
+// AcquireAdvisoryLock acquires a session-level advisory lock, blocking until
+// the lock is available. Returns a release function that must be called when done.
+// This is useful for migrations where we want to wait rather than fail fast.
+func AcquireAdvisoryLock(ctx context.Context, db *sql.DB, key AdvisoryLockKey) (func(), error) {
+ conn, err := db.Conn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // pg_advisory_lock blocks until the lock is acquired
+ if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", int64(key)); err != nil {
+ conn.Close()
+ return nil, err
+ }
+
+ release := func() {
+ _, _ = conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", int64(key))
+ conn.Close()
+ }
+ return release, nil
+}