Sub topic 15
Production practices and customizing migration at startup
This chapter covers how to run Flyway safely in production and how to change what Spring Boot does when migrations run. It assumes you can already write versioned and repeatable migrations, read flyway_schema_history, and configure spring.flyway properties. It also assumes you know what checksum validation does and how expand and contract works.
Where migrations run
Spring Boot runs Flyway while the application context starts, before JPA's EntityManagerFactory is created. This is convenient, but it ties schema changes to application startup. You have two broad choices:
- Let each application instance migrate at startup (the default).
- Disable startup migration and run Flyway as a separate deployment step, such as a CI/CD job, a Kubernetes init container, or the Flyway command line.
| Aspect | Migrate at startup | Separate migration step |
|---|---|---|
| Setup | None beyond the dependency | Extra job or pipeline stage |
| Database privileges | App needs DDL rights | App can use a restricted account |
| Failure effect | The instance fails to start | The deploy stops before new code ships |
| Rollout control | Tied to the first instance that starts | Explicit, with a clear point to take a backup |
| Best for | Small services, development, tests | Larger teams, strict production controls |
Neither option is wrong. Choose the second when the application account should not be allowed to alter tables, or when you want a human or a pipeline gate between "schema changed" and "new code running".
Multiple instances starting at once
When several instances start together, they all try to migrate. Flyway guards against this with a lock on the database. On PostgreSQL it uses an advisory lock, and on other databases it uses a lock on the schema history table. One instance applies the pending migrations while the others wait. They then find nothing left to do and continue.
This means concurrent startup is safe. It also means a slow migration delays every instance, and a hung migration can leave the others waiting. Keep that in mind when you set readiness and liveness probe timeouts. A probe that kills an instance in the middle of a long migration causes a failed deployment that is harder to read.
Use separate credentials
By default Flyway uses the application's spring.datasource connection. In production you can give Flyway its own account, so the runtime account needs only DML rights:
spring:
datasource:
url: jdbc:postgresql://db:5432/app
username: ${APP_DB_USER}
password: ${APP_DB_PASSWORD}
flyway:
url: jdbc:postgresql://db:5432/app
user: ${FLYWAY_DB_USER}
password: ${FLYWAY_DB_PASSWORD}
clean-disabled: true
validate-on-migrate: true
out-of-order: falseWhen spring.flyway.url, user, and password are set, Boot creates a dedicated connection for Flyway and the main data source stays unchanged. Read the credentials from environment variables or a secrets manager, never from a committed file.
Two settings in this block protect you from destructive mistakes:
clean-disabled: trueblocksflyway clean, which drops every object in the configured schemas. Recent Flyway versions default to disabled. Set it explicitly anyway, so the intent is visible and nobody turns it on in a production profile.validate-on-migrate: truemakes Flyway compare checksums before applying anything, so a modified migration stops the deployment.
Prepare before you migrate
A migration is a change to data you cannot recreate, so treat each production run as a release step:
- Take a backup or snapshot first. Know how long a restore takes.
- Rehearse against a copy of production data. A migration that runs in milliseconds on a test database can lock a table for minutes on millions of rows.
- Check for locks.
ALTER TABLEoften takes a lock that blocks reads and writes. Adding a column with a constant default is cheap on current PostgreSQL versions. Rewriting a column's type or adding an index normally is not. - Break up large data changes. Update rows in batches from a Java migration or a separate job instead of one huge
UPDATE. - Build indexes without blocking writes. On PostgreSQL,
CREATE INDEX CONCURRENTLYcannot run inside a transaction. Flyway detects this on PostgreSQL and runs that migration outside a transaction. Keep such a statement alone in its own migration file.
PostgreSQL runs DDL inside a transaction, so a failed migration rolls back completely. Many other databases cannot do this. On those, a half-applied migration leaves the schema partly changed and a failed row in the history table. Writing small migrations, with one logical change per file, limits the damage.
Roll forward instead of rolling back
The Community edition of Flyway has no automatic undo for versioned migrations. The usual practice is to roll forward: if release 5 introduced a bad change, ship V6 that fixes it. Expand and contract supports this. While the old column or table still exists, the previous application version keeps working, so you can redeploy it without touching the schema.
Plan these cases before you need them:
- The schema change is additive and compatible: roll back the application only.
- The change destroyed data: restore from backup, which is why the backup step exists.
- The migration failed: fix the cause, and use
repaironly for the history table, not for the schema itself.
Customizing migration with FlywayMigrationStrategy
Spring Boot's Flyway auto-configuration calls flyway.migrate() by default. If you define a bean of type FlywayMigrationStrategy, Boot calls your code instead. The default behavior is only replaced, so your code must call migrate itself or nothing will be applied.
The simplest strategy repeats the default:
import org.flywaydb.core.Flyway;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class FlywayConfig {
@Bean
FlywayMigrationStrategy migrationStrategy() {
return Flyway::migrate;
}
}That is a starting point. A more useful version logs what is about to happen, so deployment logs show which migrations ran:
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class FlywayConfig {
private static final Logger log = LoggerFactory.getLogger(FlywayConfig.class);
@Bean
FlywayMigrationStrategy loggingStrategy() {
return flyway -> {
MigrationInfo[] pending = flyway.info().pending();
for (MigrationInfo info : pending) {
log.info("Pending migration {} - {}", info.getVersion(), info.getDescription());
}
flyway.migrate();
log.info("Schema is now at version {}", flyway.info().current().getVersion());
};
}
}flyway.info().current() returns null on an empty database with nothing applied. After a successful migrate() it is non-null as long as at least one versioned migration exists.
A strategy can also be limited to a profile. This version resets a local database on every start:
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("local")
class LocalFlywayConfig {
@Bean
FlywayMigrationStrategy cleanAndMigrate() {
return flyway -> {
flyway.clean();
flyway.migrate();
};
}
}It works only when spring.flyway.clean-disabled is false in the local profile. Keep that setting out of every shared or production configuration.
Turning off startup migration
When migrations run in a pipeline, disable them in the application:
spring:
flyway:
enabled: falseWith Flyway disabled, Hibernate's ddl-auto: validate still checks the entities against the schema. If the application starts before the migration job finishes, validation fails with a missing table or column. Order the pipeline so the migration job completes first.
A production checklist
- Credentials for Flyway are separate from the runtime account, or the runtime account is deliberately trusted.
clean-disabledistrueandddl-autoisvalidateornone.- A backup exists and a restore has been tested.
- New migrations were run against production-sized data.
- Migrations are backward compatible with the previous application version.
- Probes tolerate the longest expected migration.
- Logs show which migrations were applied in each deployment.
Exercise
Your service runs three instances and each one migrates at startup. A new release contains a migration that takes four minutes. What happens to the other two instances while one applies it, and what should you check in your deployment configuration?
Show answer
Flyway's database lock makes the other two instances wait until the first finishes. They then see no pending migrations and continue starting. Check that the readiness and liveness probe timeouts and the deployment's progress deadline are longer than four minutes. Otherwise the orchestrator may kill the waiting or migrating instances and fail the rollout.
Exercise
You add a FlywayMigrationStrategy bean that only logs a message and does not call migrate. The application starts without errors. Why does Hibernate fail with a missing table, and how do you fix the bean?
Show answer
A FlywayMigrationStrategy bean replaces the default call to migrate, so no migrations were applied. Hibernate's validate mode then finds tables missing. Fix the bean so it calls flyway.migrate(), as in the logging strategy shown above.