- Home
- Skills
- Data & Databases
- DB Migration Safety Reviewer: Zero-Downtime Schema Changes
Works with the AI Agents you already use
DB Migration Safety Reviewer: Zero-Downtime Schema Changes
by a365ngay
The migration that took 3 seconds in staging can lock your biggest table for an hour in production. This skill reviews schema changes the way a careful DBA does, before they ship.
Free
DB Migration Safety Reviewer: Zero-Downtime Schema Changes
Example session with this skill installed
Can you check this before I merge? Postgres 15, Flyway (default settings, so each migration runs in one transaction). invoices has ~80M rows, ~60 GB, around 400 writes/s at peak. We do rolling deploys on Kubernetes.
-- V42__invoices_tenant.sql
ALTER TABLE invoices ADD COLUMN tenant_id bigint NOT NULL DEFAULT 0;
UPDATE invoices i SET tenant_id = a.tenant_id FROM accounts a WHERE a.id = i.account_id;
ALTER TABLE invoices ADD CONSTRAINT invoices_tenant_fk FOREIGN KEY (tenant_id) REFERENCES tenants(id);
CREATE INDEX invoices_tenant_created_idx ON invoices (tenant_id, created_at);
ALTER TABLE invoices RENAME COLUMN amount TO amount_cents;
ALTER TABLE invoices ALTER COLUMN amount_cents TYPE bigint;
- Read your context and instructions
- Compiled the db migration safety
Verdict: UNSAFE: in one transaction, the first statement's ACCESS EXCLUSIVE lock is held until the end, so invoices is unreadable and unwritable for the whole 80M-row update, the FK scan, the index build and a 60 GB table rewrite (likely over an hour), and the rename breaks the old pods during the rolling deploy.
Context and assumptions
- PostgreSQL 15, Flyway wrapping V42 in a single transaction, rolling deploy (old and new pods run together).
- 80M rows / 60 GB / ~400 writes/s (given).
tenantsis small.amountisintegerholding cents (assumed).idis abigintprimary key (assumed). - Durations are rough estimates for this size on typical SSD storage, not measurements.
| # | Statement | Lock / blocks | Rewrite or scan | Risk | Fix |
|---|---|---|---|---|---|
| 1 | ADD COLUMN tenant_id bigint NOT NULL DEFAULT 0 | ACCESS EXCLUSIVE, blocks everything; held until commit | None on 15 (constant default) | High (because of the transaction); no tenant 0 exists, so #3 fails after everything else ran | Add nullable, no sentinel default |
| 2 | UPDATE invoices ... FROM accounts (80M rows) | Row locks on every row until commit (plus #1's lock) | New version of every row: ~60 GB of new tuples, WAL spike, replica lag | High | Batched, idempotent backfill script outside the migration |
| 3 | ADD CONSTRAINT ... FOREIGN KEY | SHARE ROW EXCLUSIVE on invoices and tenants | Full scan of 80M rows | High; fails on the 0 rows from #1 | NOT VALID now, VALIDATE CONSTRAINT after backfill |
| 4 | CREATE INDEX | SHARE, blocks writes for the whole build | Full scan + sort | High | CREATE INDEX CONCURRENTLY in its own non-transactional migration |
| 5 | RENAME COLUMN amount TO amount_cents | ACCESS EXCLUSIVE (brief) | None | High: old pods still query amount and fail until rollout completes | Do not rename in this change |
| 6 | ALTER COLUMN amount_cents TYPE bigint | ACCESS EXCLUSIVE | Full rewrite of 60 GB + every index rebuilt; needs about as much free disk | Critical | Separate expand/contract project, only if integer is really too small |
Is the type change needed? integer holds up to 2,147,483,647 cents (about $21.4M per invoice). If no invoice gets close, drop #5 and #6; a cosmetic rename costs four releases.
Safe version
-- V42__invoices_tenant_expand.sql (transactional is fine: only brief locks)
SET lock_timeout = '3s';
ALTER TABLE invoices ADD COLUMN tenant_id bigint; -- nullable, metadata only
ALTER TABLE invoices
ADD CONSTRAINT invoices_tenant_fk FOREIGN KEY (tenant_id)
REFERENCES tenants(id) NOT VALID; -- enforced for new rows only
-- backfill_invoices_tenant.sql (run by a job, batch by batch, NOT a Flyway migration)
UPDATE invoices i
SET tenant_id = a.tenant_id
FROM accounts a
WHERE a.id = i.account_id
AND i.id >= :start AND i.id < :start + 5000
AND i.tenant_id IS NULL;
-- commit, sleep ~100 ms, advance :start; stop if replica lag > 30 s
-- V43__invoices_tenant_index.sql
-- Flyway script config V43__invoices_tenant_index.sql.conf: executeInTransaction=false
SET lock_timeout = '3s';
CREATE INDEX CONCURRENTLY IF NOT EXISTS invoices_tenant_created_idx
ON invoices (tenant_id, created_at);
-- V44__invoices_tenant_enforce.sql (after backfill reports 0 rows left)
SET lock_timeout = '3s';
ALTER TABLE invoices VALIDATE CONSTRAINT invoices_tenant_fk; -- reads/writes continue
ALTER TABLE invoices ADD CONSTRAINT invoices_tenant_nn CHECK (tenant_id IS NOT NULL) NOT VALID;
ALTER TABLE invoices VALIDATE CONSTRAINT invoices_tenant_nn; -- scan without blocking writes
ALTER TABLE invoices ALTER COLUMN tenant_id SET NOT NULL; -- 12+: uses the valid check, no scan
ALTER TABLE invoices DROP CONSTRAINT invoices_tenant_nn;
Runbook
| Step | Type | Duration (est.) | Monitor | Stop if | Rollback |
|---|---|---|---|---|---|
| 1. V42 expand | Migration | Seconds | Lock waits on invoices | lock_timeout hit 3 times: find the long transaction first | ALTER TABLE invoices DROP COLUMN tenant_id; |
2. App release: set tenant_id on every insert/update | App release | Normal rollout | Error rate; FK violations | FK errors: roll back the app | Roll back app; column stays nullable |
| 3. Backfill job | Script | Hours at 5k rows/batch (~16,000 batches) | Replica lag, CPU, dead tuples | Lag > 30 s, CPU > 80 % | Stop the job; rerun later (idempotent) |
4. Check SELECT count(*) FROM invoices WHERE tenant_id IS NULL; = 0 | Check | Minutes (read-only scan) | - | > 0: rerun backfill | - |
| 5. V43 index | Migration (no transaction) | Tens of minutes | Disk, I/O, replica lag | Fails: DROP INDEX CONCURRENTLY invoices_tenant_created_idx; and retry | Same drop |
| 6. V44 enforce | Migration | Two full scans; writes continue | Lock waits | lock_timeout: retry off-peak | DROP NOT NULL / DROP CONSTRAINT invoices_tenant_fk |
7. App release: queries use tenant_id | App release | Normal | Query latency | - | Roll back app |
Also set statement_timeout for the migration role, and add a CI linter (squawk) so these patterns are caught before review.
Need from you
- Confirm
amountmax values: is thebigintchange actually needed? - Whether every
accountsrow has a non-nulltenant_id(otherwise the backfill leaves NULLs and V44 fails).
Connects securely to your tools. The creator never sees your data.
About this skill
The migration that took 3 seconds in staging can lock your biggest table for an hour in production. This skill reviews schema changes the way a careful DBA does, before they ship.
For every statement it tells you
- The lock it takes and what that blocks (reads, writes or both), for your engine and version.
- Whether it rewrites or scans the table, and roughly how long that takes at your size.
- Whether it breaks the app version still running during a rolling deploy (renames, drops, NOT NULL, type changes).
- The lock queue trap: a 5 ms ALTER waiting behind a long transaction that freezes every query on the table.
Then it rewrites it safely
- Expand, backfill, contract: split into migrations and app releases in the right order.
- Online forms:
CREATE INDEX CONCURRENTLY,NOT VALID+VALIDATE,ALGORITHM=INSTANT/INPLACE,ONLINE = ON, gh-ost / pt-online-schema-change (with their limits, such as gh-ost and foreign keys). - Batched, idempotent, resumable backfills that watch replica lag.
- Lock timeouts with retry, and the right no-transaction or algorithm option for Rails, Django, Alembic, EF Core, Flyway, Liquibase, Laravel, Knex.
- A runbook: order, duration estimate, what to monitor, when to stop, rollback per step.
Migration stuck right now?
Rescue mode gives the read-only query that shows who is blocking whom and the safest thing to cancel, and leaves the decision to you.
PostgreSQL, MySQL/MariaDB (including RDS) and SQL Server (with edition differences). Works in any language and answers in yours.
Pairs with: SQL Query Clinic (free) for the index, Incident Postmortem (free) if it already went wrong.
Reviews what you paste; it does not connect to your database or run anything. Lock behavior is version- and edition-specific, so it asks for exact versions and states assumptions when they are missing. Duration figures are estimates from table size, not measurements. Business decisions (how to resolve duplicates, whether a type change is needed) are left to you.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Free to use
No account required to browse
Trust & safety
Security scan
Security scan passed 6 days ago
- Free with an Agensi account
Requires
Nothing to install.
Permissions
No special permissions declared or detected
What's inside
Frequently Asked Questions
New in Data & Databases
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Data & Databases.