How do you handle database migrations in a CD pipeline?
AdvancedConceptFundamentals and Pipeline Design
Answer
Migrations must be backward compatible with the currently running app version, because during rolling, blue-green or canary deployments old and new code run against the same database. Use the expand/contract pattern:
- Expand: add new nullable columns or tables (old code ignores them).
- Deploy code that writes both and reads the new one.
- Backfill data.
- Contract: drop the old column in a later release once no code uses it.
Run migrations as a dedicated pipeline step or a Kubernetes Job/Helm pre-upgrade hook using Flyway, Liquibase, Alembic or Rails migrations, never from many app replicas starting at once. Never ship a destructive migration in the same release as the code that stops needing it.
flyway -url=jdbc:postgresql://db:5432/app -user=$DB_USER -password=$DB_PASS migrate
More on Fundamentals and Pipeline Design
What is Continuous Integration (CI)?BeginnerWhat is the difference between Continuous Delivery and Continuous Deployment?IntermediateWhat is a CI/CD pipeline and what are its stages?BeginnerWhy should a pipeline "fail fast", and how do you order stages to achieve it?IntermediateWhat makes a build reproducible, and why does it matter?AdvancedHow does your branching strategy affect CI? Compare trunk-based development with GitFlow.Intermediate