Database schema changes are among the most dangerous production operations — a simple ALTER TABLE on a large table can lock it for minutes, causing query timeouts and service downtime across your entire application. Zero-downtime migrations using the expand-contract pattern let you ship schema changes to your Hong Kong VPS production database while the application continues serving Asia-Pacific users without interruption, even during peak hours.
Why Naive Migrations Cause Downtime
| Operation | Risk | Table size impact |
|---|---|---|
| ADD COLUMN NOT NULL without DEFAULT | Rewrites entire table | Minutes for large tables |
| DROP COLUMN | Requires AccessExclusiveLock | Brief but blocks all queries |
| CREATE INDEX (without CONCURRENTLY) | Locks table for reads + writes | Minutes to hours |
| RENAME COLUMN/TABLE | Breaks running app code immediately | Instant but catastrophic |
| ALTER COLUMN TYPE | Full table rewrite + lock | Minutes to hours |
The Expand-Contract Pattern
Instead of making breaking changes atomically, split them into three phases deployed separately:
<code">
Phase 1 — EXPAND: Add new columns/tables alongside old ones
Old app code still works (reads old column)
New app code writes to BOTH old and new
Phase 2 — MIGRATE: Backfill existing data from old to new schema
Both old and new app code work simultaneously
Phase 3 — CONTRACT: Remove old columns/tables once new code is stable
(can happen days/weeks later)
Example 1: Rename a Column (Safe)
Phase 1: Expand — Add New Column
<code"># WRONG (causes downtime — app breaks immediately):
ALTER TABLE users RENAME COLUMN full_name TO display_name;
# RIGHT — Phase 1: Add new column alongside old
ALTER TABLE users ADD COLUMN display_name TEXT;
# Trigger to keep both columns in sync during transition
CREATE OR REPLACE FUNCTION sync_display_name()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.full_name IS NOT NULL AND NEW.display_name IS NULL THEN
NEW.display_name = NEW.full_name;
END IF;
IF NEW.display_name IS NOT NULL AND NEW.full_name IS NULL THEN
NEW.full_name = NEW.display_name;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER sync_display_name_trigger
BEFORE INSERT OR UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION sync_display_name();
Phase 2: Backfill Existing Rows
<code"># Backfill in batches to avoid locking the table
DO $$
DECLARE
batch_size INT := 5000;
last_id BIGINT := 0;
max_id BIGINT;
BEGIN
SELECT MAX(id) INTO max_id FROM users;
WHILE last_id < max_id LOOP UPDATE users SET display_name = full_name WHERE id > last_id AND id <= last_id + batch_size
AND display_name IS NULL;
last_id := last_id + batch_size;
RAISE NOTICE 'Migrated up to id %', last_id;
PERFORM pg_sleep(0.1); -- Brief pause to reduce I/O pressure
END LOOP;
END $$;
Phase 3: Contract — Remove Old Column (after new code deployed)
<code"># Only after all application code uses display_name exclusively: DROP TRIGGER sync_display_name_trigger ON users; DROP FUNCTION sync_display_name(); ALTER TABLE users DROP COLUMN full_name;
Example 2: Add NOT NULL Column (Safe)
<code"># WRONG — blocks table until all rows written: ALTER TABLE orders ADD COLUMN region TEXT NOT NULL DEFAULT 'HK'; # RIGHT — Phase 1: Add nullable first ALTER TABLE orders ADD COLUMN region TEXT; # Phase 2: Backfill UPDATE orders SET region = 'HK' WHERE region IS NULL; # Phase 3: Add constraint after backfill ALTER TABLE orders ALTER COLUMN region SET NOT NULL; ALTER TABLE orders ALTER COLUMN region SET DEFAULT 'HK'; # PostgreSQL 11+: fast for constant defaults (doesn't rewrite table) -- In PG 11+, constant DEFAULT doesn't require table rewrite -- So this IS safe: ALTER TABLE orders ADD COLUMN region TEXT NOT NULL DEFAULT 'HK'; -- But only for truly constant defaults — verify your PG version first
Example 3: Create Index Without Locking
<code"># WRONG — locks table for duration of index build: CREATE INDEX idx_orders_user_id ON orders(user_id); # RIGHT — always use CONCURRENTLY for production: CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id); -- Takes longer but doesn't lock reads or writes # Monitor progress: SELECT schemaname, tablename, indexname, idx_scan FROM pg_stat_user_indexes WHERE indexname = 'idx_orders_user_id'; # If CONCURRENTLY fails (rare), check for INVALID index and drop/retry: SELECT indexname, indisvalid FROM pg_indexes JOIN pg_index ON pg_indexes.indexname::text = pg_indexes.indexname WHERE tablename = 'orders'; -- Drop an invalid index: DROP INDEX CONCURRENTLY idx_orders_user_id;
Example 4: Large Table Column Type Change
<code"># WRONG — locks and rewrites entire table:
ALTER TABLE events ALTER COLUMN payload TYPE JSONB USING payload::jsonb;
# RIGHT — add new column, migrate, swap:
-- Phase 1
ALTER TABLE events ADD COLUMN payload_jsonb JSONB;
-- Phase 2: batch convert
DO $$
DECLARE last_id BIGINT := 0;
BEGIN
LOOP
UPDATE events
SET payload_jsonb = payload::jsonb
WHERE id > last_id AND id <= last_id + 10000
AND payload_jsonb IS NULL AND payload IS NOT NULL;
EXIT WHEN NOT FOUND;
last_id := last_id + 10000;
PERFORM pg_sleep(0.05);
END LOOP;
END $$;
-- Phase 3: swap (deploy code using payload_jsonb, then drop payload)
ALTER TABLE events DROP COLUMN payload;
ALTER TABLE events RENAME COLUMN payload_jsonb TO payload;
Migration Tools
Flyway / Liquibase
<code"># Flyway migration file: V2__add_display_name.sql -- EXPAND phase (safe to deploy while old app version runs) ALTER TABLE users ADD COLUMN display_name TEXT; CREATE INDEX CONCURRENTLY idx_users_display_name ON users(display_name); # Run migrations before deploying new app code: flyway -url=jdbc:postgresql://localhost/myapp -user=myapp_user migrate
Django Migrations
<code"># 0005_add_display_name.py — expand phase migration
from django.db import migrations, models
class Migration(migrations.Migration):
operations = [
# Safe: add nullable column
migrations.AddField(
model_name='user',
name='display_name',
field=models.CharField(max_length=255, null=True, blank=True),
),
]
# 0006_backfill_display_name.py — data migration
from django.db import migrations
def backfill_display_name(apps, schema_editor):
User = apps.get_model('users', 'User')
User.objects.filter(display_name__isnull=True).update(
display_name=models.F('full_name')
)
class Migration(migrations.Migration):
operations = [
migrations.RunPython(backfill_display_name, migrations.RunPython.noop),
]
Migration Checklist
| Before Running | Check |
|---|---|
| Table size | SELECT pg_size_pretty(pg_total_relation_size('tablename')); |
| Active connections | SELECT count(*) FROM pg_stat_activity WHERE datname='mydb'; |
| Lock wait timeout set | SET lock_timeout = '5s'; before the ALTER |
| Backup taken | pg_dump -Fc mydb > pre_migration_backup.dump |
| Rollback plan ready | DROP COLUMN / DROP INDEX CONCURRENTLY prepared |
Conclusion
Zero-downtime database migrations on a Hong Kong VPS require a mental model shift — from “apply schema change” to “expand first, migrate data, contract later”. The expand-contract pattern lets you ship schema changes while your application serves Asia-Pacific users continuously: no maintenance windows, no late-night deployments to avoid China peak hours. Combined with CREATE INDEX CONCURRENTLY for index additions and batch data migrations with brief sleep intervals, your PostgreSQL or MySQL database handles structural changes without a single dropped request.
Ship schema changes safely: Browse Server.HK Hong Kong VPS plans — all VPS plans give you full PostgreSQL control to implement these migration patterns without managed database restrictions.