Database migration patterns

From FerroxLabs/wayland · View interactive version

Database migration patterns is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level database migration patterns implementation: database and automation decision frameworks, production-ready patterns, and concrete templates for database migration patterns workflows. Use when the user asks about database migration patterns, database migration patterns configuratio

How to use this skill

Skill file

Database Migration Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Classify the Migration Type and Risk Level

Before writing a single SQL statement, determine which category the migration falls into. Each category has different risk profiles and execution patterns.

Assign a risk tier (1 = safe, 2 = caution, 3 = high-risk) at the top of every migration file as a comment. This shapes the rest of the process.

2. Audit the Current Schema and Application References

A migration cannot be planned in isolation -- it requires full knowledge of what currently depends on the object being changed.

3. Choose the Correct Migration Pattern

Select the pattern based on the migration type from Step 1:

Pattern A -- Direct Apply (additive only):

Pattern B -- Expand-Contract (for column renames, type changes, table splits):

Pattern C -- Online Schema Change (for large table structural changes):

Pattern D -- Constraint addition without full table lock:

4. Write the Migration File

Structure every migration file consistently. Use the following conventions regardless of the migration framework:

5. Design and Execute Backfill Operations

Data backfills for large tables require a batching strategy to avoid long-running transactions, excessive replication lag, and out-of-memory conditions.

```

min_id = SELECT MIN(id) FROM orders WHERE new_column IS NULL;

max_id = SELECT MAX(id) FROM orders;

batch_size = 5000;

current = min_id;

WHILE current <= max_id:

UPDATE orders SET new_column = derive(old_column)

WHERE id >= current AND id < current + batch_size

AND new_column IS NULL;

COMMIT;

SLEEP 100ms; -- allow replication to catch up

current = current + batch_size;

```

6. Integrate with CI/CD and Migration Framework

Migration tooling should be a first-class citizen of the CI/CD pipeline:

7. Execute, Monitor, and Roll Back in Production

Production migration execution requires an operational runbook, not just code:

8. Document and Archive

Every migration that reaches production becomes part of the permanent history of the system. Treat it accordingly.


Output Format

When helping a user with a database migration, produce output in the following structure:

## Migration Plan: [brief description]

### Classification
- Migration Type: [Additive | Destructive | Type Change | Constraint Addition | Backfill | Expand-Contract]
- Risk Tier: [1 (Safe) | 2 (Caution) | 3 (High Risk)]
- Estimated Lock Duration: [e.g., < 1 second, 5-30 seconds, minutes -- table scan required]
- Estimated Execution Time: [e.g., < 5 seconds, 30 minutes backfill at 5k rows/batch]
- Deployment Phases Required: [1 | 2 | 3 | 4]

### Pre-Migration Checklist
- [ ] Backup verified and restorable
- [ ] Staging migration applied successfully
- [ ] All application references to affected objects identified
- [ ] Dependent views/triggers/stored procedures reviewed
- [ ] Replication lag baseline measured: [current value]
- [ ] On-call team notified

### Migration Files

#### Phase [N]: [Description]
**File:** `YYYYMMDDHHMMSS_description.sql`
**Deploy before or after app release:** [before | after | with]

-- Migration: [description]

-- Author: [team]

-- Date: [date]

-- Risk: Tier [1|2|3]

-- Lock Type: [ACCESS SHARE | ROW EXCLUSIVE | ACCESS EXCLUSIVE]

-- Estimated execution time on production: [X seconds/minutes]

-- Rollback: [rollback SQL or procedure]

-- Dependencies: [prior migrations or app release versions]

SET lock_timeout = '5s';

SET statement_timeout = '30s';

BEGIN;

-- [migration SQL here]

COMMIT;


#### Backfill Script (if applicable)
**Run as:** [migration framework | background job | manual]
**Batch size:** [N rows]
**Monitor:** [what to watch]

-- Backfill: [description]

-- Batch over IDs, sleep between batches

DO $$

DECLARE

batch_start BIGINT;

batch_end BIGINT;

max_id BIGINT;

BEGIN

-- [batched backfill logic]

END $$;


### Rollback Procedure
1. [Step 1 with exact SQL or command]
2. [Step 2]
3. [Verification query to confirm rollback succeeded]

### Post-Migration Validation

-- Run immediately after migration applies

-- [Verification queries asserting expected schema state]

-- [Row count assertions]

-- [Constraint verification]


### Follow-Up Actions
- [ ] [Contract phase ticket created with due date]
- [ ] [Schema documentation updated]
- [ ] [ADR written if non-standard pattern used]

