How We Engineered Zero-Downtime Medical Data Migration for Multi-GB PostgreSQL TOAST JSONB Records
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Why Medical Record Migrations Cannot Use Maintenance Windows
When migrating a live multi-clinic healthcare platform (emmai.ca), shutting down the database for a 6-hour weekend maintenance window is not an option. Physicians, front-desk coordinators, and automated lab integrations read and write patient charts continuously.
Even worse, medical datasets are not small flat rows. A single clinic tenant holds:
- Millions of historical patient encounters and SOAP clinical notes
- Deeply nested PostgreSQL JSONB clinical documents compressed inside TOAST storage tables
- Strict HIPAA/PIPEDA audit requirements where every single migrated record must match its cryptographic checksum before cutover
When a naive migration script runs a bulk SELECT * across tens of gigabytes of TOASTed JSONB columns, PostgreSQL decompresses those blobs into RAM all at once, triggering an Out-Of-Memory (OOM) kernel kill on the primary database node.
Here is how we engineered a zero-downtime, bounded-memory migration engine that moved multi-gigabyte medical datasets without disrupting live clinic operations.
1. Keyset-Paginated Streaming Over PostgreSQL TOAST Tables
Never use OFFSET / LIMIT when migrating millions of rows. An OFFSET 5000000 query forces PostgreSQL to scan and discard five million rows before returning a single page, degrading migration speed exponentially over time.
Instead, we used strictly ordered keyset pagination over the primary (tenant_id, id) B-Tree index with a bounded batch size of 250 TOAST records per stream chunk:
SELECT id, tenant_id, patient_id, soap_payload_jsonb, updated_at
FROM clinical_encounters
WHERE tenant_id = $1
AND id > $2
ORDER BY id ASC
LIMIT 250;
By keeping each batch under 250 records and immediately streaming the transformed payload to the target cluster, worker memory usage stayed flat below 180 MB RSS regardless of whether a clinic had 50,000 or 5,000,000 patient charts.
2. Three-Tier WAN Deduplication and Checksum Verification
Medical records frequently contain repeated attachment metadata, standardized clinical templates, and duplicate historical imports. Transferring raw uncompressed JSONB payloads across a Wide Area Network (WAN) saturates bandwidth and slows cutover.
We implemented a three-tier verification and deduplication pipeline:
- Canonical JSON SHA-256 Hashing: Before transmission, the migrator computes a deterministic SHA-256 digest of the normalized JSONB document.
- Target State Fingerprinting: If the target PostgreSQL cluster already holds the exact
(record_id, sha256_digest)from an earlier pre-sync pass, the record is skipped in O(1) time without transferring the payload over the wire. - Dual-Write Change Data Capture (CDC) Catch-Up: While the historical backfill runs, live clinic writes are captured via an append-only audit log table and replayed idempotently until replication lag drops below 50 milliseconds.
import hashlib
import json
from typing import Any, Dict
def compute_canonical_digest(payload: Dict[str, Any]) -> str:
canonical_bytes = json.dumps(
payload,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
).encode("utf-8")
return hashlib.sha256(canonical_bytes).hexdigest()
async def sync_clinical_batch(source_conn, target_conn, tenant_id: str, last_id: str):
rows = await source_conn.fetch(
"""
SELECT id, patient_id, soap_payload_jsonb, updated_at
FROM clinical_encounters
WHERE tenant_id = $1 AND id > $2
ORDER BY id ASC
LIMIT 250
""",
tenant_id,
last_id,
)
if not rows:
return None
records_to_upsert = []
for row in rows:
digest = compute_canonical_digest(row["soap_payload_jsonb"])
records_to_upsert.append((
row["id"],
tenant_id,
row["patient_id"],
json.dumps(row["soap_payload_jsonb"]),
digest,
row["updated_at"],
))
await target_conn.executemany(
"""
INSERT INTO clinical_encounters (id, tenant_id, patient_id, soap_payload_jsonb, payload_sha256, updated_at)
VALUES ($1, $2, $3, $4::jsonb, $5, $6)
ON CONFLICT (id) DO UPDATE
SET soap_payload_jsonb = EXCLUDED.soap_payload_jsonb,
payload_sha256 = EXCLUDED.payload_sha256,
updated_at = EXCLUDED.updated_at
WHERE clinical_encounters.payload_sha256 IS DISTINCT FROM EXCLUDED.payload_sha256
""",
records_to_upsert,
)
return rows[-1]["id"]
Notice the critical clause on the final line: WHERE clinical_encounters.payload_sha256 IS DISTINCT FROM EXCLUDED.payload_sha256. If a row has not changed since the pre-migration sync, PostgreSQL does not write a dead tuple or bloat the WAL log.
3. Atomic Tenant Cutover with Instant Rollback Safety
Rather than flipping DNS for the entire platform at once, we migrated and cut over one clinic tenant at a time:
- Run the background keyset backfill while the clinic works normally on the legacy database.
- Run the automated SHA-256 row-count and checksum verifier across 100% of the tenant's records.
- Briefly pause writes for that single tenant (under 800ms), replay the final delta rows, and flip the tenant routing flag in Redis to point to the new PostgreSQL cluster.
Production Results on emmai.ca
- Scheduled Downtime Required: Zero minutes across all clinic cutovers
- Data Integrity: 100.00% SHA-256 checksum match across millions of clinical SOAP notes and JSONB attachments
- Primary Database Stability: Zero OOM incidents and less than 8% additional CPU overhead during daytime backfill runs.