Skip to content

feat: allow migrating postgres via a kubernetes job - #3594

Merged
turip merged 1 commit into
mainfrom
feat/allow-migrations-in-external-job
Nov 10, 2025
Merged

turip merged 1 commit into
mainfrom
feat/allow-migrations-in-external-job

Conversation

@turip

@turip turip commented Nov 10, 2025 •

Copy link
Copy Markdown
Member

Overview

This change introduces the support to migrate database using an external job, which is more reliable for large scale deployments than the current implementation.

To do so, the backend services can have their autoMigrate set to migration-job. In this mode the service waits until the database schema's version becomes >= than the currently embedded latest migration.

This approach allows for running older versions of backend against newer version of the database (e.g. blue/green deployment scenarios).

The polling of the database timeouts after 30s. This is enough as the readiness probe of the services will restart the container faster either ways.

Notes for reviewer

Summary by CodeRabbit

  • New Features
    • Added a new migrate CLI subcommand to run database migrations with selectable modes.
    • Introduced "migration-job" as a new migration configuration mode.
    • Added migration-job monitoring that waits and verifies the database reaches the target migration version before reporting success.

@coderabbitai

coderabbitai Bot commented Nov 10, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR adds a "migration-job" AutoMigrate mode, a CLI migrate subcommand, and a migration-wait mechanism: configuration accepts the new mode, the app can call WaitForMigrationJob to poll migration completion, and the CLI exposes a migrate command to trigger or validate migration modes.

Changes

Cohort / File(s) Summary
Config
app/config/postgres.go
Added AutoMigrateMigrationJob ("migration-job") to AutoMigrate and updated Validate() to accept it. Enabled() behavior unchanged.
Database runtime
app/common/database.go
Extended Migrator.Migrate switch to handle AutoMigrateMigrationJob by calling migrate.WaitForMigrationJob(dbURL, logger) and wrapping errors with context.
CLI integration
cmd/jobs/main.go, cmd/jobs/migrate/migrate.go
Registered migrate subcommand; new RootCommand() implements a CLI command with -m mode flag, validates mode, applies it to internal.App.Migrator.Config.AutoMigrate, and runs Migrator.Migrate. The command disallows running in migration-job mode.
Migration tooling
tools/migrate/migrate.go
Replaced Migrate type alias with a struct holding the underlying migrate instance and a source.Driver; added LatestVersion() to inspect available migrations; centralized setup via getMigrationForConn; and added WaitForMigrationJob(conn string, logger *slog.Logger, ...opts) with retry/delay options and dirty-state checks to poll until DB matches the binary's migration version.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI Command
    participant Config as Config
    participant Migrator as Migrator
    participant DB as Database
    participant WaitFn as WaitForMigration

    Note over CLI: User runs migrate command with mode flag

    CLI->>Config: Validate migration mode
    Config-->>CLI: Mode valid or error
    CLI->>Migrator: Set Migrator.Config.AutoMigrate(mode)
    Migrator->>DB: Migrator.Migrate(ctx)
    
    alt mode == "migration-job"
        DB->>WaitFn: WaitForMigrationJob(dbURL, logger)
        loop retry
            WaitFn->>DB: Query current migration version
            DB-->>WaitFn: current version / dirty flag
            WaitFn->>WaitFn: Compare with LatestVersion()
            alt match
                WaitFn-->>DB: return success
            else dirty or mismatch
                WaitFn->>WaitFn: sleep & retry
            end
        end
    else other modes
        DB->>DB: Apply migrations directly
    end

    DB-->>Migrator: result
    Migrator-->>CLI: success or error
    CLI->>CLI: log outcome
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Focus review on:
    • tools/migrate/migrate.go — struct refactor, LatestVersion() correctness, WaitForMigrationJob retry logic and dirty-state handling.
    • app/common/database.go — correct invocation and error wrapping for the new mode.
    • cmd/jobs/migrate/migrate.go — mode validation and CLI gating for migration-job.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main feature: adding support for database migrations via Kubernetes jobs, which aligns perfectly with the changeset's core objective.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/allow-migrations-in-external-job

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai

