Database Migrations with Flyway and Liquibase in Spring Boot
Spring Boot in Production · Part 3 of 17
- #Java
- #Spring Boot
- #production
- #flyway
- #liquibase
- #postgresql
Most Spring Boot apps start with spring.jpa.hibernate.ddl-auto=update, and
for a while it works. Then the schema starts to matter. A column gets renamed
and the old one stays behind forever, because update never drops anything.
Staging and production slowly stop matching. Someone runs an ALTER TABLE by
hand on Friday and nobody writes it down. A Spring Boot Flyway setup fixes
this by turning every schema change into a numbered SQL file that lives in
git, gets reviewed like code, and runs exactly once per database.
That part is easy. The harder questions show up in production. What happens when three pods start at the same time and all try to migrate? Should migrations run when the app boots, or as their own step in the pipeline? How do you adopt Flyway on a database that has been in production for four years? And how do you rename a column while the old version of the app is still serving traffic?
This is Part 3 of Spring Boot in Production.
Part 1 made bad
configuration fail at startup, and
Part 2 made health checks honest.
This part is about the schema. The example is the same orders service,
now on PostgreSQL. Everything below ran on Spring Boot 4.2.0 and
Java 25 (Amazon Corretto), with the Flyway 12.11 and Liquibase 5.0 versions
that Boot 4.2 manages, against a real PostgreSQL 17 started by
Testcontainers.
Why ddl-auto is not a migration strategy
ddl-auto makes Hibernate guess the schema from your entities. That guess is
fine on your laptop and wrong for a shared database, for a few reasons:
- It only adds.
updatecreates tables and columns. It doesn't drop, rename, or change types, so every refactor leaves debris behind. - There's no history. Nothing records which change ran when, so you can't tell why staging and production differ.
- It can't move data. A schema change often comes with a data change (backfill a column, split a field). Hibernate has no idea that's needed.
- Nobody reviews it. The DDL is generated at startup, on whichever instance boots first. The first time a human sees it is in production.
Persisting Data with Spring Data JPA showed the minimal switch. This post starts where that one stopped.
Adding Flyway to Spring Boot
On Spring Boot 4, the auto-configuration for each library lives in its own
module, so you add the Flyway starter. On Spring Boot 3.x, flyway-core on
the classpath was enough. On PostgreSQL, Flyway also needs its database
module:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-flyway</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
</dependency>
Scripts go in src/main/resources/db/migration. Spring Boot runs them on
startup, before Hibernate builds the EntityManagerFactory, so by the time
your entities are checked the schema is already there:
spring:
jpa:
hibernate:
ddl-auto: validate
open-in-view: false
flyway:
locations: classpath:db/migration
postgresql:
transactional-lock: false # explained below, it matters
The first migration creates the table:
-- V1__create_orders.sql
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_email VARCHAR(320) NOT NULL,
total_cents BIGINT NOT NULL,
status VARCHAR(20) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
On an empty database, startup logs every step:
Creating Schema History table "public"."flyway_schema_history" ...
Current version of schema "public": << Empty Schema >>
Migrating schema "public" to version "1 - create orders"
Migrating schema "public" to version "2 - add orders currency"
...
Migrating schema "public" to version "6 - index orders email" [non-transactional]
Migrating schema "public" with repeatable migration "order totals view"
Successfully applied 7 migrations to schema "public", now at version v6
Versioned vs repeatable migrations
Flyway reads the file name to decide what a script is and when it runs:
Versioned files (V1__..., V2__...) run once, in order. Flyway stores
a checksum for each one in flyway_schema_history. Change a file after it ran
and the next startup fails validation. That's on purpose: the database already
has the old version, and editing the file doesn't change the database. To fix
a mistake, add a new migration.
Repeatable files (R__...) have no version. They run after all versioned
migrations, and again whenever their content changes. They're a good fit for
things you'd rather define than patch: views, functions, grants.
-- R__order_totals_view.sql
CREATE OR REPLACE VIEW order_totals_by_status AS
SELECT status, currency, count(*) AS orders, sum(total_cents) AS total_cents
FROM orders
GROUP BY status, currency;
A repeatable script has to be safe to run again on top of itself, so it's
CREATE OR REPLACE, never a plain CREATE.
A naming rule that saves arguments later: pick a version scheme before the
second developer joins. Plain integers (V7, V8) are readable, but two
branches will both create V7 sooner or later, and the second one to merge
has to renumber. Timestamps (V20261201_1030__...) avoid that collision.
Whichever you pick, put a check in CI so nobody can merge a version number
lower than one that's already in main, because Flyway's default is to
refuse out-of-order migrations.
Let Hibernate check the schema, not create it
ddl-auto: validate is the other half of the setup. Hibernate stops changing
the schema and only compares it with your entities. If they disagree, the
app doesn't start.
It catches more than missing columns. While the code for this post was being
written, the currency column was first declared as CHAR(3) in SQL and
mapped as a String with length = 3 in the entity. Startup failed:
Schema validation: wrong column type encountered in column [currency] in
table [orders]; found [bpchar (Types#CHAR)], but expecting [char(3) (Types#VARCHAR)]
That's the kind of drift you want to see at startup, in a test, not as odd
padding in production data. The fix was VARCHAR(3) in the migration.
What happens when two pods start at once
A rolling deploy with three replicas starts three JVMs, and each one runs Flyway during startup. They don't take turns on their own. On PostgreSQL, Flyway uses an advisory lock: the first instance gets it and migrates, the others wait, then find nothing left to do.
You can see that in a test. Two threads stand in for two pods and migrate the same empty database at the same time:
@Test
void twoPodsStartingAtOnceApplyEachMigrationOnce() throws Exception {
Callable<MigrateResult> pod = () -> TestFlyway.against(postgres).load().migrate();
List<MigrateResult> results;
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
var a = executor.submit(pod);
var b = executor.submit(pod);
results = List.of(a.get(), b.get());
}
assertThat(results).extracting(r -> r.migrationsExecuted).containsExactlyInAnyOrder(7, 0);
assertThat(jdbc.queryForObject(
"select count(*) from flyway_schema_history where success", Long.class)).isEqualTo(7L);
}
One pod ran 7 migrations, the other ran 0, and the history has 7 rows. The lock works. The cost is that the pods that lose the race block until the winner finishes, so a slow migration makes all of them slow to start. Keep that in mind with the startup probe from Part 2: a migration that takes longer than the probe allows gets the pod restarted halfway through.
The CREATE INDEX CONCURRENTLY hang
On a busy table, you build an index with CREATE INDEX CONCURRENTLY, which
doesn't block writes. PostgreSQL won't run it inside a transaction, and
Flyway knows that. It runs the script outside one and marks it
[non-transactional] in the log.
-- V6__index_orders_email.sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_email ON orders (email);
With Flyway's default settings, this migration never finishes. Flyway holds
its PostgreSQL lock inside a transaction on a second connection, and
CREATE INDEX CONCURRENTLY waits for every open transaction to end before it
can build the index. That includes Flyway's own. In the test run, the
migration was still waiting after 20 seconds, and pg_stat_activity showed
why:
state | wait_event_type | query
---------------------+-----------------+--------------------------------------------
idle in transaction | Client | SELECT COUNT(*) FROM pg_namespace WHERE ...
active | Lock | CREATE INDEX CONCURRENTLY IF NOT EXISTS ...
The fix is the transactional-lock: false line from the configuration above
(spring.flyway.postgresql.transactional-lock). Flyway then uses a
session-level advisory lock instead, which doesn't hold a transaction open.
With it, the same migration finished in milliseconds, and the two-pod test
above still passed. If you add Flyway to a PostgreSQL project, set it on day
one, before the first concurrent index shows up during an incident.
On startup, or as a separate step?
Running migrations at startup is the default, and for one small service it's fine. It gets less comfortable as the system grows:
The problems with migrating on startup:
- The app needs DDL permissions. The user that serves requests can also drop tables. Splitting the migration user from the runtime user is a cheap win for least privilege.
- A failed migration fails every pod. The rollout stalls with pods in a crash loop, instead of the pipeline stopping cleanly before anything deployed.
- Long migrations fight your probes, as above.
The alternative is to run migrate as its own pipeline step (a Flyway CLI or
container image, a Kubernetes Job, or the app itself started with a migrate-only
profile) and let the app only check the schema. Spring Boot has a hook for
that: a FlywayMigrationStrategy bean replaces the default migrate call.
package com.example.orders;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class MigrationConfig {
// The pipeline runs `migrate` as its own step. App pods only check that
// the schema matches the scripts they were built with, and refuse to start if not.
@Bean
@ConditionalOnProperty(name = "app.migrations.mode", havingValue = "validate")
FlywayMigrationStrategy validateOnly() {
return flyway -> flyway.validate();
}
}
In Spring Boot 3.5 the interface is
org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy. Set
APP_MIGRATIONS_MODE=validate on the deployed pods. If the pipeline step
didn't run, the pods refuse to start, and the reason is in the log:
Validate failed: Migrations have failed validation
Detected resolved migration not applied to database: 1.
To fix this error, either run migrate, or set -ignoreMigrationPatterns='*:pending'.
That beats the alternative, which is the app starting against an old schema and failing on the first request that touches a new column. A test for it starts the app before and after the migrate step:
@Test
void appRefusesToStartUntilThePipelineHasMigrated() {
assertThatThrownBy(() -> new SpringApplicationBuilder(OrdersApplication.class).run(args()).close())
.hasStackTraceContaining("Validate failed");
TestFlyway.against(postgres).load().migrate(); // the pipeline's migrate step
try (var context = new SpringApplicationBuilder(OrdersApplication.class).run(args())) {
assertThat(context.getBean(PurchaseOrderRepository.class).count()).isZero();
}
}
Which one should you choose? If you have one service, one database, and migrations that take seconds, migrating on startup is simpler and the risks are small. Once you have strict permissions, big tables, or many replicas, move it to the pipeline.
Baselining an existing database
Adopting Flyway on a database that already exists (built by hand, or by years
of ddl-auto: update) has one trap: V1 tries to create tables that are
already there. Baselining tells Flyway "this database is already at version
N, start from N+1":
spring:
flyway:
baseline-on-migrate: true
baseline-version: 1
The process that works:
- Dump the current production schema (
pg_dump --schema-only) and turn it intoV1__baseline.sql. New, empty databases (CI, a developer's laptop) build from it. - Set
baseline-versionto1. On a database that has tables but noflyway_schema_history, Flyway records version 1 as the baseline and skips it. - Every change after that is
V2onwards, the normal way.
The test creates the old table by hand, inserts a row, and lets Flyway take over:
@Test
void existingDatabaseStartsAtTheBaseline() throws Exception {
// A database someone built by hand (or with ddl-auto=update) years ago:
jdbc.execute(Files.readString(Path.of("src/main/resources/db/migration/V1__create_orders.sql")));
jdbc.update("insert into orders (customer_email, total_cents, status) values ('[email protected]', 1, 'PAID')");
var result = TestFlyway.against(postgres)
.baselineOnMigrate(true)
.baselineVersion("1")
.load()
.migrate();
assertThat(result.migrationsExecuted).isEqualTo(6); // V2..V6 + the view, never V1
assertThat(jdbc.queryForObject("select email from orders", String.class)).isEqualTo("[email protected]");
}
Be careful with baseline-on-migrate once the migration is done. It only
acts on a non-empty schema without a history table, so it's mostly harmless,
but if someone points the app at the wrong database, a baseline will happily
mark it as "already migrated". Turn it off after the first production run.
Expand and contract: schema changes without downtime
Here's the problem that matters most in production. During a rolling deploy, the old and new versions of your app run side by side, against the same database. Every migration has to work with both. And if you need to roll back, the old version has to work with the new schema too.
Some changes are safe in a single step. Adding a column with a constant default is one of them. On PostgreSQL 11 and later, it doesn't even rewrite the table, and old code that doesn't know the column keeps inserting rows:
-- V2__add_orders_currency.sql
ALTER TABLE orders ADD COLUMN currency VARCHAR(3) NOT NULL DEFAULT 'BRL';
Renaming a column isn't. The moment customer_email becomes email, every
pod still running the old code starts failing. So you split the rename into
steps, one release apart. This pattern is called expand and contract
(or parallel change):
The migrations:
-- V3__add_orders_email.sql (release 1)
-- Expand: the new column arrives empty and nullable. Old code ignores it.
ALTER TABLE orders ADD COLUMN email VARCHAR(320);
-- V4__backfill_orders_email.sql (release 2)
-- Runs only after every pod writes both columns.
UPDATE orders SET email = customer_email WHERE email IS NULL;
ALTER TABLE orders ALTER COLUMN email SET NOT NULL;
ALTER TABLE orders ALTER COLUMN customer_email DROP NOT NULL;
-- V5__drop_orders_customer_email.sql (release 4)
-- Contract: ships one release after the code stopped writing customer_email.
ALTER TABLE orders DROP COLUMN customer_email;
Release 3 has no migration at all. It's the release where the code stops
writing customer_email, and it's why the drop waits until release 4. If the
column disappeared together with that code change, the release 2 pods still
running during the rollout would fail their inserts.
This sequence is easy to get wrong by one release, so it deserves a test.
Flyway.configure().target("3") migrates only up to a given version, so a
test can walk the schema forward one step at a time and run each release's
SQL against it:
@Test
void renameColumnWithoutBreakingAnyRunningVersion() {
migrateTo("2");
release0Insert("[email protected]");
migrateTo("3"); // expand: release 0 and release 1 pods run side by side
release0Insert("[email protected]");
release1Insert("[email protected]");
migrateTo("4"); // backfill once no release-0 pod is left
assertThat(jdbc.queryForObject("select count(*) from orders where email is null", Long.class)).isZero();
release1Insert("[email protected]"); // rolling back to release 1 still works
release3Insert("[email protected]"); // release 3 needs customer_email nullable
// Contracting too early is the bug this whole dance prevents:
assertThatThrownBy(() -> release0Insert("[email protected]"))
.hasStackTraceContaining("null value in column \"email\"");
migrateTo("5"); // contract, one release after nobody writes customer_email
release3Insert("[email protected]");
assertThatThrownBy(() -> release1Insert("[email protected]"))
.hasStackTraceContaining("column \"customer_email\" of relation \"orders\" does not exist");
}
release0Insert, release1Insert and release3Insert are one-line
JdbcTemplate inserts with the columns each release writes. The test also
shows the failure you're avoiding: release 0 code against the V4 schema
breaks, which is exactly why V4 waits until release 1 is fully rolled out.
A few things the small example hides, which matter on big tables:
- Backfill in batches. One
UPDATEover millions of rows is one long transaction that holds row locks and bloats the table. Update a few thousand rows at a time, from a job or a script, and keep the migration that setsNOT NULLfor after the backfill. SET NOT NULLscans the whole table while holding an exclusive lock. On PostgreSQL 12 and later you can avoid the long lock: add aCHECK (email IS NOT NULL) NOT VALIDconstraint,VALIDATEit in a separate step, thenSET NOT NULLuses it and skips the scan.- Set a
lock_timeout. A migration waiting for a lock blocks every query that queues behind it.SET lock_timeout = '5s';at the top of a script makes it fail fast and retry later instead of taking the service down while it waits.
The same idea covers more than renames: changing a type, splitting a table, moving data to a new table. Expand first, move the code, contract last. For how this fits blue-green and canary releases, see Deployment Strategies Explained.
Flyway or Liquibase?
My personal preference is Liquibase. Flyway is the tool this post leads with because it has fewer concepts and it's what most Spring Boot tutorials start from, and everything above about expand/contract, baselining and where migrations run applies the same way to both.
Liquibase describes changes as changesets in a changelog (YAML, XML, JSON or SQL). The same schema, as Liquibase:
# src/main/resources/db/changelog/db.changelog-master.yaml (excerpt)
databaseChangeLog:
- changeSet:
id: add-orders-email
author: orders-team
changes:
- addColumn:
tableName: orders
columns:
- column: { name: email, type: VARCHAR(320) }
- changeSet:
id: drop-orders-customer-email
author: orders-team
preConditions:
- onFail: HALT
- sqlCheck:
expectedResult: 0
sql: SELECT count(*) FROM orders WHERE email IS NULL
changes:
- dropColumn: { tableName: orders, columnName: customer_email }
- changeSet:
id: index-orders-email
author: orders-team
runInTransaction: false
changes:
- sql: CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_email ON orders (email)
Swap spring-boot-starter-flyway for spring-boot-starter-liquibase and
Spring Boot runs the changelog from db/changelog/db.changelog-master.yaml
at startup, the same way. The full changelog for this post (seven changesets)
ran against PostgreSQL 17 and passed the same ddl-auto: validate check and
repository test as the Flyway version. The concurrent index worked without
any extra setting, because Liquibase locks with a row in its
DATABASECHANGELOGLOCK table instead of a database transaction.
Where Liquibase tends to earn its place:
- Changesets are identified by id, author and file, not by a version
number. Two branches adding changes at the same time don't fight over
V7. - Preconditions. The drop above refuses to run if any row still has no
email. In Flyway, that check is a SQL script you write yourself. - Rollback blocks, contexts and labels, for teams that need to undo or select changes per environment.
- One changelog for several databases, if you ship to more than one vendor.
The trade-off is more to learn, and a lock that lives in a table. If a pod is
killed in the middle of a migration, the lock row stays. The next start
waits for it, then fails, until someone clears it with
liquibase release-locks. Flyway is the
simpler pick when the team writes plain SQL against one database and wants
nothing more. Whichever you choose, choose once. Mixing the two in one
database is the worst option.
Test the migrations, not only the code
The tests in this post share one idea: run the real migrations against the
real database engine. An H2 database in PostgreSQL mode would have missed the
CREATE INDEX CONCURRENTLY hang, bpchar, and the advisory lock, because
none of them exist there. The test that loads the whole app is short:
@SpringBootTest
@Testcontainers
class MigrationsTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");
@Autowired Flyway flyway;
@Autowired PurchaseOrderRepository orders;
@Test
void migrationsMatchTheEntities() {
// The context only starts if Hibernate's ddl-auto=validate agreed with the schema.
assertThat(flyway.info().current().getVersion().getVersion()).isEqualTo("6");
assertThat(flyway.info().pending()).isEmpty();
orders.save(new PurchaseOrder("[email protected]", 4_990, "PAID"));
assertThat(orders.findByEmail("[email protected]")).singleElement()
.extracting(PurchaseOrder::getCurrency).isEqualTo("BRL");
}
}
@ServiceConnection points the datasource at the container, so there's no
URL to configure. The five Flyway tests in this post (this one, two pods,
baseline, validate-only, expand/contract) run in about 13 seconds, most of
it starting containers. Part 4 goes deeper into Testcontainers: reusing
containers across test classes, and what to do in CI. For the basics of
testing a Spring Boot app, see
Testing Your Spring Boot Application.
Checklist
ddl-autoisvalidateeverywhere except throwaway prototypes.- Every schema change is a new migration file. Applied files are never edited.
- Views, functions and grants live in repeatable
R__scripts. - The version scheme is decided, and CI blocks out-of-order versions.
- On PostgreSQL,
spring.flyway.postgresql.transactional-lockisfalse. - You know where migrations run. If it's a pipeline step, the pods only validate, and the runtime user can't run DDL.
- An existing database was baselined once, and
baseline-on-migrateis off again. - Breaking changes go through expand and contract, one release per step, with a test that walks the steps.
- Big backfills run in batches, and migrations set a
lock_timeout. - Migrations are tested against the same database engine as production.
For the table design that these migrations change, see Database Design Fundamentals.
Next in the series, Part 4 covers integration tests with Testcontainers in Spring Boot: why an in-memory database lies about production, reusable containers, and keeping CI fast.