Our PostgreSQL Migration Took 14 Milliseconds in CI and 19 Minutes in Production

Our PostgreSQL Migration Took 14 Milliseconds in CI and 19 Minutes in Production

ALTER TABLE invoices ALTER COLUMN tax_rate TYPE NUMERIC(6, 4); That was the entire pull request. One SQL line, generated by Prisma, reviewed by two senior engineers, and tested in CI against a fresh Postgres container seeded with 40 clean invoices. In CI, it ran in 14 milliseconds. In production, it rewrote a 14.3-million-row table on disk under an ACCESS EXCLUSIVE lock for 19 minutes straight, backed up every SELECT and INSERT behind it, drained all 800 PgBouncer connections in 40 seconds, and knocked our checkout API offline. The migration was not "weird" or exotic. Every single engineer on the team had run it locally before merging. The problem was that our test database had 40 tidy rows created five minutes ago, while production had six years of messy history, bloated B-tree indexes, and millions of legacy NULL values. Why 40-Row Seed Scripts Are Worse Than No Tests at All If you test a database migration against 40 rows, you are not testing the migration. You are only testing whether your SQL syntax is valid. Almost every backend repo has a seed.ts or fixtures.sql file written during the first month of the project. Ours had 12 users, 40 invoices, 5 products, and zero NULLs in optional columns. Over six years, production drifted in three ways that seed.ts never modeled: Row volume: Full table rewrites (ALTER COLUMN TYPE, VACUUM FULL) and non-concurrent index builds scale with disk pages, not code complexity. Fourteen milliseconds on 40 rows tells you nothing about 14 million rows. Dirty legacy rows: We had 310,000 invoices from 2021 where tax_region was NULL because that column did not exist back then. Any NOT NULL constraint or CHECK rule that passed on clean seed data exploded the moment it touched 2021 rows. Active query traffic: On localhost, nobody else is running a 12-second Metabase reporting SELECT on invoices at the exact moment your migration asks for a lock. The Postgres Lock Queue Nobody Sees on Localhost The 19-minute outage was actually worse than just the table rewrite time. Here is the part that catches teams off guard if they only test on an idle CI container: When Postgres executes ALTER TABLE invoices ..., it requests an ACCESS EXCLUSIVE lock. If a long-running analytics query (say, an accounting export holding an ACCESS SHARE lock for 90 seconds) is already running, the ALTER TABLE has to wait for it to finish. Fair enough—except every new query that arrives after the ALTER TABLE queues up behind it. Even a 1-millisecond SELECT id FROM invoices WHERE id = $1 gets blocked waiting for the ALTER TABLE, which is waiting for the 90-second export. Within 30 seconds, your API pods burn through their entire connection pool waiting on Postgres, Kubernetes readiness probes time out, and pods start crash-looping. On localhost, there is no analytics export running. So ALTER TABLE grabs the lock instantly, rewrites 40 rows in 14ms, and tells you the PR is safe to ship. Check 1: A 95-Line SQL Migration Linter in CI Before we ever boot a database container, we run a fast static linter (scripts/lint-migrations.ts) on every .sql file touched in a pull request. It takes under 1 second and blocks four specific Postgres footguns: Missing SET lock_timeout — Every DDL migration must set a short lock_timeout (like 3s) so if it cannot grab the lock immediately, it aborts cleanly instead of piling up production traffic behind it. CREATE INDEX without CONCURRENTLY — Standard CREATE INDEX blocks all writes (INSERT/UPDATE/DELETE) on the table until the build finishes. ALTER COLUMN ... TYPE table rewrites — Flagged as a hard error unless explicitly annotated with -- allow-table-rewrite after an expand-and-contract plan. ADD CONSTRAINT ... CHECK or NOT NULL without NOT VALID — Validates every existing row under an ACCESS EXCLUSIVE lock instead of adding NOT VALID first and running VALIDATE CONSTRAINT separately under a lighter SHARE UPDATE EXCLUSIVE lock. Here is the TypeScript script we wired into GitHub Actions: import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; interface LintIssue { file: string; rule: string; message: string; } const changedSqlFiles = execFileSync( 'git', ['diff', '--name-only', '--diff-filter=AM', 'origin/main...HEAD', '--', 'prisma/migrations/**/*.sql'], { encoding: 'utf8' } ) .trim() .split('\n') .filter(Boolean); const issues: LintIssue[] = []; for (const file of changedSqlFiles) { const raw = fs.readFileSync(file, 'utf8'); const sql = raw.replace(/--.*$/gm, ''); // strip single-line comments for checks const hasDdl = /\b(ALTER\s+TABLE|CREATE\s+INDEX|DROP\s+INDEX)\b/i.test(sql); if (!hasDdl) continue; // 1. Require lock_timeout before DDL (unless running CONCURRENTLY outside tx) const usesConcurrently = /\bCREATE\s+(UNIQUE\s+)?INDEX\s+CONCURRENTLY\b/i.test(sql); if (!usesConcurrently && !/SET\s+(LOCAL\s+)?lock_timeout\s*=/i.test(sql)) { issues.push({ file, rule: 'require-lock-timeout', message: "Set `SET lock_timeout = '3s';` before DDL so blocked migrations fail fast.", }); } // 2. Ban blocking CREATE INDEX if (/\bCREATE\s+(UNIQUE\s+)?INDEX\s+(?!CONCURRENTLY\b)/i.test(sql)) { issues.push({ file, rule: 'require-concurrent-index', message: 'Use `CREATE INDEX CONCURRENTLY` to avoid blocking table writes.', }); } // 3. Ban unannotated ALTER COLUMN TYPE if ( /\bALTER\s+TABLE\b[\s\S]*?\bALTER\s+COLUMN\b[\s\S]*?\bTYPE\b/i.test(sql) && !raw.includes('-- allow-table-rewrite') ) { issues.push({ file, rule: 'ban-column-type-rewrite', message: 'ALTER COLUMN TYPE rewrites the table under ACCESS EXCLUSIVE lock. Use expand-and-contract.', }); } // 4. Require NOT VALID on new CHECK constraints if (/\bADD\s+CONSTRAINT\b[\s\S]*?\bCHECK\b/i.test(sql) && !/\bNOT\s+VALID\b/i.test(sql)) { issues.push({ file, rule: 'require-not-valid-constraint', message: 'Add CHECK constraints with `NOT VALID`, then run `VALIDATE CONSTRAINT` in a separate step.', }); } } if (issues.length > 0) { for (const issue of issues) { console.error(`[${issue.rule}] ${issue.file}: ${issue.message}`); } process.exit(1); } console.log(`Migration lint passed across ${changedSqlFiles.length} SQL file(s).`); That script blocked 9 risky migrations in its first 60 days—mostly CREATE INDEX statements missing CONCURRENTLY and ALTER TABLE scripts without lock_timeout. Check 2: Benchmarking Against 5 Million Dirty Rows in CI Static linting catches bad DDL patterns, but it cannot tell you if a backfill UPDATE or a new composite index is going to thrash disk I/O or choke on NULLs. And restoring a full 80 GB anonymized production snapshot on every single PR is slow and expensive. Instead, we built a synthetic scale generator (scripts/bench-migration.sh) that spins up an ephemeral Postgres 16 container in GitHub Actions, inserts 5 million realistic rows using generate_series (including 10% NULL values in legacy columns), and times the PR's migration with EXPLAIN and pg_stat_activity lock inspection. Generating 5 million rows in Postgres with UNLOGGED tables or INSERT INTO ... SELECT FROM generate_series(1, 5000000) takes about 11 seconds on a standard GitHub runner—fast enough to run on any PR that touches prisma/migrations/. Here is the benchmark script: #!/usr/bin/env bash set -euo pipefail PG_URL="${DATABASE_URL:?DATABASE_URL must be set}" MIGRATION_FILE="${1:?Pass path to migration.sql}" echo "Seeding 5,000,000 synthetic invoices (with 10% legacy NULLs)..." psql "$PG_URL" -v ON_ERROR_STOP=1 10s budget) on 5M rows. Break into batched backfills." exit 1 fi And the GitHub Actions job only triggers when a PR actually modifies a migration file: jobs: migration-scale-bench: runs-on: ubuntu-latest if: contains(github.event.pull_request.changed_files, 'migrations') || true services: postgres: image: postgres:16-alpine env: POSTGRES_PASSWORD: test POSTGRES_DB: bench ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 5s --health-timeout 3s --health-retries 5 steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - run: npx tsx scripts/lint-migrations.ts - name: Benchmark new migrations on 5M rows env: DATABASE_URL: postgresql://postgres:test@127.0.0.1:5432/bench run: | for f in $(git diff --name-only origin/main...HEAD -- 'prisma/migrations/**/*.sql'); do ./scripts/bench-migration.sh "$f" done The 10-second budget on 5 million rows is intentionally strict. If a migration takes 18 seconds on an idle 5M-row CI Postgres instance, it will easily take minutes under live production I/O—and that is the exact signal telling you to split the change into a safe expand-and-contract rollout with batched 5,000-row backfills. How We Actually Fixed the tax_rate Column Without Downtime For the tax_rate column that started this whole mess, we ended up doing the boring four-step expand-and-contract dance: Added tax_rate_v2 NUMERIC(6, 4) NULL (instant metadata-only operation in Postgres, under 5ms). Deployed application code that dual-wrote both tax_rate and tax_rate_v2 on new invoices. Backfilled historical rows in batches of 10,000 with a 50ms sleep between batches so replication lag stayed under 100ms. Switched reads to tax_rate_v2 and dropped tax_rate a week later. Zero lock queues, zero dropped PgBouncer connections, and zero angry Slack threads. Here is the keyset-paginated backfill loop (scripts/backfill-tax-rate.ts) we ran against production. Notice it never uses OFFSET (which gets slower on every page as you approach row 14 million) and pauses if read-replica lag climbs above 200ms: import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.PROD_DATABASE_URL }); const BATCH_SIZE = 10_000; async function runBackfill() { let lastId = 0; let totalUpdated = 0; while (true) { const { rows } = await pool.query( ` WITH batch AS ( SELECT id, tax_rate FROM invoices WHERE id > $1 AND tax_rate_v2 IS NULL ORDER BY id ASC LIMIT $2 ), upd AS ( UPDATE invoices i SET tax_rate_v2 = b.tax_rate FROM batch b WHERE i.id = b.id RETURNING i.id ) SELECT COALESCE(MAX(id), 0) AS max_id, COUNT(*)::int AS updated FROM upd; `, [lastId, BATCH_SIZE] ); const { max_id, updated } = rows[0]; if (updated === 0) break; lastId = max_id; totalUpdated += updated; if (totalUpdated % 100_000 === 0) { console.log(`Backfilled ${totalUpdated.toLocaleString()} rows (lastId=${lastId})`); } // Brief throttle so autovacuum and read replicas keep up await new Promise((r) => setTimeout(r, 50)); } console.log(`Backfill complete: ${totalUpdated.toLocaleString()} rows updated.`); await pool.end(); } runBackfill().catch((err) => { console.error(err); process.exit(1); }); Running that keyset loop took roughly 22 minutes for all 14.3 million rows, kept CPU under 18% on our RDS primary, and never once blocked a checkout write. Compare that to a single unbatched UPDATE invoices SET tax_rate_v2 = tax_rate, which generates massive WAL spikes, bloats dead tuples before autovacuum can catch up, and stalls replicas. What We Stopped Doing in Code Review We stopped asking reviewers to mentally simulate Postgres locking rules by staring at a 10-line .sql diff. Nobody is good at that at 4 PM on a Thursday, and 40-row seed scripts actively trick you into thinking a dangerous migration is instant. We also stopped trusting ORM-generated migration SQL blindly. Prisma, TypeORM, and Drizzle are great at generating schema diffs, but they optimize for developer ergonomics—not zero-downtime locking on 14-million-row tables. When an ORM emits ALTER COLUMN TYPE or drops a constraint, it will happily hand you a loaded footgun without a single warning. Six months after adding the SQL lock linter and the 5-million-row benchmark job, we have shipped 34 schema migrations to production with zero lock-queue outages. Give your CI pipeline a few million dirty rows with NULLs in the right places and a 1-second SQL linter. Your production database will thank you—mostly by staying boring.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.