What are Flyway and Liquibase, and how do they plug into Spring Boot?
Flyway and Liquibase are schema migration tools. Each keeps your database schema under version control by applying an ordered set of changes and recording which ones have already run. Flyway is built around plain SQL scripts with versioned filenames. Liquibase is built around a changelog, a list of changesets written in XML, YAML, JSON or annotated SQL.
Spring Boot auto-configures both. If the Flyway or Liquibase dependency is on the classpath and a DataSource is configured, Boot runs any pending migrations against that DataSource during startup. It does this before JPA and Hibernate initialize, so your entities never meet a schema that is out of date. This default is convenient, but it also means every application instance tries to migrate the database when it boots. Section 4 covers the consequences of that.
Each tool has its own configuration namespace:
spring.flyway.*:enabledturns automatic migration on or off.locationssets where scripts are found and defaults toclasspath:db/migration. Flyway has no direct equivalent of contexts, so teams usually varylocationsper environment to include extra scripts.spring.liquibase.*:enabledturns it on or off, andchange-logpoints to the master changelog file.contextsfilters which changesets run, which is useful for seed data that should exist only in test environments.
Both namespaces also accept their own url and user settings. This lets migrations run with a privileged account while the application connects with a restricted one.
The tools differ in syntax and features, as the later sections show. In practice, team habits decide whether migrations go smoothly more than the choice of tool does. Those habits include never editing a script after it has been applied, keeping each change small, and making sure old and new application versions can both work with the schema.
# application.yml: pick ONE tool per application. Both blocks are shown here for comparison.
spring:
datasource:
# Restricted account the application uses at runtime (DML only)
url: jdbc:postgresql://localhost:5432/orders
username: orders_app
password: ${APP_DB_PASSWORD}
flyway:
enabled: true
# Default location, stated explicitly for clarity
locations: classpath:db/migration
# Privileged account used only for migrations (DDL rights)
url: jdbc:postgresql://localhost:5432/orders
user: orders_migrator
password: ${MIGRATOR_DB_PASSWORD}
liquibase:
# Disabled because Flyway owns this schema. Never let both tools migrate the same database.
enabled: false
change-log: classpath:db/changelog/db.changelog-master.yaml
# Only changesets tagged with these contexts (or untagged ones) run
contexts: prod
---
# Test profile: Flyway has no contexts, so add a second location that holds seed data scripts
spring:
config:
activate:
on-profile: test
flyway:
locations: classpath:db/migration,classpath:db/testdata
liquibase:
# Liquibase equivalent of the same idea, applied if it were the enabled tool
contexts: test
An application.yml that shows the spring.flyway. and spring.liquibase.* namespaces side by side: enablement, script locations and the changelog path, a separate privileged migration account, and per-profile seed data handled through Flyway locations or Liquibase contexts.*
How do Flyway and Liquibase track and apply schema migrations?
Flyway's model is a numbered sequence of files. A script named V3__add_order_status.sql runs once, in version order. Repeatable scripts prefixed R__ have no version. They run after the pending versioned scripts and run again whenever their content changes, which suits views and stored procedures that you redefine in full each time. Liquibase's model is a changelog, written in XML, YAML, JSON or formatted SQL, made up of changesets. Each changeset is identified by its id, its author and the path of the changelog file. Liquibase decides what has already run by that identity, not by file order.
| Aspect | Flyway | Liquibase |
|---|---|---|
| Unit of change | Versioned V or repeatable R script |
Changeset in a changelog |
| Identity | Version number | id + author + file path |
| Tracking table | flyway_schema_history (default) |
DATABASECHANGELOG |
| Re-run on edit | R__ scripts only |
Changesets marked runOnChange |
Both tools store a checksum for every applied change. On the next run they compare it with the current file and fail validation if the two differ. A mismatch means the history recorded in the database no longer matches the source, so environments may have diverged without anyone noticing. The right response is to revert the edit and put the intended change in a new migration.
Checksums have a cost. Depending on how each tool normalises content, a whitespace edit or an editor that converts line endings can block a deploy even though the SQL means the same thing. Flyway's repair and Liquibase's checksum-clearing commands exist for these cases. Teams that reach for them routinely end up hiding genuine drift between environments.
-- ===== Flyway: db/migration/V3__add_order_status.sql =====
-- Already applied in production. Its checksum is stored in flyway_schema_history,
-- so editing this file would fail validation on the next run.
ALTER TABLE orders ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'NEW';
-- ===== Flyway: db/migration/V4__widen_order_status.sql =====
-- Fix forward: the correction goes in a new version instead of an edit to V3.
ALTER TABLE orders ALTER COLUMN status TYPE VARCHAR(40);
-- ===== Flyway: db/migration/R__order_summary_view.sql =====
-- Repeatable: no version. It runs after pending V scripts and runs again
-- whenever its checksum changes, so the full definition lives here.
CREATE OR REPLACE VIEW order_summary AS
SELECT id, customer_id, status FROM orders;
-- ===== Liquibase: db/changelog/orders.sql (formatted SQL changelog) =====
--liquibase formatted sql
-- Identity is author:id plus this file's path, recorded in DATABASECHANGELOG.
--changeset alice:add-order-status
ALTER TABLE orders ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'NEW';
--rollback ALTER TABLE orders DROP COLUMN status;
-- Fix forward with a new changeset; do not edit the one above.
--changeset alice:widen-order-status
ALTER TABLE orders ALTER COLUMN status TYPE VARCHAR(40);
-- runOnChange re-applies this changeset when its checksum changes,
-- the Liquibase counterpart to a Flyway R__ script.
--changeset alice:order-summary-view runOnChange:true
CREATE OR REPLACE VIEW order_summary AS
SELECT id, customer_id, status FROM orders;
The same schema change written as Flyway versioned and repeatable scripts and as Liquibase changesets, with the correction added as a new migration instead of editing one that was already applied.
When should you choose Flyway vs Liquibase for a Spring Boot service?
Pick based on how your team already reasons about schema changes, not on feature count.
| Criterion | Flyway | Liquibase |
|---|---|---|
| Authoring model | Plain SQL files, versioned by filename | Changelog in XML, YAML, JSON or SQL; abstract change types |
| Multiple database engines | One script set per engine | One changelog can target several engines |
| Conditional execution | Minimal; handled in SQL | Preconditions, contexts, labels |
| Bootstrapping from an existing schema | Baseline, then write SQL by hand | Can generate a changelog from a live database |
| Review by a DBA | The file is the SQL that runs | Reviewer must check the generated SQL |
Flyway suits SQL-first teams on a single engine. Each migration is a script a DBA can read, run in a console, and approve without learning a new format.
Liquibase suits teams that ship one product against several engines, need to gate changes per environment with contexts or labels, or want an initial changelog generated from an existing schema. The abstraction has costs. Changesets are verbose. The generated SQL can differ from what you expected, such as a different column type or constraint name. Many teams end up writing raw SQL changesets for anything non-trivial, which gives up the portability that justified the tool. Check the current edition matrix before committing to either tool. Undo migrations, dry-run output and drift reports have been tied to paid editions.
Hand-rolled scripts work until you need ordering, locking and history, and then you rebuild one of these tools. Hibernate's ddl-auto is unsuitable for production. It keeps no history and cannot express a rename or a data backfill. It also never drops what it no longer recognizes, and it lets entity changes alter the schema with no review.
Should migrations run at application startup or as a separate job?
…schema on whatever instance happens to boot first. That raises the next question: where should the real migration tool run? Spring Boot's default is to run Flyway or Liquibase during startup, before the application context finishes initializing.
Concurrent startup and locks
When a Deployment scales to several replicas, every pod tries to migrate at the same moment. Both tools serialize this with a lock. Flyway takes a database-level lock for the duration of the run. Liquibase sets LOCKED to true in a single row of the DATABASECHANGELOGLOCK table and records LOCKEDBY and LOCKGRANTED. The other instances poll until the lock is released.
Liquibase's lock is ordinary data, so it outlives the process that took it. If a pod is OOM-killed or evicted mid-migration, the row stays locked. Every later instance then waits and fails to acquire the changelog lock. Before clearing it, check the LOCKEDBY host and confirm that pod is gone. Also check the database's active sessions for a migration that is still running. Then reset the row or use Liquibase's release-locks command. If you release a lock held by a live migration, two writers will apply changesets at the same time.
Startup migrations in Kubernetes
A long backfill can outlast the startup or liveness probe. The kubelet then kills the pod mid-migration and restarts it. A broken changeset fails identically on every replica, so the whole rollout crash-loops.
The safer pattern is to run migrations once, from a dedicated Kubernetes Job or pipeline step, before the new Deployment rolls out. Set spring.flyway.enabled=false or spring.liquibase.enabled=false in the application itself. Init containers are better than in-app startup migrations, but they still run once per pod.
# Run migrations once per release, before the new Deployment rolls out.
apiVersion: batch/v1
kind: Job
metadata:
name: orders-migrate-1-4-2 # one Job per release version
spec:
backoffLimit: 0 # a broken changeset should fail once, not retry in a loop
activeDeadlineSeconds: 3600 # long backfills are bounded by this, not by app probes
template:
spec:
restartPolicy: Never
containers:
- name: flyway
# Image built FROM the Flyway CLI image with this release's SQL copied into /flyway/sql
image: registry.example.com/orders-migrations:1.4.2
args: ["migrate"]
env:
- name: FLYWAY_URL
value: jdbc:postgresql://orders-db:5432/orders
- name: FLYWAY_LOCATIONS
value: filesystem:/flyway/sql
- name: FLYWAY_USER
valueFrom: { secretKeyRef: { name: orders-db-migrator, key: username } }
- name: FLYWAY_PASSWORD
valueFrom: { secretKeyRef: { name: orders-db-migrator, key: password } }
---
# Excerpt from the application Deployment: the app never migrates on startup.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders
spec:
template:
spec:
containers:
- name: app
image: registry.example.com/orders:1.4.2
env:
- name: SPRING_FLYWAY_ENABLED # or SPRING_LIQUIBASE_ENABLED
value: "false"
A one-shot Kubernetes Job runs Flyway migrations with no retries and its own deadline, and the application Deployment disables startup migrations through Spring Boot's relaxed-binding environment variable.
Why is rollback a forward-fix problem in both tools?
Liquibase can generate rollback statements automatically for structural changes whose inverse is unambiguous, such as createTable, addColumn, or renameColumn. For dropTable, raw sql, or data changes, you must write an explicit rollback block in the changeset. Flyway's undo migrations are available only in its commercial editions, not the open-source one. Neither tool can recover information that a migration destroyed. If a down migration re-adds a dropped column, the column comes back empty. If a migration merged first_name and last_name into full_name, reversing it means guessing where to split. Only a backup or a retained copy of the data can restore it.
Rollback scripts also rarely run until an incident, so the first time they execute is under pressure against production data. A forward fix is safer because it goes through the same review and test pipeline as every other migration: a new migration that corrects the schema or restores compatibility.
Partial failure depends on the database. PostgreSQL runs most DDL inside a transaction, so a failed migration rolls back cleanly. CREATE INDEX CONCURRENTLY is an exception because it cannot run inside a transaction block. MySQL commits each DDL statement implicitly. If the third statement of a migration fails, the first two stay applied, and Flyway records the migration as failed. You then have to reconcile the schema by hand before running repair. Liquibase leaves the changeset unrecorded, so rerunning it collides with the objects that were already created.
For this reason, each migration should contain one logical change. When it fails, there is only one thing to inspect and only one thing to fix forward.
databaseChangeLog:
# One logical change per changeSet, so a failure has one thing to inspect.
- changeSet:
id: 001-add-full-name
author: alice
changes:
# addColumn has an unambiguous inverse, so Liquibase can generate the rollback.
- addColumn:
tableName: customer
columns:
- column:
name: full_name
type: varchar(255)
- changeSet:
id: 002-backfill-full-name
author: alice
changes:
# Raw SQL has no automatic inverse, so the rollback must be written explicitly.
- sql:
sql: UPDATE customer SET full_name = CONCAT(first_name, ' ', last_name)
rollback:
# Safe only because first_name and last_name still exist at this point.
- sql:
sql: UPDATE customer SET full_name = NULL
- changeSet:
id: 003-drop-first-name
author: alice
changes:
- dropColumn:
tableName: customer
columnName: first_name
rollback:
# The column comes back structurally but empty. The data is gone.
- addColumn:
tableName: customer
columns:
- column:
name: first_name
type: varchar(100)
A Liquibase YAML changelog with one logical change per changeSet. It shows an auto-generated rollback for addColumn, an explicit rollback for raw SQL, and a dropColumn rollback that restores the column's structure but not its data.
How do you implement zero-downtime expand/contract migrations in Flyway and Liquibase?
Parallel change follows the same principle as one change per migration, but it spreads a single rename or type change across several releases. Take renaming users.email to users.email_address:
- Expand. Add
email_addressas a nullable column. Nullable matters because old application instances are still inserting rows without it, and aNOT NULLconstraint would make their inserts fail. - Backfill. Copy
emailintoemail_addressin batches. A singleUPDATEover a large table can hold locks long enough to stall live traffic. - Dual-write. Deploy code that writes both columns and reads the new one. Old and new instances can now run side by side.
- Contract. In a later release, after no running version reads
email, drop it and add any constraints toemail_address.
In Flyway, each step is its own versioned script: V20__add_email_address.sql, V21__backfill_email_address.sql, and later V24__drop_email.sql. In Liquibase, each step is a separate changeset: addColumn, then an sql or update changeset for the backfill, then dropColumn in a later changelog file. Each step has its own ID, so a failure stays isolated to one step.
Out-of-order migrations from parallel branches
The two tools handle parallel branches differently:
- Flyway orders migrations by version. If branch A merges
V22afterV23has already been applied, validation fails. You can setspring.flyway.out-of-order=trueto apply it anyway, but that hides real ordering dependencies. - Liquibase identifies changesets by ID, author, and file path, and runs any changeset it hasn't run before. That makes merges easier, but execution order follows the changelog's include order, so a merge conflict there is a schema question, not just a text conflict.
Teams need a few procedures to handle this:
- Use timestamp-based versions or IDs.
- Add a CI check that rejects a migration older than what's on main.
- Renumber a migration only if it has never been applied anywhere.
How do you test migrations and adopt a tool on an existing database?
Run migrations in CI against the same database engine and major version you use in production, started in a container for each build. An in-memory substitute accepts different SQL, handles types and defaults differently, and does not reproduce locking. A migration can pass against it and still fail on the real engine during a deploy. The container adds some build time, but it tests the SQL that will actually run.
In the same test run, set spring.jpa.hibernate.ddl-auto=validate. After Flyway or Liquibase applies the migrations, Hibernate compares the resulting schema with your entity mappings and fails startup if a table or column is missing, or if a column type is wrong. This catches cases where an entity was changed without a matching migration, or a migration was added without updating the entity.
Adopting a tool on an existing database
Flyway: Run baseline, or enable spring.flyway.baseline-on-migrate. This records the current schema as a starting version, so Flyway applies only migrations numbered above it.
Liquibase: Use generate-changelog to produce a changelog from the live schema, then review and clean it up. Run changelog-sync against existing environments to mark those changesets as applied without executing them.
Switching tools and where the time goes
Switching tools later in a service's life means re-baselining every environment and keeping two history tables until the old one is removed. The migration files themselves are often the smaller part of the work. Pick a tool once and keep it.
The time savings do not come from writing SQL faster. They come from:
- Drift caught in CI instead of found in production.
- Schema changes reviewed in pull requests like any other code.
- Fewer failed deploys, because each migration has already run against a real database before release.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to flyway vs liquibase spring boot, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.