Works with the AI Agents you already use

    DB Migration Safety Reviewer: Zero-Downtime Schema Changes

    by a365ngay

    1

    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

    Security scanned
    DB Migration Safety Reviewer: Zero-Downtime Schema Changes

    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). tenants is small. amount is integer holding cents (assumed). id is a bigint primary key (assumed).
    • Durations are rough estimates for this size on typical SSD storage, not measurements.
    #StatementLock / blocksRewrite or scanRiskFix
    1ADD COLUMN tenant_id bigint NOT NULL DEFAULT 0ACCESS EXCLUSIVE, blocks everything; held until commitNone on 15 (constant default)High (because of the transaction); no tenant 0 exists, so #3 fails after everything else ranAdd nullable, no sentinel default
    2UPDATE 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 lagHighBatched, idempotent backfill script outside the migration
    3ADD CONSTRAINT ... FOREIGN KEYSHARE ROW EXCLUSIVE on invoices and tenantsFull scan of 80M rowsHigh; fails on the 0 rows from #1NOT VALID now, VALIDATE CONSTRAINT after backfill
    4CREATE INDEXSHARE, blocks writes for the whole buildFull scan + sortHighCREATE INDEX CONCURRENTLY in its own non-transactional migration
    5RENAME COLUMN amount TO amount_centsACCESS EXCLUSIVE (brief)NoneHigh: old pods still query amount and fail until rollout completesDo not rename in this change
    6ALTER COLUMN amount_cents TYPE bigintACCESS EXCLUSIVEFull rewrite of 60 GB + every index rebuilt; needs about as much free diskCriticalSeparate 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

    StepTypeDuration (est.)MonitorStop ifRollback
    1. V42 expandMigrationSecondsLock waits on invoiceslock_timeout hit 3 times: find the long transaction firstALTER TABLE invoices DROP COLUMN tenant_id;
    2. App release: set tenant_id on every insert/updateApp releaseNormal rolloutError rate; FK violationsFK errors: roll back the appRoll back app; column stays nullable
    3. Backfill jobScriptHours at 5k rows/batch (~16,000 batches)Replica lag, CPU, dead tuplesLag > 30 s, CPU > 80 %Stop the job; rerun later (idempotent)
    4. Check SELECT count(*) FROM invoices WHERE tenant_id IS NULL; = 0CheckMinutes (read-only scan)-> 0: rerun backfill-
    5. V43 indexMigration (no transaction)Tens of minutesDisk, I/O, replica lagFails: DROP INDEX CONCURRENTLY invoices_tenant_created_idx; and retrySame drop
    6. V44 enforceMigrationTwo full scans; writes continueLock waitslock_timeout: retry off-peakDROP NOT NULL / DROP CONSTRAINT invoices_tenant_fk
    7. App release: queries use tenant_idApp releaseNormalQuery 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 amount max values: is the bigint change actually needed?
    • Whether every accounts row has a non-null tenant_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. 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. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 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

    Listed6 days ago

    What's inside

    Frequently Asked Questions

    No. It reviews the migration and context you paste and gives you rewritten migrations, scripts and commands to run yourself. In rescue mode it gives read-only queries to find the blocker and leaves any cancel or kill decision to you.

    PostgreSQL, MySQL/MariaDB (including RDS and Aurora notes) and SQL Server (including Standard vs Enterprise differences for online operations). It asks for the exact version because lock behavior changes between versions, for example PostgreSQL 11+ fast defaults or MySQL 8.0.29 INSTANT changes.

    Yes: Rails, Django, Alembic, Prisma, EF Core, Laravel, Flyway, Liquibase, Knex and raw SQL. It reviews the SQL the tool generates and answers in your tool's style, including the right no-transaction or ALGORITHM option for that tool and database.

    SAFE: every statement takes only brief locks and works with the app version still running. SAFE WITH CHANGES: small fixes needed, such as a lock timeout or an online option. UNSAFE: something would block traffic for long, rewrite a big table, break running code or risk data; you get a step-by-step safe version.

    Yes. Rescue mode gives the query that shows who is blocking whom for your engine, explains why cancelling the waiting migration is usually safer than killing app sessions, and what each option rolls back. You run the commands; afterwards it reviews the migration properly.

    They are rough estimates from the table size and write rate you give, labeled as such. For big rebuilds it recommends measuring on a production-size copy before the real run.

    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.

    Free