Zero-Downtime Production Migration: Expand-Contract Pattern and AI Guardrail Rules in Action
Intercept table-lock risks via Cursor rules to achieve a 76% automated migration workflow, ensuring zero data loss and zero business disruption.

Completion Score
The overall completion rate of 76% reflects AI's efficiency in generating standard migration scripts and backfill logic. However, manual intervention is still required when handling complex concurrent lock contention and final traffic shifting verification. AI excels at generating idempotent scripts and SQL structures but has limitations in assessing real-time production load and confirming business logic compatibility; therefore, manual gates must be retained.
Dimension breakdown
AI can accurately generate Prisma/Drizzle schema difference comparisons and automatically identify incompatible changes, but business semantics must be confirmed manually.
Rules enforce the use of CONCURRENTLY, but AI struggles to predict lock wait times under extreme loads, requiring manual assessment combined with production monitoring data.
AI-generated backfill scripts have clear structure and idempotency, but memory optimization for ultra-large tables and error retry mechanisms require manual fine-tuning.
Rollback scripts are complete, but traffic ratio control during canary shifting and business logic rollback depend on application-layer configuration, which AI cannot fully cover.
Human checkpoint
Before deployment, manually review the batch size and concurrency strategy in `backfill_script.js`, and confirm that the dual-write logic in the application layer has been correctly deployed. During the contraction phase, manually verify that there are no long-running transactions in `pg_stat_activity` and confirm that business monitoring metrics are normal before executing the DROP operation.
Upgrade / downgrade path
If resources are constrained, downgrade to using only the Expand phase while retaining the old column, achieving compatibility through application-layer logic to avoid complex backfill scripts. If higher performance is required, introduce Citus or partitioning strategies, but this necessitates adding corresponding sharding key migration logic, which increases the complexity of AI generation; it is recommended that a senior DBA review this.
When to use & prerequisites
Suitable for production PostgreSQL database environments with over 1 million rows, where teams use Prisma or Drizzle as the ORM. The target audience is backend engineers who need to perform schema changes (e.g., adding non-nullable columns, renaming columns) without service interruption. Ideal use cases include high-frequency change scenarios such as extending e-commerce order table fields and optimizing user profile table structures.
Ready-to-copy configs
定义数据库迁移的硬性安全边界,禁止 AI 生成直接锁表操作,强制使用 Expand-Contract 模式。
---
alwaysApply: true
---
# Database Migration Guard Rules
## 1. Prohibited Patterns (Hard Block)
- **NEVER** generate `ALTER TABLE ... ADD COLUMN ... NOT NULL` without a default value.
- **NEVER** generate `ALTER TABLE ... DROP COLUMN` in a single atomic step.
- **NEVER** use `CREATE INDEX` without `CONCURRENTLY` on tables > 100k rows.
- **NEVER** assume `prisma migrate deploy` handles data backfilling.
## 2. Mandatory Expand-Contract Workflow
All schema changes must follow this 3-phase sequence:
1. **Expand**: Add new nullable column/index. Verify no lock contention.
2. **Contract**: Backfill data in batches, then change column to NOT NULL.
3. **Shrink**: Drop old column/index only after 100% traffic switch.
## 3. Verification Requirements
- Every migration file must include a `-- VERIFY` comment block.
- Index creation must specify `ON CONFLICT DO NOTHING` or `CONCURRENTLY`.
- Backfill scripts must be idempotent and batched (limit 1000 rows).
## 4. Human Gate
- If `pg_stat_activity` shows `idle in transaction` > 5s, HALT and alert.
- Require manual approval for any `DROP` statement.提供可复用的 Expand-Contract 迁移技能模板,包含双写逻辑与幂等回填脚本生成规范。
---
name: expand-contract-migration
description: Generates safe, zero-downtime database migrations using the Expand-Contract pattern.
---
# Expand-Contract Migration Skill
## Objective
Generate a 3-step migration sequence that ensures zero downtime and no data loss.
## Step 1: Expand (Safe Addition)
- Add new column as `NULL`.
- Create new index with `CONCURRENTLY`.
- Update application code to write to BOTH old and new fields (Dual Write).
## Step 2: Backfill (Idempotent Data Copy)
- Generate a batched SQL script to copy data from old to new column.
- Batch size: 1000 rows.
- Use `WHERE id > $last_id` for pagination.
- Ensure script is idempotent (safe to re-run).
## Step 3: Contract (Safe Removal)
- Set new column to `NOT NULL` with default value.
- Drop old index/column ONLY after verifying 100% read traffic uses new field.
- Include a rollback script that restores old column if needed.
## Output Format
1. `migration_001_expand.sql`
2. `backfill_script.js` (Node.js/Prisma)
3. `migration_002_contract.sql`
4. `rollback_plan.md`AI Vibe Coding in 4 steps
- 1
Generate Expand Phase Migration Script
Goal: Create a safe table expansion migration, add new columns, and establish concurrent indexes to ensure no write blocking.
PromptBased on the .cursor/rules/db-migration-guard.mdc rule, add a JSONB column named 'profile_v2' to the users table. Requirements: 1. The column must be NULL. 2. Index creation must use CONCURRENTLY. 3. Generate a Prisma migration file. 4. Add a VERIFY comment at the top of the file explaining how to check lock status.Verify:
Run `npx prisma migrate dev --name add_profile_v2`, check if the generated SQL includes `CREATE INDEX CONCURRENTLY`, and confirm there are no `LOCK TABLE` statements. - 2
Generate Idempotent Data Backfill Script
Goal: Write a Node.js script to batch-copy old data to the new column, ensuring the script is re-executable and does not block the primary database.
PromptBased on .cursor/skills/expand-contract/SKILL.md, generate a backfill_profile_v2.js script. Requirements: 1. Use the Prisma client. 2. Batch size of 1000. 3. Use WHERE id > $lastId for pagination. 4. Ensure script idempotency (skip already filled rows). 5. Add progress logging and error retry mechanisms.Verify:
Run the script in the test environment, check if logs show batched execution, and verify that running the script repeatedly does not cause errors or duplicate data writes. - 3
Implement Dual-Write Logic and Traffic Shifting Preparation
Goal: Modify application code to implement dual-write for old and new fields and prepare the traffic switching toggle.
PromptModify the create and update methods in the User service. Requirements: 1. Update both 'profile' and 'profile_v2' fields simultaneously upon write. 2. Add an environment variable FEATURE_FLAG_PROFILE_V2 to control the read source. 3. Ensure the dual-write logic is atomic. 4. Generate unit tests covering dual-write scenarios.Verify:
Run unit tests to confirm that when FEATURE_FLAG_PROFILE_V2 is false, the old field is read; when true, the new field is read. Also, ensure both fields are updated upon write. - 4
Generate Contract Phase and Rollback Plan
Goal: Generate migration scripts for the contraction phase, set the new column to NOT NULL, and write detailed rollback documentation.
PromptGenerate migration_002_contract.sql and rollback_plan.md. Requirements: 1. Set 'profile_v2' to NOT NULL with a default value of '{}' in the SQL. 2. Delete the old column 'profile' (commented out, requires manual confirmation). 3. rollback_plan.md must include: - How to rollback the schema. - How to rollback application code. - SQL for data consistency checks. 4. Emphasize the manual acceptance gate.Verify:
Review the SQL file to confirm DROP statements are commented or marked for manual execution. Check if rollback_plan.md includes specific SQL statements for data consistency checks.
Pitfalls & fixes
- AI may generate `ALTER TABLE ... ADD COLUMN ... NOT NULL` without a default value, causing table locks. Fix: Explicitly forbid this pattern in Rules and enforce adding a NULL column first.
- Backfill scripts may crash due to memory overflow on ultra-large tables. Fix: Limit batch size and add memory monitoring and automatic restart logic to the script.
- In dual-write logic, if the old field update fails but the new field succeeds, data inconsistency occurs. Fix: Use database transactions to ensure dual-write atomicity or add compensation mechanisms in the application layer.
FAQ
Why can't Prisma's migrate deploy be used directly to complete all changes?
Prisma's migrate deploy handles only schema changes, not data backfill. Direct execution for adding non-nullable columns or renaming columns can cause table locks or data loss. The Expand-Contract pattern ensures safety through step-by-step operations and manual gates.
What residue is left if CONCURRENTLY index creation fails?
If CONCURRENTLY index creation fails, an index with an INVALID status is left behind. Manually execute `DROP INDEX CONCURRENTLY index_name` to clean up, then recreate it. AI-generated scripts should include this cleanup logic.
How to verify dual-write logic is correct in the production environment?
Monitor database write logs to confirm that both old and new fields are updated on every write. PostgreSQL's `pg_stat_statements` or application-layer logs can be used for verification. Additionally, run data consistency check SQL periodically to ensure old and new field data match.


