Zero-Downtime Production Database Migration
Hard · System Design · Software Engineer · Onsite
Prompt
Plan an online migration of a live 2 TB production database from Microsoft SQL Server to PostgreSQL with zero downtime, strict transactional consistency, and a post-cutover rollback safety net. Peak daytime traffic drives heavy concurrent transactional writes, and two distinct database consumers must remain supported throughout:
- Internal Transactional Service: An in-house backend executing continuous read/write transactions; its data-access adapter can be swapped, though core domain logic should remain untouched.
- External Read-Only Analytics Application: A vendor-managed reporting client whose source code cannot be altered and which cannot execute federated queries across two databases.
Operational & Migration Goals - Continuous Synchronization: Keep the legacy SQL Server cluster and the new PostgreSQL cluster closely synchronized with minimal replication lag while migration is in progress. - Transparent Reader Cutover: Eventually serve the unmodifiable read-only analytics client from PostgreSQL without requiring vendor code changes. - Live Parity Verification: Continuously validate row-by-row integrity between both database engines before cutting over. - Safe Cutover & Reversibility: Switch authoritative traffic with negligible service disruption, while preserving a zero-data-loss rollback path back to SQL Server if issues surface after cutover.
Illustrative Scenario
- During initial snapshot copying of the 2 TB dbo.Invoices dataset (id = 101 starting at $420), the internal writer updates id = 101 to $480 and inserts id = 102 ($150), while the vendor BI client queries bi-sql.internal:1433 uninterrupted.
- After PostgreSQL catches up, passes full parity verification, and takes over writes (id = 103 inserted at $310), a reverse synchronization stream keeps SQL Server ready for a zero-loss rollback.
Scope & Expectations
- Synchronization & Routing Topology: Architecture comparing log-based Change Data Capture (CDC), dual writes, and logical replication, plus network/protocol handling for the unmodifiable analytics reader.
- Schema, Code & Parity Strategy: Mapping rules for SQL Server data types, collations, identity columns, and stored procedures, paired with live reconciliation between both engines.
- Cutover & Rollback Runbook: Ordered steps to transition reads and writes safely, plus a post-cutover rollback plan that retains every post-cutover transaction.
Step-by-step walkthrough
Clarify requirements and migration goals
Copying 2 TB of static files takes a couple of hours. Migrating a live 2 TB production database across two different database engines (Microsoft SQL Server to PostgreSQL) is hard for four specific reasons: 1. Continuous writes: The source keeps mutating every millisecond, yet PostgreSQL must end up transactionally identical to SQL Server without tearing multi-row transactions apart. 2. Moving-target verification: You have to prove both databases hold the exact same data while rows are changing in flight. 3. Unmodifiable reader: A third-party analytics client speaks only SQL Server's network protocol and SQL dialect, and we cannot change its code. 4. Zero-data-loss rollback: If PostgreSQL misbehaves three days after cutover, switching back to SQL Server must keep every single transaction written after cutover.
Functional requirements - Keep SQL Server and PostgreSQL continuously synchronized throughout the migration window. - Migrate the internal write service by swapping its data-access layer (the thin module that sends SQL queries to the database) without rewriting core business logic. - Switch the third-party read-only analytics service onto PostgreSQL with zero code changes on the vendor's side.
Non-functional requirements - Availability: Zero downtime for reads. At final write cutover, hold incoming writes in memory for ~20–60 seconds rather than rejecting them, so callers experience one slow response instead of errors. - Strict consistency: Readers of the target never observe half of a multi-row transaction, and at cutover zero committed transactions are lost or duplicated. - Low lag & full reversibility: Steady-state replication lag under 2 seconds at p99, continuous parity verification, and a 4-week zero-data-loss rollback window.
Working assumptions to confirm with the interviewer - SQL Server 2016 SP1+ (which supports native Change Data Capture in Standard and Enterprise editions) and PostgreSQL 17 as the target (which supports logical failover slots so our rollback stream survives a PostgreSQL primary failover). - Peak write traffic is 1,000 transactions/s touching 3 rows each during 10 business hours/day, across ~200 tables, ~150 stored procedures, and a handful of scheduled SQL Server Agent jobs. - The analytics service connects via a corporate DNS name we control (
bi-sql.internal:1433).Back-of-the-envelope numbers
Let's turn the 2 TB dataset and write rate into concrete throughput, storage, and catch-up numbers:
Dataset size 2 TB total on disk (~1.4 TB table data + ~0.6 TB indexes) Write volume Peak: 1,000 tx/s * 3 rows/tx = 3,000 row changes/s Business-hours avg: ~1,500 row changes/s * 36,000 s (10 h) = 54M row changes/day CDC event bandwidth ~500 B average row -> ~1 KB per event (before + after row + metadata) Peak stream: 3,000 * 1 KB = 3 MB/s; daily volume: 54M * 1 KB = 54 GB/day Kafka buffer 7 days retention * 54 GB/day = 378 GB logical (* 3 replicas ~= 1.1 TB raw) SQL Server overhead 3 days local CDC table retention ~= 162 GB extra disk on SQL Server Initial bulk copy 1.4 TB / (8 parallel streams * 25 MB/s = 200 MB/s) = 7,000 s ~= 2 hours Applier throughput Target >= 15,000 rows/s (5x peak) using batched transaction commits 1-hour outage catch Backlog at peak: 3,000 rows/s * 3,600 s = 10.8M rows Net drain rate: 15,000 apply/s - 3,000 incoming/s = 12,000 rows/s Catch-up time: 10,800,000 / 12,000 = 900 s = 15 minutes Full checksum scan 1.4 TB read at 200 MB/s per engine ~= 2 hours (run off-peak in parallel) Random row sampling 100 rows/s * 86,400 s ~= 8.6M verified rows/dayThree design decisions fall directly out of this math: - 3 MB/s is small enough for a single ordered stream. One Kafka partition and one ordered applier easily keep up while preserving global transaction commit order—eliminating cross-table race conditions. - Full verification takes ~2 hours, so verification must be two-tiered: lightweight continuous random sampling all day plus a full primary-key chunk checksum pass overnight and before cutover. - CDC writes extra data onto the production SQL Server, so we must monitor source log/disk growth and wire up a kill switch that protects production first.
Client interfaces and target data model
Before moving any bytes, we lock down four clean interfaces and a metadata schema inside PostgreSQL. Two database terms show up throughout these contracts: - TDS (Tabular Data Stream): SQL Server's binary wire protocol over TCP port
1433. - LSN (Log Sequence Number): SQL Server's monotonically increasing byte offset in its transaction log; comparing twocommit_lsnvalues tells us the exact order in which two transactions committed.1. Internal write service (owned by us) Runtime flags read at the start of every transaction: DB_BACKEND = sqlserver | postgres WRITE_MODE = normal | draining (draining holds new write txns up to 60 s, then returns 503) Normalized database exception mapping across both drivers: SQL Server 2627 / 2601, PostgreSQL 23505 -> DuplicateKeyError SQL Server 1205, PostgreSQL 40P01 -> DeadlockRetryableError 2. Third-party analytics service (unmodifiable) Connects via TDS to bi-sql.internal:1433 -> HAProxy TCP load balancer Phases 0-2 backend: SQL Server (:1433) Phase 3+ backend: Babelfish TDS endpoint on PostgreSQL (:1433) 3. Ordered forward change stream (Kafka, 1 topic, 1 partition) Event = {op: "c"|"u"|"d", table, key, before, after, source: {commit_lsn, change_lsn, event_serial_no, ts_ms}} Separate transaction-metadata topic emits BEGIN / END records with expected event_count per commit_lsn. 4. Migration controller CLI (admin runbook tool) migrate status | migrate fence | migrate flip --target=postgres|sqlserverTarget PostgreSQL schema rules - Identifiers are lowercased (
dbo.invoices) so queries never require double quotes; compatibility views preserve mixed-case names for the analytics layer. - Every table must have a primary key (added on SQL Server before Phase 1 if missing) so upserts, deletes, and chunk checksums can address every row uniquely. -IDENTITYcolumns becomeGENERATED BY DEFAULT AS IDENTITYso the replication applier can insert SQL Server's explicit IDs during sync while PostgreSQL can generate new IDs after cutover.Migration state tables on PostgreSQL (with
cutover_markerandheartbeatalso created on SQL Server):CREATE SCHEMA migration; CREATE TABLE migration.table_state ( source_table text PRIMARY KEY, -- e.g. 'dbo.Invoices' target_table text NOT NULL, -- e.g. 'dbo.invoices' key_columns text[] NOT NULL, phase text NOT NULL, -- pending | copying | catching_up | synced | verified copy_finished_lsn bytea, -- source LSN when bulk copy finished rows_copied bigint ); CREATE TABLE migration.apply_checkpoint ( stream text PRIMARY KEY, -- 'forward' before cutover, 'reverse' after cutover last_commit_lsn bytea NOT NULL, -- highest source transaction completely applied source_commit_time timestamptz NOT NULL, applied_at timestamptz NOT NULL ); CREATE TABLE migration.mismatch ( id bigserial PRIMARY KEY, table_name text NOT NULL, row_key jsonb NOT NULL, source_row jsonb, target_row jsonb, found_by text NOT NULL, -- sample | checksum | invariant | shadow_query status text NOT NULL, -- suspected | confirmed | repaired | explained first_seen timestamptz NOT NULL DEFAULT now() ); CREATE TABLE migration.cutover_marker (id bigint PRIMARY KEY, written_at timestamptz NOT NULL); CREATE TABLE migration.heartbeat (id int PRIMARY KEY, beat_at timestamptz NOT NULL);Updating
migration.apply_checkpointinside the exact same PostgreSQL transaction as the replicated row writes guarantees effectively-once state: if the applier crashes mid-flight, both the row writes and the checkpoint roll back together. Meanwhile, updatingmigration.heartbeaton SQL Server once per second ensures the change stream advances even during quiet nights.High-level architecture and phased rollout
Why use Change Data Capture (CDC) (streaming committed changes directly from the database's transaction log) instead of dual writes (having application code write to both SQL Server and PostgreSQL)? With dual writes, there is no atomic commit across two engines: if SQL Server commits and the PostgreSQL network call times out, the databases silently diverge; worse, two concurrent threads updating the same row can commit in order
A -> Bon SQL Server andB -> Aon PostgreSQL, leaving permanently mismatched values. CDC reads SQL Server's single authoritative commit order with zero changes to business logic.Phases 1-3: SQL Server is the sole writer; PostgreSQL syncs via forward CDC [ Internal Write Service ] [ 3rd-Party Analytics (Read-Only) ] | TDS | TDS (bi-sql.internal:1433) v v [ MS SQL Server (2 TB) ] <--- Phases 0-2 --- [ HAProxy (TCP) ] --- Phase 3+ ---+ | transaction log | v | [ SQL Server CDC Capture ] -> [ _CT Change Tables ] | | Debezium SQL Server Connector | v v [ Kafka: 1-partition ordered change topic ] [ Babelfish TDS Endpoint (:1433) ] | | v v [ Transactional Applier (type transform + upsert) ] ------> [ PostgreSQL 17 Primary ] | ^ sync replication v | [ Continuous Verifier (samples, chunk hashes, shadow SQL) ] -> [ PG Sync Standby ] Phases 4-5: PostgreSQL is the sole writer; reverse CDC keeps SQL Server rollback-ready [ Internal Write Service ] -> [ PostgreSQL 17 Primary ] -> WAL (pgoutput failover slot) -> [ Debezium PG Connector ] -> [ Kafka ] -> [ Reverse Applier ] -> [ MS SQL Server (warm standby) ]We roll out in seven low-risk phases, deliberately cutting over the read-only analytics client first (reversible in seconds via HAProxy) so PostgreSQL proves itself under real production read queries before taking a single authoritative write:
Phase 0 (Weeks 1-4) Port schema & stored procs; ship dual data-access layer; place HAProxy in front of SQL Server Phase 1 (Week 5) Enable SQL Server CDC, record start_lsn, run snapshot bulk copy, catch up, build indexes Phase 2 (Weeks 5-7) Run continuous row sampling, nightly chunk checksums, and shadow analytics query replay Phase 3 (Week 7) Flip HAProxy backend to PostgreSQL's TDS endpoint for the analytics service Phase 4 (Week 8) Write cutover (~20-60 s drain): fence SQL Server, drain forward CDC, start reverse CDC, flip writer Phase 5 (Weeks 8-12) Rollback window: reverse CDC keeps SQL Server < 2 s behind PostgreSQL Phase 6 (Week 12) Retire reverse CDC and decommission SQL ServerDeep dive 1: Zero-gap initial load and transactional CDC apply
Preparing SQL Server without breaking production Before enabling CDC (
sys.sp_cdc_enable_dbandsys.sp_cdc_enable_table), we change one critical server setting: SQL Server'smax text repl size (B)defaults to65536bytes (64 KB), which causes productionINSERT/UPDATEstatements writing largervarchar(max),nvarchar(max), orxmlpayloads into a CDC-enabled table to fail outright! Settingmax text repl size (B)to-1(unlimited) prevents that trap. We also tune the CDC log-scan interval from 5 seconds down to 1 second so steady-state lag stays under 2 seconds.How to bulk-copy 2 TB while writes continue—with zero lost or corrupted rows If you bulk-copy first and turn on CDC afterward, you lose every write that happened in the gap between the two steps. Instead, we overlap them and rely on idempotent apply (applying an operation multiple times yields the exact same row state as applying it once):
LSN timeline on SQL Server: start_lsn = 100 chunk copies run under SNAPSHOT isolation copy_finished_lsn = 180 |--------------------------------------------------------------------------|-----------------> 1. Start Debezium from start_lsn=100 (events buffer safely in Kafka; applier is paused). 2. Bulk-copy tables into PostgreSQL (ONLY Primary Key indexes exist; NO unique secondary indexes yet!). 3. Start applier from LSN 100 -> replays [100 .. 180] idempotently via PK upserts & deletes. 4. Once last_commit_lsn >= 180, build secondary/unique indexes and VALIDATE foreign keys!Two subtle details here prevent classic production disasters: - Read with
SNAPSHOTisolation, neverWITH (NOLOCK):NOLOCKperforms dirty reads that can copy a row from an uncommitted transaction that subsequently rolls back. Because rolled-back transactions never appear in CDC, PostgreSQL would keep a phantom row forever!SNAPSHOTisolation reads only committed versions using SQL Server'stempdbversion store without blocking writers. - Build unique secondary indexes after replaying pastcopy_finished_lsn: SupposeUsershasUNIQUE (email). At LSN 110 Alice (id=1) freesann@x.com, and at LSN 120 Bob (id=2) claimsann@x.com. The LSN 180 snapshot already contains Bob (id=2, ann@x.com). IfUNIQUE (email)already existed when the applier replayed an LSN 105 update for Alice (id=1, ann@x.com), PostgreSQL would crash with a duplicate-email error before reaching LSN 110! Holding off secondary indexes untillast_commit_lsn >= 180avoids every transient pre-snapshot collision and makes bulk replay much faster.Transactional applier logic The applier groups CDC events by
commit_lsn(verifying completeness against Debezium's transactionENDevent count) and commits whole source transactions in exact commit order:def apply_transaction(pg, txn): # session_replication_role = 'replica' disables user triggers and FK checks during apply # so triggers that already fired on SQL Server do not fire a second time on PostgreSQL. with pg.transaction(replication_role="replica"): for event in txn.events: if event.op == "d": pg.delete(event.table, event.key) else: # Both inserts ('c') and updates ('u') carry the full after-row image, # so INSERT ... ON CONFLICT (pk) DO UPDATE makes replay idempotent. mapped_row = transform_row(event.table, event.after) pg.upsert(event.table, mapped_row) # Commit the LSN checkpoint inside the SAME PostgreSQL transaction as the row writes. pg.save_checkpoint("forward", txn.commit_lsn, txn.commit_time) def run_applier(stream, pg): last_applied_lsn = pg.load_checkpoint("forward") for txn in stream.complete_transactions(): # Skip transactions re-delivered by Kafka after an applier restart. if txn.commit_lsn <= last_applied_lsn: continue # Any unexpected type/constraint error raises and halts the applier immediately; # never skip a failed row, or the two databases silently diverge. apply_transaction(pg, txn) last_applied_lsn = txn.commit_lsn stream.commit_kafka_offset(txn)For throughput, small consecutive source transactions can be committed together in one PostgreSQL transaction batch (up to ~1,000 rows or 50 ms), always cutting batches purely on transaction boundaries so no half-transaction is ever visible. Conversely, a giant batch transaction (e.g., 2M rows) streams directly into a single open PostgreSQL transaction so applier memory stays flat.
Deep dive 2: Data type mapping, collations, and stored procedures
Data type and precision mapping SQL Server and PostgreSQL differ in subtle ways around booleans, string encodings, and timestamp precision:
SQL Server Type PostgreSQL Type Migration Rule / Pitfall ---------------------------- --------------------------------- -------------------------------------------------- bit boolean Rewrite T-SQL "= 1" / "= 0" predicates in procs tinyint (0..255) smallint + CHECK (val BETWEEN ..) PostgreSQL has no 1-byte integer type smallint / int / bigint smallint / integer / bigint Direct 1:1 match decimal(p,s) / numeric(p,s) numeric(p,s) Exact fixed-point match money / smallmoney numeric(19,4) / numeric(10,4) Avoid PG's locale-dependent money type char(n) / varchar(n) char(n) / varchar(n) (UTF-8) Convert Windows-1252 code pages to UTF-8 nchar(n) / nvarchar(n) varchar(n) (UTF-8) Convert UTF-16 to UTF-8 varchar(max) / nvarchar(max) text Unbounded UTF-8 text varbinary / image bytea Raw binary bytes uniqueidentifier uuid SQL Server sorts mixed-endian GUID bytes differently! datetime timestamp(3) 3.33 ms ticks (.000/.003/.007); round to ms identically datetime2(n) timestamp(min(n, 6)) datetime2(7) is 100 ns; PG caps at 1 us (6 digits) datetimeoffset(n) timestamptz + orig_offset_min PG timestamptz normalizes to UTC and drops the offset rowversion / timestamp bigint + BEFORE UPDATE trigger Used for optimistic concurrency; increment in PG IDENTITY(1,1) GENERATED BY DEFAULT AS IDENTITY Reseed sequence at cutover Computed column GENERATED ALWAYS AS (...) STORED Omit from applier column listSemantic traps beyond column types - Case-sensitivity and collations: A collation is the rule set a database uses to compare and sort strings. SQL Server defaults (
SQL_Latin1_General_CP1_CI_AS) are case-insensitive ('Ann@x.com' = 'ann@x.com') and ignore trailing spaces ('abc' = 'abc '), whereas PostgreSQL defaults are strictly case-sensitive! Without action, unique indexes on emails or usernames allow'Bob'alongside'bob'right after cutover, andWHEREfilters miss mixed-case rows. We audit string columns used in filters, joins, and unique constraints and apply PostgreSQLcitextor case-insensitive ICU collations (pluslower(col)unique indexes). - Concurrency locks: T-SQL's"if not exists, insert"pattern usingWITH (UPDLOCK, HOLDLOCK)acquires a key-range gap lock on a missing key; PostgreSQL'sSELECT ... FOR UPDATElocks zero rows when the key does not exist yet! We translate upsert patterns into nativeINSERT ... ON CONFLICT DO UPDATE(or transaction-scopedpg_advisory_xact_lock(hashtext(key))).Stored procedures and scheduled jobs 1. Prune dead code: Query
sys.dm_exec_procedure_statsand Query Store over 30 days to drop uncalled legacy procedures before porting. 2. Convert and review: Use an automated transpiler (such as AWS SCT or Ora2Pg/pgLoader equivalents) for boilerplate, then manually review T-SQL idioms (TOP n->LIMIT n,ISNULL->COALESCE,SCOPE_IDENTITY()->INSERT ... RETURNING,GETDATE()->clock_timestamp()when intra-transaction wall time is needed rather than transaction-startnow(), andDATEDIFF(day, a, b)->b::date - a::date). 3. Differential replay: Capture one week of production procedure calls via SQL Server Extended Events, replay them against staging snapshots of both databases at identical LSNs, and require zero result-set or row-diff mismatches. 4. Scheduled jobs: Port SQL Server Agent jobs topg_cronor the application scheduler, keeping write jobs disabled on PostgreSQL until cutover so CDC does not apply their side effects twice.Deep dive 3: Live data verification and switching the unmodifiable reader
How to verify two live databases without false alarms from replication lag If you read
Invoices(id=101)on SQL Server and PostgreSQL at the exact same instant, an update that committed 50 ms ago on SQL Server may still be in flight in Kafka. To separate harmless replication lag from real data corruption, our verifier coordinates with the source clock and the 1-second heartbeat table:def row_matches_live(table, key, sqlserver, postgres, checkpoint_tracker, retries=3): for _ in range(retries): src_row = sqlserver.read_row(table, key) src_read_time = sqlserver.current_timestamp() # Wait until the applier has committed every SQL Server transaction up through src_read_time. checkpoint_tracker.wait_until_applied(src_read_time) tgt_row = postgres.read_row(table, key) # canonical() is written INDEPENDENTLY from the applier's transform_row() # so a bug in transform_row() cannot mask itself during verification! if canonical(table, src_row) == canonical(table, tgt_row): return True # If they differed, the row might have been updated AGAIN on SQL Server after src_read_time; # retrying confirms whether the mismatch persists once settled. return FalseWe layer three verification passes so nothing slips through: 1. Continuous random sampling (~100 rows/s = 8.6M rows/day): Catches systematic mapping bugs within seconds. By the statistical "rule of three,"
Nclean samples bound the defect rate to roughly3 / Nat 95% confidence—great as an instant alarm, but not mathematical proof over billions of rows. 2. Nightly and pre-cutover primary-key chunk checksums: Walk each table in 10,000-row primary-key slices, serialize canonical rows in the verifier (never relying on engine-specificCHECKSUM()functions, which use incompatible binary layouts and weak XOR hashes), and compare SHA-256 digests. Any mismatched chunk is bisected down to individual keys and passed throughrow_matches_liveto filter out in-flight writes. 3. Daily shadow analytics replay: Capture two weeks of real T-SQL queries from the third-party analytics login and replay them against both SQL Server and PostgreSQL's compatibility endpoint, checking both row parity and p99 query latency.Switching the unmodifiable third-party analytics client Because the vendor client hardcodes a SQL Server driver and T-SQL queries, we combine HAProxy in TCP pass-through mode with Babelfish for PostgreSQL (an open-source / Aurora PostgreSQL extension that listens on port
1433, speaks native SQL Server TDS wire protocol, and executes T-SQL against PostgreSQL tables): 1. Phase 0 (weeks early): Pointbi-sql.internalto an HAProxy TCP pair forwarding to SQL Server, and build the PostgreSQL target with Babelfish enabled. Run Babelfish Compass and our captured shadow queries in Phase 0; where a vendor query hits unsupported T-SQL syntax, adjust our compatibility views so their query succeeds unchanged. 2. Phase 3 (read cutover): Add PostgreSQL's port1433as the active HAProxy backend, mark SQL Serverdrain, terminate idlesleepinganalytics sessions on SQL Server so the client's connection pool reconnects transparently through HAProxy to PostgreSQL, and keep SQL Server one HAProxy toggle away for instant read rollback.Deep dive 4: Write cutover and zero-data-loss rollback
Go / no-go gates before starting cutover: p99 replication lag
< 2 sfor 7 consecutive business days (< 1 sat T-0), zero confirmed row mismatches, a 100% clean full chunk checksum within 24 hours, all foreign keysVALIDATED, shadow queries matching within 20% p99 latency, and two timed end-to-end rehearsals (including rollback) in staging.Step-by-step write cutover runbook (~20–60 s write hold, zero read downtime)
Step Action Why this exact order matters ---- --------------------------------------------------------------------- ---------------------------------------------------- 1 Set WRITE_MODE=draining on internal write service Holds new write txns in memory (<= 60 s); reads run 2 Wait until open write transactions on SQL Server == 0 Drains in-flight work cleanly 3 Revoke INSERT/UPDATE/DELETE/EXEC from app login on SQL Server; Hard fence against stray writers or forgotten jobs disable app SQL Agent write jobs (keep CDC capture job running!) 4 Admin inserts marker row into migration.cutover_marker on SQL Server; Single-partition commit order proves EVERY prior wait until applier commits that marker row on PostgreSQL SQL Server write is now durable in PostgreSQL 5 Verify emitted == applied counts + spot-check last-hour modified rows Final sanity gate while rollback is still trivial 6 Stop forward Debezium SQL Server connector Prevents reverse-replicated writes from looping back! 7 Reseed every PG identity sequence to GREATEST(MAX(id), ident_current) Prevents duplicate PKs (handles deleted tail IDs too) 8 Create PG 17 logical slot (failover=true) + start reverse CDC pipeline Captures 100% of PG writes from the very first txn 9 Flip write service: DB_BACKEND=postgres, WRITE_MODE=normal Queued writes flush into PostgreSQL; cutover complete! 10 Run sys.sp_cdc_disable_db on SQL Server Frees SQL Server to truncate its transaction logNotice two subtle traps solved in Steps 7 and 8: - Reseeding sequences safely (Step 7): Setting a sequence only to
COALESCE(MAX(id), 1)fails on empty tables (unlessis_calledis set tofalse) and re-issues an already-used ID if the highest row (sayid = 500) was deleted right before cutover! TakingGREATEST(COALESCE(MAX(id), 0), sqlserver_ident_current)guarantees monotonic IDs. - Surviving a PostgreSQL primary crash after cutover (Step 8): Reverse CDC reads PostgreSQL's Write-Ahead Log (WAL) (PostgreSQL's append-only transaction log) through a logical replication slot (a persistent server-side cursor that keeps WAL segments on disk until Debezium reads them). Prior to PostgreSQL 17, logical slots vanished during a primary-to-standby failover, creating a permanent data gap in reverse CDC! Using PostgreSQL 17'sfailover => trueslot withsynchronized_standby_slotsensures the synchronous standby preserves the exact reverse-CDC cursor across failovers.Post-cutover rollback runbook (any time during the 4-week Phase 5 window) 1. Set
WRITE_MODE = drainingon the write service and wait for zero open PostgreSQL transactions. 2. Revoke write privileges from the app role on PostgreSQL (hard fence). 3. Insert a reverse marker row intomigration.cutover_markeron PostgreSQL and wait until the reverse applier commits it on SQL Server (confirming zero post-cutover data loss). 4. Verify SQL Server identity seeds viaDBCC CHECKIDENT ('dbo.Invoices', NORESEED)(SET IDENTITY_INSERT ONupdates SQL Server's high-water mark on explicit inserts, and we reseed any table that lags). 5. Re-enable SQL Server triggers, scheduled jobs, and app write permissions; flipDB_BACKEND = sqlserver,WRITE_MODE = normal(and flip HAProxy back to SQL Server if PostgreSQL reads are unhealthy). 6. Stop the reverse connector and drop the PostgreSQL logical replication slot so retained WAL cannot fill PostgreSQL's disk while engineers diagnose the issue.Bottlenecks, failure modes, and trade-off summary
Key bottlenecks and operational guardrails - Production SQL Server log growth (kill switch): While CDC is active, SQL Server refuses to truncate transaction log segments that the CDC capture job has not scanned yet (
log_reuse_wait_desc = 'REPLICATION'). If capture stalls and SQL Server transaction log usage crosses 70%, automated remediation callssys.sp_cdc_disable_dbimmediately: protecting production availability always outranks migration progress (we simply re-run Phase 1 once fixed). Similarly, on PostgreSQL post-cutover,max_slot_wal_keep_sizecaps retained WAL if reverse CDC stalls. - Single-applier ceiling: One ordered applier caps throughput at ~15,000–25,000 rows/s (5×+ our 3,000 rows/s peak). If traffic grew 10×, we could shard appliers by an independent key such astenant_idonly after verifying that zero transactions or foreign keys span tenants. - PostgreSQL update bloat: PostgreSQL's MVCC (Multi-Version Concurrency Control) writes a new row tuple on everyUPDATE, leaving dead tuples behind. During heavy CDC upserts, we setfillfactor = 80and aggressive per-tableautovacuumthresholds on hot tables so updates stay on the same 8 KB page.Failure handling matrix
Failure Scenario System Response ------------------------------------------ ----------------------------------------------------------------------- Debezium or Applier process crashes Restarts and resumes from migration.apply_checkpoint; <= LSN skipped Unmappable / corrupt value hits Applier Applier halts immediately & pages on-call; Kafka buffers up to 7 days Connector down > 12 hours Pages on-call well before SQL Server's 3-day _CT retention expires PostgreSQL primary node crashes Promotes sync standby (< 15 s); PG 17 failover slot preserves reverse CDC Cutover aborts before Step 9 Drop unused PG slot, restart forward Debezium, restore SQL Server permsSummary of architectural trade-offs - Log-based CDC over dual writes: Adds Kafka/Debezium infrastructure and mild source I/O overhead, in exchange for exact transactional ordering, zero partial-commit bugs, and untouched business logic. - Single-partition ordered apply over table-parallel apply: Caps maximum apply throughput (~5× peak), in exchange for strict cross-table transactional consistency at every instant. - Brief queued write hold (~20–60 s) over active-active multi-master: Adds one brief latency spike at cutover, in exchange for eliminating split-brain write conflicts completely. - Babelfish TDS layer for third-party analytics, native PostgreSQL for our write service: Respects the vendor's zero-code-change constraint while freeing our own codebase from permanent compatibility-layer limitations. - 4-week reverse CDC pipeline: Requires operating a reverse stream after launch, in exchange for a push-button rollback that loses zero post-cutover transactions.
Intuition & how it works
Think of migrating a continuously used database like switching a busy restaurant kitchen from a paper order ledger to a computer system in the middle of the dinner rush without dropping a single ticket. You cannot freeze the kitchen for two hours to retype 2 TB of history. Instead, you first clip a carbon-copy tape onto the paper ledger (Change Data Capture, or CDC — a background process that reads committed row changes directly from a database's transaction log and streams them as ordered events), photocopy the existing ledger from a frozen camera snapshot while new orders pile up safely on the carbon-copy tape, and fast-forward the tape into PostgreSQL until it catches up to within a second of live traffic. For the third-party analytics client that only knows how to speak to SQL Server, you place a protocol translator (Babelfish, a PostgreSQL extension that speaks SQL Server's TDS wire protocol and T-SQL dialect on port 1433) behind a TCP proxy (HAProxy) so the client never realizes the engine underneath changed. Finally, during a ~30-second pause where new writes wait in a queue, you send one marker row down the pipe to drain the last drop of data, flip writes to PostgreSQL, and immediately start a reverse CDC tape back to SQL Server so you can switch back with zero data loss if anything goes wrong over the next month.
Why do simpler approaches fail? Taking SQL Server offline for a traditional dump-and-restore violates zero-downtime availability for hours. Having the application write to both SQL Server and PostgreSQL at the same time (dual writes) fails strict consistency: one database can commit while the second crashes, or two concurrent updates to the same row can land in opposite orders (A -> B vs. B -> A), leaving the two engines permanently out of sync. And changing connection strings alone fails for the third-party analytics tool because its binary driver and queries are hardcoded for SQL Server.
Let's trace a tiny concrete example with an Invoices table (id=101: $420 initially) and analytics endpoint bi-sql.internal:1433 across the initial sync, cutover, and rollback stream:
Step Event on Active Writer Forward / Reverse Stream & Target State
---- ------------------------------ ------------------------------------------------------------------------------
1 Enable CDC at start_lsn = 100 Kafka buffers all changes from LSN 100 onward; applier paused.
2 LSN 105: UPDATE id=101 -> $480 Bulk COPY snapshots SQL Server at LSN 110 -> PG gets {101: $480, 102: $150}.
LSN 108: INSERT id=102 -> $150 Applier replays LSN 105 & 108 as idempotent upserts -> PG still {101: $480, 102: $150}!
3 Cutover: hold writes, fence DB Admin writes cutover_marker at LSN 120; once PG applies LSN 120, PG == SQL Server.
4 Flip writer to PostgreSQL Stop forward CDC; reseed PG sequence to 102; start reverse CDC slot on PG.
5 PG commits INSERT id=103 -> $310 Reverse CDC writes {103: $310} into SQL Server -> instant zero-loss rollback ready!
Key trade-offs
- Log-based CDC vs. application dual writes vs. periodic batch exports. CDC (via SQL Server CDC + Debezium, an open-source log-streaming connector, over Kafka, a durable distributed event log) preserves SQL Server's exact transaction commit order without touching business logic, at the cost of operating a streaming pipeline and adding ~160 GB of change-table storage on SQL Server. Dual writes cannot commit atomically across two engines and diverge under concurrent updates, while batch exports cannot hold lag to a couple of seconds.
- Single-partition ordered applier vs. table-parallel appliers. Routing all tables through one Kafka partition and one transactional applier caps throughput at ~15,000–25,000 rows/s (still 5× our 3,000 rows/s peak), but guarantees that multi-table transactions commit atomically in order so analytics readers never see orphan child rows or half-transferred balances.
- Brief queued write hold (~20–60 s) vs. zero-pause multi-master writes. Strict consistency requires a single authoritative writer at every instant. Holding write requests in memory for ~30 seconds during cutover causes one brief latency bump with zero errors, whereas running both databases as active writers simultaneously invites split-brain primary-key and update conflicts.
- Babelfish TDS translation for third-party reads vs. native PostgreSQL for internal writes. Babelfish lets the unmodifiable analytics client keep sending T-SQL over port
1433, though it ties the target cluster to a Babelfish-capable PostgreSQL build (such as Aurora PostgreSQL or open-source Babelfish). Porting our own internal write service's data-access layer and stored procedures to native PostgreSQL costs upfront engineering work, but prevents our core product from being locked behind T-SQL translation limits forever. - Cutting over reads first (Phase 3), then writes (Phase 4). Running two cutovers instead of one adds a milestone, but moving the read-only analytics proxy first is reversible in seconds and battle-tests PostgreSQL under real production queries before a single authoritative write lands on it.
- Continuous random sampling + nightly chunk checksums. Continuous random sampling (~100 rows/s) catches mapping bugs within seconds at negligible load, but statistically
Nclean samples only bound the error rate to roughly3 / N. Full primary-key chunk checksums take ~2 hours of disk reads off-peak, providing the exact mathematical proof required before cutover. - 4-week reverse CDC pipeline vs. backup-only rollback. Operating reverse replication from PostgreSQL's Write-Ahead Log (WAL) (PostgreSQL's transaction log) back to SQL Server adds post-cutover operational overhead, in exchange for being able to roll back days later without losing a single post-cutover transaction.
Common mistakes
- Using
WITH (NOLOCK)for the initial bulk copy:NOLOCKreads uncommitted rows from transactions that may later roll back; because rolled-back writes never emit a CDC undo event, phantom rows stay in PostgreSQL forever. Always bulk-copy underSNAPSHOTisolation. - Starting CDC after the bulk copy finishes: Every row modified between the start of the bulk copy and enabling CDC is permanently missed. Always start CDC capture first (
start_lsn), then copy, then replay idempotently over the overlap. - Building unique secondary indexes before initial CDC catch-up finishes: If a unique email or order code moved from row A to row B during the bulk-copy window, replaying pre-snapshot events over the post-snapshot table hits transient unique-constraint errors unless secondary indexes are built after
last_commit_lsnpassescopy_finished_lsn. - Leaving SQL Server's
max text repl sizeat its 64 KB default: Enabling CDC on tables withvarchar(max),nvarchar(max), orxmlcolumns causes production writes exceeding 65,536 bytes to fail untilmax text repl size (B)is set to-1. - Letting target triggers and scheduled jobs run during replication: If PostgreSQL triggers or
pg_cronwrite jobs fire while PostgreSQL is still a replica, actions already recorded in SQL Server's CDC stream happen twice. Apply withsession_replication_role = 'replica'and enable jobs only on the active writer. - Reseeding PostgreSQL sequences only to
MAX(id)or forgetting to reseed at all: Forgettingsetval()makes the first post-cutoverINSERTcrash with a duplicate key, and usingMAX(id)alone re-issues a previously deleted tail ID (useGREATEST(COALESCE(MAX(id), 0), sqlserver_ident_current)and handle empty tables cleanly). - Sharing transformation code between the applier and the verifier: If
canonical()reusestransform_row(), any rounding, timezone, or truncation bug transforms both sides identically and passes every check undetected. - Forgetting to stop forward CDC before starting reverse CDC (or missing PG 17 failover slots): Leaving both streams running creates an infinite ping-pong replication loop, and using pre-PG-17 non-failover logical slots breaks reverse CDC silently if PostgreSQL fails over to its standby.
- Missing a source transaction-log kill switch: A stalled CDC capture job prevents SQL Server from truncating its transaction log (
REPLICATIONlog-reuse wait), which can fill production's disk unless automation disables CDC at a safety threshold (e.g., 70% log usage).
Follow-up questions
- What if product engineering needs to ship a schema change using a PostgreSQL-specific feature that legacy SQL Server cannot represent natively while migration is still underway? While SQL Server is still the active writer (before Phase 4), every write lands on SQL Server first, so truly SQL-Server-incompatible structures must either wait until after write cutover or be stored in a compatible representation on SQL Server (for example,
nvarchar(max)with anISJSON()check constraint mapped by the applier into PostgreSQLjsonb). When adding compatible columns before cutover, SQL Server allows up to two concurrent CDC capture instances per table, so you create a second capture instance including the new column and transition Debezium seamlessly without dropping events. After write cutover (during the 4-week rollback window), use an expand-and-contract pattern where the reverse applier translates the new PostgreSQL feature into a fallback column on SQL Server—or if the feature fundamentally cannot be represented in SQL Server at all, treat that migration as an explicit business sign-off to close the rollback window early. - Which concrete operational and data-integrity signals must pass before you give the green light for final cutover? Require both pipeline-health and data-correctness gates to stay green simultaneously for 7 consecutive business days: end-to-end CDC replication lag
p99 < 2 s(and< 1 sright before cutover), zero applier stops or unhandled rows, exactemitted == appliedtransaction counts, SQL Server transaction-log usage steady well below the 70% kill-switch threshold, zero confirmed mismatches from continuous random sampling, a 100% clean full primary-key chunk checksum completed within the prior 24 hours, and 100% result parity on replayed shadow analytics queries withp99latency within 20% of SQL Server. Measuring lag alone is never sufficient because a broken pipeline can replicate corrupted data very quickly. - Suppose the third-party analytics tool keeps persistent pooled TCP connections open indefinitely—how do you redirect its traffic to PostgreSQL without restarting the vendor process? Weeks before cutover, point
bi-sql.internalto an HAProxy TCP load balancer forwarding to SQL Server so DNS caching ceases to matter once connections flow through the proxy. At switchover time, add PostgreSQL's Babelfish port1433to HAProxy and set the SQL Server backend todrainso every new TCP connection routes to PostgreSQL, then run a loop on SQL Server usingKILL <spid>to terminate the analytics login's idle (sleeping, zero open transactions) sessions—followed by HAProxyshutdown sessions serverafter a brief query timeout for stragglers. Because standard database connection pools automatically discard closed sockets and open fresh connections on the next query (or retry once), traffic moves onto PostgreSQL within seconds without restarting the vendor's process.
Follow-up questions
- What if product engineering needs to ship a schema change using a PostgreSQL-specific feature that legacy SQL Server cannot represent natively while migration is still underway?
- Which concrete operational and data-integrity signals must pass before you give the green light for final cutover?
- Suppose the third-party analytics tool keeps persistent pooled TCP connections open indefinitely—how do you redirect its traffic to PostgreSQL without restarting the vendor process?
Similar questions
- Workflow Dependency and Sequence Validator
- Critical-Path Completion Time Across a Production DAG
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests