{"data":{"slug":"discovered-ebdd0b3e7da011816f01cb77f9f503a741545f160128b7e6","title":"Database Migrations \u2014 Safety Patterns","summary":"Apply safe database migration strategies to avoid outages, ensure rollback capability, and prevent lock contention during schema changes. This includes parallel change patterns, chunked backfills, and non-blocking index creation.","url":"https:\/\/skillshunter.net\/skills\/discovered-ebdd0b3e7da011816f01cb77f9f503a741545f160128b7e6","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-ebdd0b3e7da011816f01cb77f9f503a741545f160128b7e6","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-ebdd0b3e7da011816f01cb77f9f503a741545f160128b7e6.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-ebdd0b3e7da011816f01cb77f9f503a741545f160128b7e6\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Always invoke this skill before writing or executing a schema migration on any environment with data. Migration files are append-only once merged; editing them rewrites history and can cause production drift. Each migration must have both `up` and `down` steps, or a documented reason for no rollback.","instructions":"---\nname: database-migrations\nversion: 1.0.0\ndescription: Safe database migrations under load \u2014 backfills, concurrent indexes, lock timeouts, parallel-change pattern, rollback strategy. Invoke before writing or running any schema migration.\n---\n\n# Database Migrations \u2014 Safety Patterns\n\n**ALWAYS invoke before writing or executing a schema migration on any environment with data.**\n\n> A migration that locks the table for 90 seconds at 1k writes\/sec creates a 90,000-request outage. The only safe migration is one that ships in pieces.\n\n## The Cardinal Rule: Parallel Change\n\nFor any non-trivial schema change, deploy in **at least two releases**:\n\n```\nRelease N   \u2192 expand:  add new column\/table, dual-write, leave old\nRelease N+1 \u2192 migrate: backfill data\nRelease N+2 \u2192 contract: drop old, switch reads\n```\n\nNever combine expand + contract in one deploy. You will regret it the moment you need to roll back.\n\n---\n\n## 1. Adding a Column\n\n### NOT NULL with default\n\nPostgreSQL \u2265 11 \/ MySQL 8 \/ MariaDB 10.5+: `ADD COLUMN ... NOT NULL DEFAULT ...` is fast (metadata-only). On older versions or other engines, it rewrites the whole table.\n\n**Safe pattern (works on any version):**\n```sql\n-- Step 1 (release N): nullable, no default \u2192 instant\nALTER TABLE users ADD COLUMN plan VARCHAR(20);\n\n-- Step 2 (release N): app dual-writes \u2014 sets plan on every INSERT\/UPDATE\n-- Step 3 (release N+1): backfill in chunks (see \u00a73)\n-- Step 4 (release N+2): set NOT NULL + default\nALTER TABLE users ALTER COLUMN plan SET NOT NULL;\nALTER TABLE users ALTER COLUMN plan SET DEFAULT 'free';\n```\n\n### Generated columns\nPrefer over backfilling derived data when possible \u2014 DB keeps it consistent.\n\n---\n\n## 2. Adding an Index\n\nIndexes lock the table during build on most engines.\n\n### PostgreSQL\n```sql\n-- WRONG \u2014 exclusive lock for the duration\nCREATE INDEX idx_users_email ON users(email);\n\n-- CORRECT \u2014 non-blocking\nCREATE INDEX CONCURRENTLY idx_users_email ON users(email);\n-- Caveats: cannot run inside a transaction; on failure leaves invalid index \u2014 drop with `DROP INDEX CONCURRENTLY`\n```\n\n### MySQL \/ MariaDB\nInnoDB \u2265 5.6 supports `ALGORITHM=INPLACE, LOCK=NONE` for most index types:\n```sql\nALTER TABLE users ADD INDEX idx_email (email), ALGORITHM=INPLACE, LOCK=NONE;\n```\n\nIf `LOCK=NONE` fails, the engine tells you why (e.g. fulltext, spatial). Don't override \u2014 the lock is real.\n\n### MongoDB\n```js\ndb.users.createIndex({ email: 1 }, { background: true })   \/\/ 4.2 default; deprecated in 6+ where it's always non-blocking\n```\n\n### Tooling\n- **Postgres**: `pg_repack` for table-rewrite migrations without long locks\n- **MySQL**: `pt-online-schema-change` (Percona) or `gh-ost` (GitHub) \u2014 both work via shadow tables + triggers\n- **Mongo**: rolling builds across replica set members\n\n---\n\n## 3. Backfilling \u2014 Chunked\n\nSingle `UPDATE` over millions of rows = long transaction = long lock = replication lag = page.\n\n### SQL (chunked, app-driven)\n```sql\n-- pseudo: loop in app code\nUPDATE users\nSET plan = COALESCE(plan, 'free')\nWHERE id BETWEEN :start AND :end\n  AND plan IS NULL;\n-- Sleep 50ms between batches; chunk size 1k\u201310k rows\n```\n\n### Laravel\n```php\nUser::whereNull('plan')->chunkById(1000, function ($users) {\n    foreach ($users as $user) {\n        $user->update(['plan' => 'free']);\n    }\n    usleep(50_000);   \/\/ 50ms breathing room\n});\n```\n\n### Mongoose\n```ts\nconst cursor = User.find({ plan: { $exists: false } }).cursor();\nfor await (const user of cursor) {\n  await User.updateOne({ _id: user._id }, { $set: { plan: 'free' } });\n}\n```\n\n### Django\nUse `RunPython` migration with `atomic=False` and chunk:\n```python\nclass Migration(migrations.Migration):\n    atomic = False\n    operations = [migrations.RunPython(backfill, reverse_code=migrations.RunPython.noop)]\n\ndef backfill(apps, schema_editor):\n    User = apps.get_model(\"app\", \"User\")\n    qs = User.objects.filter(plan__isnull=True).only(\"id\")\n    for batch in chunked(qs.iterator(), 1000):\n        User.objects.filter(id__in=[u.id for u in batch]).update(plan=\"free\")\n```\n\n---\n\n## 4. Lock Timeouts (Critical)\n\nSet a short timeout so a stuck migration fails fast instead of blocking the app:\n\n```sql\n-- Postgres\nSET LOCAL lock_timeout = '5s';\nSET LOCAL statement_timeout = '15s';\nALTER TABLE users ADD COLUMN x INT;\n\n-- MySQL \/ MariaDB\nSET SESSION lock_wait_timeout = 5;\nSET SESSION innodb_lock_wait_timeout = 5;\n```\n\nWithout this, an `ALTER` waiting for a long-running `SELECT` will block every subsequent write behind it (Postgres queue).\n\n---\n\n## 5. Renaming \u2014 Never Direct in Prod\n\nNever `ALTER TABLE users RENAME COLUMN email TO email_address` in a single deploy. The old code on the previous release will break.\n\n```\nRelease N:   add new column, dual-write\nRelease N+1: backfill, switch reads to new column\nRelease N+2: drop old column\n```\n\nSame for table renames, type changes (often disguised renames + casts), enum value removal.\n\n---\n\n## 6. Foreign Keys\n\nAdding a FK validates every existing row. On large tables this locks.\n\n### Postgres\n```sql\n-- Two-step\nALTER TABLE orders ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) NOT VALID;  -- fast\n-- Validate when load is low; takes only SHARE UPDATE EXCLUSIVE lock\nALTER TABLE orders VALIDATE CONSTRAINT fk_user;\n```\n\n### MySQL \u2014 no equivalent; use offline tooling (`gh-ost`).\n\n---\n\n## 7. Dropping \u2014 Always Soft First\n\n```\nRelease N:   stop writing to column (deploy)\nRelease N+1: stop reading from column (deploy)  \u2190 observe metrics\nRelease N+2: drop column\n```\n\nAdd a feature flag for the new code path so you can roll back without a schema change.\n\n---\n\n## 8. Migration Tooling Per Stack\n\n| Stack | Tool | Notes |\n|---|---|---|\n| Node + SQL | Drizzle \/ Kysely \/ Knex \/ TypeORM | Drizzle is the modern choice; uses `meta` snapshots |\n| Node + Mongo | Mongoose schema versioning | No DDL \u2014 but evolve with backfills |\n| Python + SQL | Alembic (SQLAlchemy), Django migrations | |\n| PHP | Laravel migrations + `doctrine\/dbal` for DDL | |\n\nRules regardless of tool:\n- Migration files are **append-only** once merged. Edit = rewrite history = production drift.\n- Each migration has both `up` and `down` (or a documented \"no rollback\" reason).\n- Migrations run idempotently (safe to re-run).\n- Never include data migrations in schema migrations on huge tables \u2014 separate scripts.\n\n---\n\n## 9. Rollback Strategy\n\nFor every migration ask: **\"How do I undo this in 5 minutes if prod breaks?\"**\n\n| Operation | Rollback |\n|---|---|\n| Add nullable column | `DROP COLUMN` (instant) |\n| Add NOT NULL column with default | `DROP COLUMN` |\n| Add index | `DROP INDEX [CONCURRENTLY]` |\n| Rename column | None \u2014 that's why parallel change |\n| Drop column | Restore from backup. **Don't.** |\n| Backfill | Run inverse update OR accept the data is now correct |\n\nIf you can't write a 5-minute rollback, the migration is too risky for one release. Split it.\n\n---\n\n## 10. Pre-Deploy Checklist\n\n- [ ] Migration runs in < 5s OR is concurrent \/ non-blocking\n- [ ] Lock + statement timeouts set\n- [ ] Tested on a copy of prod-sized data (or a representative subset)\n- [ ] Backfills are chunked with breathing room\n- [ ] No combined expand + contract in same deploy\n- [ ] App code on previous release survives if migration runs first\n- [ ] App code on next release survives if migration is delayed\n- [ ] Rollback plan written (or \"no rollback\" justified)\n- [ ] DBA \/ on-call notified for high-risk migrations\n\n## FORBIDDEN\n\n| Pattern | Reason |\n|---|---|\n| `ALTER TABLE` without lock timeout in prod | Single bad query = full outage |\n| `CREATE INDEX` without `CONCURRENTLY` (Postgres) | Locks writes |\n| Renaming a column in one deploy | Breaks rolling deploys |\n| Single huge `UPDATE` | Replication lag, locks, redo bloat |\n| Editing a merged migration file | Prod drift, dev\/prod mismatch |\n| Dropping a column without two prior soft-delete deploys | No rollback |\n| Migrations running automatically on every deploy without gates | Surprise outage |\n| Mixing schema and data migrations on hot tables | Single-tx behavior unpredictable |\n\n## See Also\n\n- `observability` \u2014 track migration duration and lag during runs\n- `error-handling` \u2014 service-side feature flags for parallel change\n- `ci-pipelines` \u2014 gate migrations behind manual approval for production\n","use_cases":["Adding a new column with a NOT NULL constraint","Creating non-blocking indexes on large tables","Performing chunked backfills on millions of rows","Dropping columns safely in production","Renaming columns without breaking existing code"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/0x57-1\/start-vibing-stacks\/blob\/6e398b34c4dfe73ac8f809216b218856b8e02ff4\/stacks\/_shared\/skills\/database-migrations\/SKILL.md","source_commit":"6e398b34c4dfe73ac8f809216b218856b8e02ff4","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T09:11:02.000000Z","updated_at":"2026-12-03T16:20:08.000000Z","seo_title":"Safe Database Migrations \u2014 Backfills, Indexes, and Rollback Strategies","seo_description":"Learn how to perform safe and non-disruptive database migrations with parallel change patterns, chunked backfills, and non-blocking index creation to avoid outages and un","seo_keywords":["database migration","safe schema changes","non-blocking index","chunked backfill","rollback strategy","parallel change pattern","database lock timeout","migration best practices"]}}