--- name: database-migration description: Execute safe database schema migrations — zero-downtime techniques, rollback strategies, column additions/removals, migration scripts (Flyway, Liquibase, raw SQL). license: MIT --- ## What I do Guide safe database migrations. Use when adding, modifying, or removing tables, columns, indexes. ## Principles - **Always backup** before destructive changes - **Test migrations** on production-like data - **Write reversible** when possible - **Never modify** applied migrations - **One migration** per logical change - **Keep fast**: under 30 seconds ## Common Patterns ### Add Column 1. Add nullable (or with default) 2. Update rows 3. Add NOT NULL constraint ### Remove Column 1. Stop writing to column (code deploy) 2. Migrate/drop data 3. Remove column ### Add Index Use CONCURRENTLY for PostgreSQL (avoids locks). ## Zero-Downtime Migration 1. **Dual write**: Write both old and new format 2. **Migrate**: Background job for existing data 3. **Switch**: Deploy code using new format 4. **Cleanup**: Remove old column/code ## Large Tables - Batch processing (1000-10000 rows) - Add indexes after data migration - Schedule low-traffic periods ## Rollback For each migration document: - How to detect failure - How to rollback - How to recover data ## Checklist ### Pre-Migration - [ ] Backup created - [ ] Tested on staging - [ ] Rollback plan documented - [ ] Maintenance window (if needed) ### Post-Migration - [ ] Verify data integrity - [ ] Application works - [ ] Monitor errors - [ ] Update documentation --- Use before every database migration.