Video in progress

Strong Middle 🧩 Microservices

How do Flyway migrations work when several pods start at the same time, and where do you run a long-running migration?

Flyway takes a lock in the DB before migrating (an advisory lock in PostgreSQL), so one pod migrates and the others wait, then continue knowing "everything is already applied". But a long migration blocks pod startup and probes may kill it, so I move such work into a separate job or a background backfill.

📖 Answer

In a rolling deploy, 3 new pods come up and all three start Flyway. Before working with flyway_schema_history, Flyway takes a lock: the first pod runs the migration, the others wait, then read the history and see there is nothing left to apply. That part is safe.

The problems are elsewhere:

  1. A long migration. Creating an index or running UPDATE on 50 million rows takes minutes. During that time the pod isn't ready and runs past the startup probe limit, so Kubernetes restarts it and the migration is cut off halfway. In PostgreSQL, DDL is transactional, so it usually rolls back; in MySQL a half-applied state can remain.

  2. Locks. Even a short ALTER TABLE takes an ACCESS EXCLUSIVE lock. If a long query is running on the table, the ALTER waits for it, and every ordinary query queues up behind the ALTER, so the old pods hang too. SET lock_timeout = '5s' at the start of the migration protects against that.

  3. CREATE INDEX CONCURRENTLY doesn't work inside a transaction. On PostgreSQL, Flyway detects such a statement and runs the script without a transaction, but don't mix it with ordinary DDL in one file (otherwise you need the mixed setting and atomicity is lost).

Where to run it:

  • small, fast schema changes: at application startup, plain Flyway;
  • heavy work: a separate Kubernetes Job before the deploy or a CI step (the flyway migrate CLI), with spring.flyway.enabled=false in the application;
  • moving data (a backfill) is not a migration: it's a job that works in chunks in the background, because it can run for hours.

And a migration must also be compatible with the old code: during a rolling deploy the old pods run against the new schema.