Rules

  1. NEVER modify an already-applied migration file. Once a migration has been executed in any environment beyond local development, it is immutable. Flyway enforces this with checksums; enforce it manually for other tools. Corrections go in a new, forward-only migration.
  1. NEVER add a NOT NULL column with no default in a single ALTER TABLE on a table with existing rows. In Postgres before version 11, this causes a full table rewrite. In Postgres 11+, it is safe ONLY if the default is a constant (not a function call). Always verify Postgres version before choosing this shortcut. MySQL always rewrites the table for structural changes regardless of version.
  1. NEVER run an unbatched UPDATE or DELETE against a table with more than 100,000 rows in a single transaction. The transaction log growth, lock duration, and replication lag risk are unacceptable. Batch all DML in the 1,000-10,000 row range.
  1. NEVER apply a destructive migration (DROP COLUMN, DROP TABLE) in the same release that removes the application code referencing it. Always allow at least one full release cycle where the application has stopped using the object before dropping it. Rolling deployments mean old application instances may still be running when the migration applies.
  1. NEVER skip the lock_timeout setting on DDL statements in production. Without a lock timeout, a long-running query holding a conflicting lock will cause the DDL to queue indefinitely, which in turn causes ALL subsequent connections needing a table lock to queue behind it -- creating a connection pile-up that can take down the application.
  1. NEVER create an index without CONCURRENTLY on a table larger than 10,000 rows in a live production database. Non-concurrent index creation acquires an exclusive lock for the duration of the index build, which can take seconds to hours on large tables.
  1. ALWAYS test migrations against a database restored from a recent production backup before executing in production. Staging environments with synthetic data are insufficient for validating execution time, lock behavior, and constraint violations. Use production-restore pipelines in CI or pre-production environments.
  1. ALWAYS validate foreign key constraints with NOT VALID first on tables with existing data, then validate separately. Adding a plain REFERENCES constraint on a large table with existing rows triggers a full table scan under a lock. NOT VALID skips the scan; VALIDATE CONSTRAINT performs the scan later with a weaker lock level (ShareUpdateExclusiveLock in Postgres).
  1. NEVER allow the application to handle two schema states (expand phase) for more than 30 days. Dual-write code is complexity debt. Expand-contract phases must have explicit completion timelines enforced by follow-up tickets. Abandoned expand phases are one of the most common causes of schema confusion in long-running systems.
  1. ALWAYS confirm that enum type changes are safe for your database version before applying. In Postgres, adding a new value to an ENUM type is non-transactional (it cannot be rolled back within a transaction). In Postgres < 12, adding an enum value requires a catalog rewrite. In all versions, renaming an enum value or removing a value is not natively supported -- it requires creating a new type, migrating columns, and dropping the old type, which is a full expand-contract operation.

Edge Cases

Large Table with Active Write Traffic (> 50 million rows, > 1,000 writes/second)

Standard ALTER TABLE operations will cause unacceptable lock wait times. Use online schema change tooling:

Polyglot or Multi-Tenant Schema (schema-per-tenant or database-per-tenant)

When migrations must be applied across hundreds or thousands of schemas/databases:

Circular Dependency Between Application Deployment and Migration

Sometimes the migration requires application code to exist (to populate data) and the application code requires the migration to exist (to start up). This is a genuine chicken-and-egg problem:

Failed Migration Leaving Schema in Partial State

When a migration fails midway and the database is not fully transactional for DDL (MySQL, or Postgres migrations that span multiple transactions):

Zero-Downtime Requirement with Blue-Green Deployments

Blue-green deployments swap all traffic from the old version (blue) to the new version (green) simultaneously. Unlike rolling deployments, there is a brief moment where only one version is active. This changes the migration timing constraints:

Migrations in Microservices with Shared Database (Anti-Pattern Remediation)

When multiple services share a single database schema and need to migrate it:

Enum Value Removal or Rename (Postgres)

Postgres does not support removing or renaming values from an ENUM type natively. This is one of the most dangerous schema changes in Postgres:


Example

User Input: "We have a users table with 80 million rows. We need to rename the column username to display_name and change its type from VARCHAR(50) to VARCHAR(100). We use Postgres 14, Flyway, and deploy via Kubernetes rolling updates with 3 replicas. We cannot have more than 30 seconds of downtime."


Output:

Migration Plan: Rename users.username to display_name and widen VARCHAR(50) to VARCHAR(100)

Classification

Pre-Migration Checklist


Phase 1: Expand -- Add display_name Column

File: 20240319020000_expand_add_display_name_to_users.sql