coderabbitai Bot commented Nov 10, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/allow-migrations-in-external-job

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@turip turip added the release-note/feature Release note: Exciting New Features label Nov 10, 2025
@turip
turip marked this pull request as ready for review November 10, 2025 13:49
@turip
turip requested a review from a team as a code owner November 10, 2025 13:49
@turip
turip force-pushed the feat/allow-migrations-in-external-job branch from 37db5c7 to ad7cfc8 Compare November 10, 2025 13:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/config/postgres.go (1)

20-25: Document the new migration-job option

The inline docs still list only false, ent, and migration. Folks reading this comment won’t discover the new migration-job mode, which makes it harder to configure correctly.

A quick tweak keeps the comment up to date:

-// - "migration" to use the migrations directory
+// - "migration" to use the migrations directory
+// - "migration-job" to wait for an external migration job to finish provisioning the schema
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d7c37fa and ad7cfc8.

📒 Files selected for processing (5)
  • app/common/database.go (1 hunks)
  • app/config/postgres.go (2 hunks)
  • cmd/jobs/main.go (2 hunks)
  • cmd/jobs/migrate/migrate.go (1 hunks)
  • tools/migrate/migrate.go (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

⚙️ CodeRabbit configuration file

**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.

Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.

Files:

  • app/common/database.go
  • cmd/jobs/main.go
  • app/config/postgres.go
  • cmd/jobs/migrate/migrate.go
  • tools/migrate/migrate.go
🧬 Code graph analysis (3)
app/common/database.go (2)
app/config/postgres.go (1)
  • AutoMigrateMigrationJob (71-71)
tools/migrate/migrate.go (1)
  • WaitForMigrationJob (142-188)
cmd/jobs/main.go (1)
cmd/jobs/migrate/migrate.go (1)
  • RootCommand (12-43)
cmd/jobs/migrate/migrate.go (2)
app/config/postgres.go (3)
  • AutoMigrate (66-66)
  • AutoMigrateMigrationJob (71-71)
  • AutoMigrateMigration (70-70)
app/common/database.go (1)
  • Migrator (31-35)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Code Generators
  • GitHub Check: Build
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Analyze (go)

Comment thread cmd/jobs/migrate/migrate.go Resolved
Comment thread tools/migrate/migrate.go Resolved
Comment thread tools/migrate/migrate.go Resolved

@GAlexIHU GAlexIHU left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like the >= N check as the default (and only) behavior... to solve those "older version not getting stuck with newer db if we fail" scenarios you called out

  1. we'd be currently failing on those and as bad as they sound i'm not sure we need them based on the operation experience of the past year
  2. if we really want to solve them i think we should do that on the deploy level (e.g. make app somehow aware it's "restarting" and not "starting"). ik that sounds like a hack, but assuming the app will run with the wrong db version is already a hack

otherwise if you need this urgently i'm ok with this being merged

Comment thread tools/migrate/migrate.go
return err
}

err = retry.Do(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: do we need a lib for this?

Comment thread tools/migrate/migrate.go Resolved
Comment thread tools/migrate/migrate.go
)

if ver >= currentBinaryTargetVersion {
// We are at least on the version that is required by the binary => good to go

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know leniency in version enforcement is comfortable, but there are reasons app version N wouldn't work with db version N+1 :D

I think it's fine if the migration tooling has a method that polls for version >= X, but at least in the app startup we should have more control... still the related issues mostly come about in relation to lack of easy rollbacks and dirty states....

Comment thread app/common/database.go
return fmt.Errorf("failed to migrate db: %w", err)
}
case config.AutoMigrateMigrationJob:
if err := migrate.WaitForMigrationJob(m.Config.AsURL(), m.Logger); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: if we want a scoped logger let's add a constructor to migrate instead

Comment thread cmd/jobs/main.go
rootCmd.AddCommand(entitlement.RootCommand())
rootCmd.AddCommand(billing.Cmd)
rootCmd.AddCommand(quickstart.Cmd)
rootCmd.AddCommand(migrate.RootCommand())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, we have a very basic migrate job in the cloud repo for the Tilt migration setup, we should consolidate that too to (though its not exactly the same thing as this)

@turip
turip merged commit 76c032a into main Nov 10, 2025
@turip
turip deleted the feat/allow-migrations-in-external-job branch November 10, 2025 14:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants