Large tables cannot be altered with blocking operations or migrated in one transaction. Use expand and contract with batched backfills. 1. Expand (backward-compatible schema change) - Add new nullable columns or a new table. In PostgreSQL, adding a nullable column (or one with a constant default, since PostgreSQL 11) is a fast metadata change; in MySQL 8 use ALGORITHM=INSTANT where supported. - Create indexes without blocking writes: CREATE INDEX CONCURRENTLY (PostgreSQL) or online DDL (MySQL InnoDB, or gh-ost and pt-online-schema-change for heavy changes). - Run these migrations with Flyway or Liquibase as a separate deployment step, with lock timeouts (SET lock_timeout) so they fail fast instead of blocking production traffic. Flyway can mark migrations that must run outside a transaction (required for CONCURRENTLY). 2. Dual write - Deploy a Spring Boot release that writes both the old and new columns (or tables), and reads from the old one. 3. Backfill in batches - A resumable job (Spring Batch, or a scheduled task with ShedLock) copies data in chunks by primary key range: UPDATE orders SET new_status = legacy_status WHERE id BETWEEN :from AND :to AND new_status IS NULL; - Small batches (thousands of rows), short transactions, pauses between batches, progress tracking, and monitoring of replication lag and database load. 4. Verify and switch reads - Compare old and new data with checksums or sample queries; then release code that reads from the new structure (behind a feature flag if useful). 5. Contract - After all instances use the new structure and rollback is no longer needed, stop writing the old column, then drop it in a later release. Restructuring an entire table - Create the new table, backfill in batches, keep it in sync with triggers or change data capture (Debezium), then switch reads and writes, and finally rename or drop the old table in a brief maintenance step or behind a view. Safety measures - Rehearse on a production-sized copy to measure timing and locking. - Backups or point-in-time recovery before starting. - Keep every intermediate state compatible with both the old and new application versions, so rolling back the application never requires rolling back the database. - Communicate and monitor: dashboards for locks, slow queries and error rates during the migration.
Ravindra Wadile · · 0 likes