Deploy: BEFORE application Release 1 (app still reads/writes only username)

-- Migration: Add display_name column to users table (Phase 1 of 4 -- Expand)
-- Author: platform-team
-- Date: 2024-03-19
-- Risk: Tier 3 -- part of expand-contract for username -> display_name rename
-- Lock Type: ACCESS EXCLUSIVE (brief, catalog-only change for VARCHAR widening)
-- Estimated execution time on production: < 2 seconds
-- Rollback: DROP COLUMN IF EXISTS display_name; -- safe, application does not use it yet
-- Dependencies: None -- apply before Release 1

SET lock_timeout = '5s';
SET statement_timeout = '30s';

BEGIN;

-- Add the new column as nullable (no default needed -- backfill handles population)
ALTER TABLE users ADD COLUMN IF NOT EXISTS display_name VARCHAR(100);

-- Also widen the existing column in the same transaction while we hold the lock
-- (VARCHAR widening is catalog-only in Postgres -- no table rewrite)
ALTER TABLE users ALTER COLUMN username TYPE VARCHAR(100);

-- Update the dependent view to include both columns during transition
CREATE OR REPLACE VIEW user_search_view AS
  SELECT
    id,
    username,         -- keep for backward compatibility
    display_name,     -- new column (may be NULL during backfill)
    email,
    created_at
  FROM users;

COMMIT;

Post-Phase-1 Validation:

-- Confirm column exists and types are correct
SELECT column_name, data_type, character_maximum_length, is_nullable
FROM information_schema.columns
WHERE table_name = 'users'
  AND column_name IN ('username', 'display_name');
-- Expected: both present, both VARCHAR(100), display_name nullable

-- Confirm view was updated
SELECT viewname, definition FROM pg_views WHERE viewname = 'user_search_view';

Phase 2: Application Release 1 -- Dual Write

Deploy Release 1 after Phase 1 migration is confirmed applied.

Application code changes required in Release 1:

```ruby

before_save :sync_display_name

def sync_display_name

self.display_name = self.username if display_name.blank?

end

```


Phase 2b: Backfill display_name from username

Run as: Background job deployed with Release 1 -- NOT as a Flyway migration (too slow for migration framework sequence)

Batch size: 5,000 rows per transaction

Total estimated time: 80,000,000 rows / 5,000 per batch = 16,000 batches * ~6 seconds per batch (UPDATE + sleep) ≈ 27 hours

Monitor: Poll replication lag every 30 seconds; pause if lag > 30s

-- Backfill Script: Populate users.display_name from users.username
-- Run as a background job with retry capability
-- Track progress in migration_progress table

