Sub topic 4
What happens when the application starts
This chapter assumes you have finished the setup and versioned-migration chapters. You should have flyway-core and the PostgreSQL module on the classpath, a db/migration folder with at least one V1__...sql file, and a working DataSource. It follows what Spring Boot and Flyway do between the moment you run the application and the moment your first request is served.
Flyway is a bean, not a separate step
Flyway has no separate command in a Spring Boot project. Spring Boot's FlywayAutoConfiguration creates a Flyway bean and runs it while the application context is being built. The auto-configuration is active when these conditions hold:
- The
Flywayclass is on the classpath. - A
DataSourcebean exists, orspring.flyway.urlis set. spring.flyway.enabledistrue. This is the default.
If any condition fails, nothing runs and no error appears. A missing migration on startup is often just a missing dependency or enabled: false in a profile.
Boot builds a Flyway object from your spring.flyway.* properties and hands it to a FlywayMigrationStrategy. The default strategy calls flyway.migrate(). A later chapter shows how to replace the strategy. For now, treat it as "call migrate() once during startup".
Flyway runs before JPA
Spring Boot makes the EntityManagerFactory depend on Flyway. Hibernate does not initialize until the migration has finished. This ordering matters because of ddl-auto: validate. Hibernate compares your entities with the real tables, and those tables must already exist.
spring:
flyway:
enabled: true
locations: classpath:db/migration
jpa:
hibernate:
ddl-auto: validateThe same ordering applies to other beans that use the database through Boot's initialization support, such as JdbcTemplate users that run on startup. If you create your own beans that query the database in a constructor or @PostConstruct, they can run before the migration. Make sure they depend on the Flyway bean or on the entity manager.
The sequence inside `migrate()`
When migrate() runs, Flyway does the following in order:
- Opens a connection from the
DataSourceand detects the database type and version. - Creates the schema history table,
flyway_schema_history, if it does not exist. - Takes a lock so that only one process migrates at a time.
- Scans the configured locations and builds a list of available migrations.
- Validates applied migrations against the available ones (checksums and names).
- Compares the two lists and finds the pending migrations.
- Applies each pending migration in version order, then writes a row to the history table.
- Releases the lock and returns.
Repeatable migrations are applied after all pending versioned ones. They run in alphabetical order by description.
Watching it happen
Start the application against an empty PostgreSQL database with this migration:
-- src/main/resources/db/migration/V1__create_app_user.sql
CREATE TABLE app_user (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);The log shows output similar to this. Exact wording and timings vary by Flyway version.
Database: jdbc:postgresql://localhost:5432/app (PostgreSQL 16.2)
Successfully validated 1 migration (execution time 00:00.014s)
Creating Schema History table "public"."flyway_schema_history" ...
Current version of schema "public": << Empty Schema >>
Migrating schema "public" to version "1 - create app user"
Successfully applied 1 migration to schema "public", now at version v1 (execution time 00:00.031s)Start the application a second time. The log now ends with a short message such as Schema "public" is up to date. No migration necessary. Flyway still opens a connection, still validates, and still reads the history table. It simply finds nothing pending.
Transactions and partial failure
Flyway wraps each versioned migration in its own transaction by default. Two consequences follow.
- Per migration, not per run. If you have V4, V5 and V6 pending and V5 fails, V4 stays committed. Flyway stops at V5 and V6 is not attempted.
- It depends on the database. PostgreSQL supports transactional DDL, so a failing migration rolls back completely and leaves no history row. MySQL and Oracle commit DDL implicitly. A migration with five statements that fails on the fourth can leave the first three applied, and Flyway marks the history row as failed.
The practical rule is to keep each migration small and focused. On a database without transactional DDL, a small file is easier to repair by hand.
A few statements cannot run inside a transaction on PostgreSQL, for example CREATE INDEX CONCURRENTLY. Flyway detects some of these and runs the migration outside a transaction. You can also control this per script with a .conf file or with spring.flyway.group and related settings, covered in the configuration chapter.
What a failure looks like
A migration that fails throws an exception from migrate(). The exception propagates out of bean creation, and the whole application context fails to start. The process exits. This is deliberate: an application should not serve requests against a schema it does not understand.
| Cause | Typical symptom | First thing to check |
|---|---|---|
| SQL error in a pending migration | `FlywayException` with the database error and the script name | Run the script by hand against a copy of the database |
| Applied file edited after the fact | `Validate failed: Migrations have failed validation` with a checksum mismatch | `git log` for the file; restore the original |
| Applied migration missing from locations | `Detected applied migration not resolved locally` | Wrong `locations`, or the file was deleted |
| Non-empty schema with no history table | `Found non-empty schema(s) ... but no schema history table` | Baselining (a later chapter) |
| Cannot connect | `Unable to obtain connection from database` | URL, credentials, network, or the database not yet up |
Each of these stops startup before Hibernate sees the database.
Several instances starting at once
In production you often start several replicas at the same time. Each one tries to run migrate(). Flyway protects against races by taking a database lock. On PostgreSQL this is an advisory lock, and other databases use a lock on the history table. The first instance migrates. The others wait, then see no pending migrations and continue.
This works well for the typical case, but know its limits:
- A slow migration holds back every other replica's startup. If a readiness probe or startup timeout is shorter than the migration, an orchestrator may kill waiting instances.
- Rolling deployments run the new code's migration while old instances still serve traffic. The old code must tolerate the new schema. The expand and contract chapter covers this.
- A pooled connection that dies mid-migration leaves the lock to the database's own cleanup. Advisory locks are released when the session ends.
Using a different user for migrations
The application's runtime user rarely needs CREATE TABLE rights. Flyway can use its own connection settings:
spring:
datasource:
url: jdbc:postgresql://db:5432/app
username: app_runtime
password: ${APP_DB_PASSWORD}
flyway:
url: jdbc:postgresql://db:5432/app
user: app_migrator
password: ${FLYWAY_DB_PASSWORD}When spring.flyway.url or user is set, Boot creates a dedicated connection for Flyway rather than reusing the application DataSource. The runtime pool then runs with reduced privileges. Keep passwords in environment variables or a secrets store, not in the file.
Turning it off on purpose
Sometimes you want the application to start without migrating, for example when migrations run in a separate deployment job. Set spring.flyway.enabled=false for that profile. Be aware of the trade-off: with ddl-auto: validate, Hibernate will still fail at startup if the schema is behind the entities, so the check is not lost.
spring:
config:
activate:
on-profile: no-migrate
flyway:
enabled: falseSummary of the startup contract
FlywayAutoConfigurationbuilds theFlywaybean and callsmigrate()through the migration strategy.- Flyway finishes before Hibernate initializes, so
ddl-auto: validatesees the final schema. - Validation runs first, then pending migrations are applied one at a time, each with its own history row.
- Any failure aborts context creation. The application does not start with a half-migrated schema unnoticed.
- Concurrent instances are serialized by a database lock.
Exercise
You deploy a new version with migration V7. V7 contains three statements, and the third one fails. The database is PostgreSQL. What state is the schema in, what does flywayschemahistory contain for V7, and what happens to the application?
Show answer
Because PostgreSQL supports transactional DDL and Flyway wraps V7 in one transaction, all three statements are rolled back. The schema stays at V6, and flywayschemahistory has no row for V7. The exception from migrate() propagates out of bean creation, so the application context fails and the process exits. After you fix V7 (it was never applied, so editing it is safe) and restart, Flyway applies it normally.
Exercise
A teammate sets spring.flyway.enabled=false in the production profile and deploys a build with a new entity column. Hibernate is configured with ddl-auto: validate. What happens at startup, and why?
Show answer
Flyway does not run, so the new column is never created. Hibernate validation then compares the entity with the real table, finds the column missing, and throws a schema-validation exception during EntityManagerFactory creation. The application fails to start, which at least surfaces the problem at startup instead of at the first query.