28 tháng 11, 2025 · 10 phút đọc

Database migration strategy: zero-downtime trong production

Expand/contract pattern, backward-compatible migrations và rollback strategies để deploy database changes an toàn.

Database migration strategy: zero-downtime trong production

Database migrations là một trong những rủi ro cao nhất trong deployment process. Schema changes sai cách có thể gây downtime, data loss, hoặc application errors khó debug. Zero-downtime migrations đòi hỏi hiểu rõ cách application và database tương tác.

Expand/Contract Pattern

Thay vì rename column trong một migration, dùng 3 phases: (1) Expand — thêm column mới, populate song song với column cũ. (2) Deploy code đọc/ghi cả hai columns. (3) Contract — sau khi confirm production ổn định, drop column cũ. Mỗi phase là deployment riêng biệt.

Pattern này đảm bảo mọi lúc đều có backward compatibility — old code và new code đều hoạt động trong transition period. Quan trọng khi có multiple server instances running đồng thời.

Database migration flowchart
Expand/Contract pattern đảm bảo zero downtime khi thay đổi schema

Migrations nguy hiểm cần tránh

DROP TABLE/COLUMN: irreversible, cần backup verify trước. Rename column: breaking change, dùng expand/contract thay vì. ADD COLUMN NOT NULL without default: locks table trong PostgreSQL (dùng ADD COLUMN với DEFAULT trước, sau đó SET NOT NULL). Changing column type: often requires rebuild index.

Lock Timeouts

Một số DDL statements trong PostgreSQL yêu cầu ACCESS EXCLUSIVE lock — block mọi reads và writes. Set lock_timeout thấp (vài giây) để migration fail fast nếu không lấy được lock, thay vì block production traffic. Retry logic với exponential backoff.

Migration Tools

Flyway và Liquibase: mature, nhiều enterprise features. Prisma Migrate: developer-friendly, tích hợp tốt với ORM. Atlas: schema-as-code với drift detection. Drizzle migrations: type-safe, SQL-first. Chọn tool phù hợp với ecosystem và team preference.

Rollback Strategy

Viết down migration cho mọi up migration khi có thể. Test rollback trong staging trước. Với destructive changes (DROP), rollback không thể — backup trước deployment là bắt buộc. Point-in-time recovery (PITR) trên managed databases là safety net quan trọng.