CREATE TABLE IF NOT EXISTS migration_progress (
  migration_name TEXT PRIMARY KEY,
  last_processed_id BIGINT NOT NULL DEFAULT 0,
  rows_processed BIGINT NOT NULL DEFAULT 0,
  started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO migration_progress (migration_name, last_processed_id)
VALUES ('backfill_display_name', 0)
ON CONFLICT (migration_name) DO NOTHING;

DO $$
DECLARE
  batch_size    INT     := 5000;
  current_id    BIGINT;
  next_id       BIGINT;
  max_id        BIGINT;
  rows_updated  INT;
BEGIN
  SELECT last_processed_id INTO current_id
  FROM migration_progress WHERE migration_name = 'backfill_display_name';

  SELECT MAX(id) INTO max_id FROM users;

  WHILE current_id < max_id LOOP
    next_id := current_id + batch_size;

    UPDATE users
    SET display_name = username,
        updated_at   = NOW()  -- only if your schema tracks this
    WHERE id > current_id
      AND id <= next_id
      AND display_name IS NULL;

    GET DIAGNOSTICS rows_updated = ROW_COUNT;

    UPDATE migration_progress
    SET last_processed_id = next_id,
        rows_processed    = rows_processed + rows_updated,
        updated_at        = NOW()
    WHERE migration_name = 'backfill_display_name';

    COMMIT;

    -- Allow replica to catch up
    PERFORM pg_sleep(0.1);  -- 100ms sleep between batches

    current_id := next_id;
  END LOOP;
END $$;

Backfill Completion Verification:

-- Must return 0 before proceeding to Phase 3
SELECT COUNT(*) FROM users WHERE display_name IS NULL;

-- Confirm progress table shows expected row count
SELECT * FROM migration_progress WHERE migration_name = 'backfill_display_name';

Phase 3: Application Release 2 -- Read from display_name

Deploy Release 2 AFTER backfill completion is verified (display_name IS NULL count = 0).

File: 20240322040000_add_not_null_constraint_display_name.sql

Deploy: WITH Application Release 2

-- Migration: Add NOT NULL constraint to display_name (Phase 3 of 4)
-- Author: platform-team
-- Date: 2024-03-22
-- Risk: Tier 2 -- constraint addition using NOT VALID + VALIDATE pattern
-- Lock Type: ShareUpdateExclusiveLock during VALIDATE (does not block reads or writes)
-- Estimated execution time: NOT VALID instant; VALIDATE ~10 minutes for 80M rows
-- Rollback: ALTER TABLE users ALTER COLUMN display_name DROP NOT NULL;
-- Dependencies: Backfill must be complete (display_name IS NULL = 0 rows)

SET lock_timeout = '5s';

BEGIN;
-- Step A: Add check constraint without scanning existing rows
ALTER TABLE users
  ADD CONSTRAINT users_display_name_not_null
  CHECK (display_name IS NOT NULL) NOT VALID;
COMMIT;

-- Step B: Validate in a separate transaction (uses ShareUpdateExclusiveLock)
-- This scans all rows but does NOT block reads or normal writes
BEGIN;
ALTER TABLE users VALIDATE CONSTRAINT users_display_name_not_null;
COMMIT;

-- Step C: In Postgres 12+, convert to true NOT NULL using the validated constraint
-- This is a catalog-only change (no table scan, < 100ms lock)
BEGIN;
ALTER TABLE users ALTER COLUMN display_name SET NOT NULL;
ALTER TABLE users DROP CONSTRAINT users_display_name_not_null;
COMMIT;

Phase 4: Contract -- Drop username Column

File: 20240329020000_contract_drop_username_from_users.sql

Deploy: AFTER Application Release 3 removes all remaining references to username

Minimum wait: 72 hours after Release 2 is fully rolled out and stable (all pods on new version, zero error-rate increase)

-- Migration: Drop username column from users (Phase 4 of 4 -- Contract)
-- Author: platform-team
-- Date: 2024-03-29
-- Risk: Tier 3 -- destructive, irreversible without backup restore
-- Lock Type: ACCESS EXCLUSIVE (brief, catalog-only column drop)
-- Estimated execution time: < 1 second
-- Rollback: RESTORE FROM BACKUP -- this operation cannot be reversed in-place
-- Pre-condition: Confirm no application code references users.username
-- Pre-condition: Confirm Release 3 has been running for >= 72 hours with no errors
-- Dependencies: Application Release 3 fully deployed and verified

SET lock_timeout = '5s';
SET statement_timeout = '10s';

BEGIN;

-- Final guard: fail loudly if any rows still have a display_name mismatch
-- (should be impossible if backfill and dual-write worked correctly)
DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM users
    WHERE display_name IS DISTINCT FROM username
    LIMIT 1
  ) THEN
    RAISE EXCEPTION 'Data mismatch detected: display_name and username differ. Aborting drop.';
  END IF;
END $$;

-- Drop the old column
ALTER TABLE users DROP COLUMN IF EXISTS username;

-- Update the search view to remove the deprecated column
CREATE OR REPLACE VIEW user_search_view AS
  SELECT
    id,
    display_name,
    email,
    created_at
  FROM users;

COMMIT;

Post-Phase-4 Validation:

-- Confirm username column is gone
SELECT column_name FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'username';
-- Expected: 0 rows

-- Confirm display_name is present, NOT NULL, VARCHAR(100)
SELECT column_name, data_type, character_maximum_length, is_nullable
FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'display_name';
-- Expected: 1 row, character_maximum_length=100, is_nullable=NO

-- Confirm view is healthy
SELECT COUNT(*) FROM user_search_view LIMIT 1;

Rollback Procedures by Phase

| Phase | Rollback Method | Estimated Time |

|-------|----------------|----------------|

| Phase 1 (Expand DDL) | ALTER TABLE users DROP COLUMN display_name; | < 1 second |

| Phase 2 (Dual Write App) | Redeploy Release 0 (app only) | 5-10 minutes (Kubernetes rollback) |

| Phase 2b (Backfill) | Stop background job; display_name remains partially populated but app still reads username | Instant |

| Phase 3 (NOT NULL + Read Switch) | ALTER TABLE users ALTER COLUMN display_name DROP NOT NULL; then redeploy Release 1 | < 1 second DDL + 5-10 min app rollback |

| Phase 4 (Drop username) | BACKUP RESTORE ONLY -- no in-place recovery | 30-120 minutes depending on backup size |


Follow-Up Actions

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.