Video in progress

Who should run the Flyway migration: the application itself at startup, or a separate step in the deploy pipeline?

Running it at startup is simple, but it causes problems with several replicas, long migrations and the startup probe. In bigger services I make the migration a separate Job or pipeline step, and the app only checks the schema version.

📖 Answer

By default Spring Boot runs Flyway while the context is coming up. For a small service that is convenient.

The problems show up as it grows:

  • 6 replicas come up at once. One takes the Flyway table lock and the others wait. That is safe, but everything slows down;
  • the migration takes 10 minutes (an index on a big table), the startupProbe kills the pod, and the migration is left half done;
  • the app's DB user needs DDL rights. From a security standpoint it is better not to give the runtime user ALTER TABLE;
  • if the migration fails, the new pods and the rolled-back old pods fail in the same way.

The alternative is a separate step:

# Helm pre-upgrade hook or a CI step
apiVersion: batch/v1
kind: Job
metadata:
  annotations:
    "helm.sh/hook": pre-upgrade,pre-install
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: registry/app:1.42.0
          args: ["--spring.main.web-application-type=none", "--spring.flyway.enabled=true"]

In the application itself you set spring.flyway.enabled=false, or at most validate. One catch: the app in the Job has to exit on its own after the migration. If the context has a Kafka listener or @Scheduled, the JVM does not stop and the Job never finishes. A separate profile for migration (listeners off), or a plain Flyway CLI image, is better.

But this approach imposes one requirement: the migration is released first and the code after. So the migration must be compatible with the old code too (add a column, do not drop one). This is the usual expand/contract discipline.