Database Migrations Best Practices
Demo Creator
@seed-creator · muallif
The Additive Migration Rule
Never remove or rename a column in a single deploy. Clients and the old code still reference the old name. Add the new column, deploy new code that writes both, then drop the old one in a later release.
A migration that drops a column is easy to write and impossible to undo in production. Earn the drop by proving the column is unused first.
Backfill Strategies
Backfilling millions of rows in a single UPDATE holds a lock for minutes. Backfill in batches with a small sleep between each: UPDATE ... WHERE id > $cursor AND id <= $cursor + 1000.
Long-running migrations that lock tables cause cascading timeouts. Always test migration duration on a copy of production data before deploying.
Column Default vs. NOT NULL
Adding a NOT NULL column with a DEFAULT rewrites every row in older Postgres versions. In Postgres 11+, stored defaults avoid the rewrite. Check your version before assuming this is free.
Testing Migrations
Run migrations against a copy of the production dump in CI. Assert that the schema matches expectations after each migration. Catch the "migration applies on a fresh DB but breaks on a stale one" class of bugs.
it('backfill does not lock the table for more than 5s', async () => { const start = Date.now(); await runMigration(db, '0005_backfill_display_name'); const elapsed = Date.now() - start; expect(elapsed).toBeLessThan(5000);});
A timing assertion catches runaway backfills before they hit production.
0 ta izoh
Tizimga kiring izoh qoldirish uchun.