Video in progress
A service runs in 6 pods and a Flyway migration runs at startup. In a multi-instance deploy, who should run the migrations and when?
If pods migrate at startup, Flyway uses a lock so one of them runs it, but a long migration blocks startup and the probes kill the pod. It is more reliable to run the migration as a separate job (init/pre-deploy) and to make every migration compatible with both the old and the new code (expand/contract).
📖 Answer
In Boot, Flyway runs at application startup by default. If 6 pods come up at once, Flyway allows only one through using a lock in the database, and the rest wait. For small migrations this works. The problems show up in a big system:
- A 20-minute index build or backfill: the startup probe kills the pod, and the next pod starts over.
- If a migration fails halfway (DDL is not transactional in databases like MySQL and Oracle), all pods fall into
CrashLoopBackOff. - The application user needs DDL permissions, which is bad from a security point of view.
The scheme I recommend:
- Migration as a separate step. A Kubernetes
Job(Helm pre-upgrade hook) or a step in the CI/CD pipeline, using a separate user with DDL permissions. In the application:spring: flyway: enabled: false # or only validate with validate-on-migrate - Every migration is backward compatible. During a rolling deploy the old and new versions run at the same time, so the schema has to fit both:
- expand: add the new column/table (nullable or with a default);
- code: write to both columns, read from the new one;
- backfill: separately, in batches;
- contract: drop the old column in the next release.
- Heavy operations:
CREATE INDEX CONCURRENTLY(it can't run inside a transaction, so for that script you have to turn off the transaction in Flyway), and big backfills are a controlled background job, not a migration. - Lock timeout.
SET lock_timeout = '5s', so anALTER TABLEdoesn't sit in the queue behind a long query and block the whole table.
A rule for teams: a migration PR goes through the review question "is this migration safe while the old version is still running?" I back that up with a checklist and an automatic linter (for example, forbidding adding a NOT NULL column without a default).
Sign up to mark studied questions and save your progress.