What are Flyway and Liquibase, and how does each model a migration?
Both tools solve the same problem: they turn schema changes into an ordered, versioned history that every environment replays the same way. Each tool records what it has applied in a tracking table in the target database. On each run it applies only what is missing and verifies checksums, so a script that was edited after it ran gets flagged instead of silently drifting.
Flyway models a migration as a file whose name carries its identity. A versioned script such as V3__add_customer_email.sql runs once, in version order. A repeatable script (prefix R__) has no version and reruns whenever its checksum changes, which suits views and stored procedures. Migrations can also be written in Java when SQL is not enough, such as for data backfills that need application logic.
Liquibase models a migration as a changeset inside a changelog. Each changeset is identified by its id, its author, and the changelog file path. Changelogs can be written in XML, YAML, JSON, or "formatted SQL". The structured formats use database-agnostic change types such as addColumn, which Liquibase translates into dialect-specific SQL.
Here is the same change in each tool:
| Aspect | Flyway | Liquibase |
|---|---|---|
| Unit of change | Versioned or repeatable script | Changeset in a changelog |
| Identity | Version in filename (V3) |
id + author + file path |
| Example | V3__add_customer_email.sql containing ALTER TABLE customer ADD COLUMN email VARCHAR(255); |
--changeset alice:3 followed by the same ALTER TABLE, or a YAML addColumn change |
| Tracking table | flyway_schema_history |
DATABASECHANGELOG |
Both tools split features between open-source and commercial editions. Check the licensing terms for the edition you run before you design a workflow around a specific capability.
-- File 1 (Flyway): src/main/resources/db/migration/V3__add_customer_email.sql
-- The filename is the identity: version 3, applied once, in version order.
ALTER TABLE customer ADD COLUMN email VARCHAR(255);
-- File 2 (Flyway): src/main/resources/db/migration/R__customer_contact_view.sql
-- Repeatable script: no version. Flyway reruns it whenever its checksum changes,
-- so the definition must be safe to apply again (hence CREATE OR REPLACE).
CREATE OR REPLACE VIEW customer_contact AS
SELECT id, name, email FROM customer;
-- File 3 (Liquibase): src/main/resources/db/changelog/changes/003-add-customer-email.sql
-- Make sure the master changelog includes this file.
-- The first line marks the file as a Liquibase formatted SQL changelog.
-- The changeset identity is author:id (alice:3) plus this file's path.
--liquibase formatted sql
--changeset alice:3
ALTER TABLE customer ADD COLUMN email VARCHAR(255);
--rollback ALTER TABLE customer DROP COLUMN email;
The same column addition as a Flyway versioned script and as a Liquibase formatted-SQL changeset, plus a Flyway repeatable script for a view. In Flyway the filename identifies the migration; in Liquibase the changeset header identifies it.
How does a migration run work?
Flyway and Liquibase follow the same basic loop each time they run, whether they are triggered by Spring Boot, a CLI, or a build plugin:
- Connect and lock. The tool connects to the target database and takes a lock so that only one process migrates at a time. Liquibase uses its
DATABASECHANGELOGLOCKtable. Flyway uses a database-level lock where the engine supports one. - Ensure the tracking table exists. On first run against an empty schema, the tool creates
flyway_schema_historyorDATABASECHANGELOG. - Discover migrations. Flyway scans its configured locations and sorts versioned scripts by version. Liquibase reads the master changelog and follows its includes in order.
- Compare with history. Each discovered migration is matched against the tracking table. Applied migrations have their checksums recomputed and compared with the stored values. A mismatch stops the run.
- Apply what is pending. Each pending migration runs in order. On engines with transactional DDL, such as PostgreSQL, a migration's statements can run inside a transaction, so a failure rolls back cleanly. On engines without it, such as MySQL, a failure can leave partial changes behind.
- Record the result. After each migration, the tool writes a row with its identity, checksum and outcome, then releases the lock.
Because every environment runs this same loop against the same files, the tracking table becomes a reliable answer to the question "what state is this database in?"
Who should use Flyway or Liquibase?
A migration tool fits any team that owns a relational schema that changes over time and is deployed to more than one place. In practice that includes:
- Backend teams running Spring Boot services with their own database, who want schema changes to ship and be reviewed alongside the code that needs them.
- Teams with several environments (developer laptops, CI, staging, production) that must end up with the same schema.
- Platform and DBA groups that need an auditable record of who changed what and when, in the database itself.
Between the two, Flyway suits teams that are comfortable writing and reviewing raw SQL for one engine. Liquibase suits teams that want a structured, database-agnostic format, need to target several engines, or must declare rollback paths. The decision table near the end of this article covers this in more detail.
A tool adds little for a single throwaway database owned by one person, or for a prototype whose schema an ORM regenerates from scratch.
When should you use a migration tool?
Introduce one as soon as any of the following is true:
- More than one environment or more than one developer touches the schema.
- Schema changes need code review before they reach production.
- The application runs as several instances, so you need a single, serialized place where DDL is applied.
- You need to rebuild a database from scratch, such as for CI or a new region, and get exactly the production schema.
The cheapest time to adopt a tool is at the start of a project, when the first migration can create the whole schema. For an existing database, both tools can baseline at the current state (spring.flyway.baseline-on-migrate, or an initial Liquibase changelog that describes the existing schema), and history is recorded from that point forward.
How do Spring Boot migrations work with Flyway and Liquibase?
Spring Boot's auto-configuration activates when it finds flyway-core or liquibase-core on the classpath along with a DataSource. Migrations then run as part of context initialization. Beans that need the schema, such as the JPA EntityManagerFactory, are made to depend on the migration bean, so Hibernate never validates against a half-migrated database. If a migration fails, the context fails and the application does not start.
Each tool is configured under its own namespace:
- Flyway reads versioned SQL files from
classpath:db/migrationby default. You can change that withspring.flyway.locations, turn it off withspring.flyway.enabled=false, or adopt an existing database withspring.flyway.baseline-on-migrate=true. - Liquibase starts from a single master changelog set by
spring.liquibase.change-log(defaultclasspath:/db/changelog/db.changelog-master.yaml). It also supportsspring.liquibase.enabledandspring.liquibase.contexts.
Both tools store a checksum for every applied migration. Flyway writes it to flyway_schema_history. Liquibase writes it to DATABASECHANGELOG, keyed by changeset id, author and file path. On the next run, each tool recomputes the checksums and compares them with the stored values. If you edit a file that has already been applied, validation fails and startup stops. This is intentional: the database no longer matches the history you claim produced it.
Both tools provide an escape hatch. Flyway has repair and Liquibase has clearCheckSums, and either one realigns the stored checksums with the current files. Neither changes the schema. If you run repair just to make an error go away, staging may keep the old DDL while production gets the new DDL, and both will report a clean history. A safer default is to fix a bad applied migration with a new forward migration and to reserve repair for cases you have actually investigated.
spring:
datasource:
url: jdbc:postgresql://localhost:5432/orders
username: orders_app
password: ${DB_PASSWORD} # injected from the environment, never committed
# --- Flyway (flyway-core on the classpath) ---
flyway:
enabled: true
# Versioned scripts such as V1__create_orders.sql live here.
locations: classpath:db/migration
# Only for adopting a database that already has tables.
# Leave false on greenfield schemas.
baseline-on-migrate: false
# Default is true. Keep it: an edited, already-applied script
# should fail startup instead of passing silently.
validate-on-migrate: true
# --- Liquibase (liquibase-core on the classpath) ---
# liquibase:
# enabled: true
# # Master changelog that includes the other changelog files.
# change-log: classpath:/db/changelog/db.changelog-master.yaml
# # Runs changesets with no context, plus changesets tagged 'prod'.
# contexts: prod
jpa:
hibernate:
# Hibernate checks the schema only after migrations finish,
# because the EntityManagerFactory depends on the migration bean.
ddl-auto: validate
A minimal application.yml for Flyway and, commented out, Liquibase, using only standard spring.flyway. and spring.liquibase.* properties, with checksum validation left on and Hibernate set to validate the schema only after migrations have run.*
Can you roll back a migration in Flyway or Liquibase?
In Flyway's community edition, the model is roll-forward only. Undo migrations are not part of it, so a bad V7__add_status.sql is fixed by shipping V8__fix_status.sql. The history table then records both the mistake and the correction, in the order each environment applied them. That record is accurate, which matters later when production, staging and a developer laptop need to agree on what happened.
Liquibase lets each changeset carry a rollback block. For some change types, such as creating a table or adding a column, it can generate the inverse itself. For raw SQL or destructive changes you write the inverse by hand, or mark the changeset as having none. You can then roll back to a tag or by a count of changesets.
The weakness is that rollback blocks are code that rarely runs. A rollback written alongside the change is almost never executed against production-shaped data. It may reference a column a later changeset renamed, or recreate a constraint that existing rows now violate. You find this out during an incident.
No tool can recover data that a migration destroyed. A rollback for dropColumn can re-add the column, but it comes back empty. The same applies to a destructive UPDATE: you need a backup or a copy you made before the change.
Side by side, the roll-forward fix is a new migration that restores the intended state, going through the same review and CI as any other change. The Liquibase rollback block is an inverse that is tested only if you deliberately test it. In practice, a roll-forward fix is the recovery path you can trust. Keep rollback blocks for genuinely reversible changes, and verify them in CI by applying each changeset, rolling it back and applying it again.
-- ===== Flyway (roll-forward): db/migration/V8__fix_status.sql =====
-- V7 shipped status with the wrong default. V7 stays in history;
-- this new migration corrects state and goes through normal review/CI.
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'pending';
-- Repair only rows V7 backfilled, identified by a known cutoff.
UPDATE orders
SET status = 'pending'
WHERE status = 'active'
AND shipped_at IS NULL;
-- ===== Liquibase (rollback block): changelog/orders.sql =====
--liquibase formatted sql
--changeset dev.team:orders-7
ALTER TABLE orders ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';
-- Reversible in schema terms, but any status values written after
-- deploy are discarded when this rollback runs.
--rollback ALTER TABLE orders DROP COLUMN status;
--changeset dev.team:orders-8
ALTER TABLE orders DROP COLUMN legacy_note;
-- This 'inverse' restores the column, not the data: every row comes
-- back NULL. Only a backup taken before the drop can recover values.
--rollback ALTER TABLE orders ADD COLUMN legacy_note TEXT;
A Flyway roll-forward fix shipped as a new versioned migration, shown next to Liquibase formatted-SQL rollback blocks, one of which re-adds a dropped column empty and cannot recover the data that was in it.
Why should you avoid running migrations on application startup at scale?
Both tools serialize migrations with a lock. Liquibase writes a row to its DATABASECHANGELOGLOCK table. Flyway relies on a database-level lock, such as an advisory lock on PostgreSQL. With twenty replicas starting at once, one wins the lock and migrates while the other nineteen block. That is safe, but it has costs.
Migrating on startup couples deploy success to migration success. A slow ALTER TABLE on a large table makes every pod wait. That wait can exceed readiness or liveness probe timeouts, so the orchestrator restarts pods mid-migration. A deploy that should change application code becomes a schema operation spread across your whole fleet.
Crashes are the worse case. If a pod is killed while holding the Liquibase lock, the row stays locked. Every later instance waits and then fails until someone runs releaseLocks. Flyway has a similar failure mode. On databases without transactional DDL, such as MySQL, a half-applied migration leaves a failed entry in flyway_schema_history. Flyway then refuses to proceed until you clean up the partial changes and run repair. Until then, no new instance can start.
The alternative is to run migrations once, as a dedicated pipeline step. Disable them in the application with spring.flyway.enabled=false or spring.liquibase.enabled=false.
build image
│
▼
migration job (same image, migrate only) ──fail──► stop deploy
│ success
▼
rolling update of app replicas (migrations disabled)
Prefer a single job over a per-pod init container. An init container still runs once per replica, which brings back the lock contention described above.
apiVersion: batch/v1
kind: Job
metadata:
name: orders-migrate-1-4-2
spec:
backoffLimit: 0 # a failed migration should stop the deploy, not retry blindly
activeDeadlineSeconds: 1800 # fail the pipeline step instead of hanging on long DDL
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: registry.example.com/orders-service:1.4.2
env:
# Run Flyway during context startup, but start no web server.
# The JVM exits after startup only if nothing else keeps it alive
# (schedulers, message listeners), so keep those off here.
- name: SPRING_FLYWAY_ENABLED
value: "true"
- name: SPRING_MAIN_WEB_APPLICATION_TYPE
value: "none"
- name: SPRING_DATASOURCE_URL
value: jdbc:postgresql://orders-db:5432/orders
- name: SPRING_DATASOURCE_USERNAME
value: orders_migrator # account with DDL rights
- name: SPRING_DATASOURCE_PASSWORD
valueFrom:
secretKeyRef:
name: orders-db-migrator
key: password
A Kubernetes Job that runs the application image once with Flyway enabled and the web server off, so the pipeline can gate the rolling update on its success while app replicas start with migrations disabled.
How do you write backward-compatible migrations for rolling deployments?
During a rolling update, old and new replicas run against the same schema at the same time, so every migration must work with both versions of the code. A direct rename or drop breaks the replicas that have not been updated yet. The expand-and-contract pattern avoids this by splitting one breaking change into several compatible steps. Here is how renaming email to email_address maps to migration files and releases:
V12__add_email_address.sqladdsemail_addressas a nullable column. Old code ignores it. Ship code that writes to both columns and still readsemail.V13__backfill_email_address.sqlcopies the existing values. On large tables, run the copy in batches, possibly as a separate job, so you don't hold one long transaction.- Next release: switch reads to
email_addressand keep the dual writes, so you can still roll back to the previous code. - Next release: stop writing
email. V14__drop_email.sql, shipped in a later release, removes the old column once no running version references it.
Neither Flyway nor Liquibase makes DDL online. Each one runs the statement you give it. Building an index or altering a large table can block writes for the full duration of the operation, so you still need engine-specific techniques:
- PostgreSQL:
CREATE INDEX CONCURRENTLYcannot run inside a transaction, so that migration must be configured to run non-transactionally. - MySQL: use
ALGORITHM=INPLACE, LOCK=NONEwhere the operation supports it.
Also set a lock timeout, so that a blocked migration fails quickly instead of queuing behind live traffic.
How do you vary and test migrations across environments without forking history?
Both tools let you keep one ordered migration history and still vary what runs per environment.
Environment-specific changes in one history
In Liquibase, you tag changesets with a context (for example dev or test) or a label, and pass the active values at runtime through spring.liquibase.contexts or the label filter. Contexts are the usual choice for environment selection. Labels suit feature or release grouping. Untagged changesets run everywhere, so the shared schema stays identical and only seed or fixture data differs.
In Flyway, you get the same effect with spring.flyway.locations. Production reads only the main migration directory. Development adds a second directory for seed scripts. Keep versioned migrations in the main directory. Versioned scripts that exist only in some environments create version gaps elsewhere and confuse validation, so put dev-only data in repeatable or clearly separated scripts. Use placeholders (spring.flyway.placeholders.*) for values that genuinely differ, such as a schema owner or a grant target. Copying a script per environment is the fork you are trying to avoid.
Test against the real engine
In CI, run every migration against the same database engine you run in production, typically in a container. Run it twice:
- From an empty schema, to prove the full history still applies cleanly.
- Against a sanitized, production-like snapshot, to catch constraint violations, slow backfills and long-held locks that only appear with real data.
In-memory substitutes such as H2 cannot do this job. They emulate dialects loosely and accept SQL your production engine rejects. They also have different transactional-DDL and locking semantics, so a migration that passes there can still block writes in production.
A migration that fails in CI costs a rerun. The same failure in production means an incident, manual repair of the schema history table, and a hand-written fix under pressure.
How can a migration tool save engineering time?
The time savings come from removing manual, error-prone steps and from catching problems before they reach production:
- No hand-applied DDL per environment. Engineers commit a migration once. Every environment applies it automatically on the next deploy, instead of someone running scripts against each database and remembering which ones already ran.
- Faster diagnosis of drift. The tracking table and checksum validation answer "which changes does this database have?" directly. Without them, that question means diffing schemas by hand.
- Reproducible environments on demand. A new developer, a CI job or a fresh staging database gets the current schema by running the history from empty, with no shared dump to keep up to date.
- Schema changes reviewed like code. Migrations live in the same pull request as the application change, so reviewers see both together and problems surface before deploy rather than during it.
- Fewer production incidents to clean up. Running the same migrations in CI against the real engine moves failures to the point where they cost a rerun.
An illustrative estimate, using assumed inputs rather than measured data: assume a team ships 3 schema changes per week across 4 environments, and that applying and verifying one change by hand takes 10 minutes per environment. That is 3 × 4 × 10 = 120 minutes per week of manual work, before counting any time spent investigating environments that missed a script. With a migration tool, the per-environment step becomes part of the existing deploy, leaving only the time to write and review the migration itself. Substitute your own change rate, environment count and per-change effort to judge whether the numbers matter for your team.
Flyway vs Liquibase: which should your team choose, and what are the alternatives?
The choice comes down to four questions about your team and your estate.
| Criterion | Lean Flyway | Lean Liquibase |
|---|---|---|
| Team SQL fluency | Engineers and DBAs write and review SQL daily | Engineers prefer a structured, declarative format |
| Database vendors | One engine per service | Several engines from the same changelog |
| Rollback | Roll forward with fix migrations | Structured rollback blocks are a requirement |
| Audit and review | Reviewers want the exact SQL that will run | Reviewers want typed changesets with metadata such as author and context |
Choose Flyway if your team is SQL-first and rolls forward on a single engine. Choose Liquibase if you need database-agnostic changelogs or declared rollback paths.
The real cost is in daily development. Plain SQL is easy to review in a pull request and matches what a DBA sees in a slow-query log. However, it ties you to one dialect. An abstract changelog is portable, but it adds a layer that people have to learn. When a generated statement locks a table unexpectedly, you have to debug through that layer.
Switching tools late is rarely worth it. The new tool has no record of past changes, so you have to baseline every environment at a known version. Any environment whose schema differs from that baseline becomes a history mismatch that surfaces later as a failed or skipped migration.
There are alternatives:
- Hand-run SQL scripts work for a single database that changes rarely and has one owner.
- ORM-managed schema generation suits prototypes and throwaway test databases.
Once multiple instances, environments, or reviewers touch the schema, you need ordered, recorded migrations.
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, 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.