Live Move of a 2TB SQL Server Database to PostgreSQL
System DesignModel answerLast updated
Plan a no-downtime move of a busy 2TB SQL Server database to PostgreSQL, covering sync, type mapping, verification, cutover and rollback, with a read-only vendor client you cannot change.
Scenario
Your team runs a core production database on Microsoft SQL Server and wants to move it to PostgreSQL. The database holds roughly 2 TB and takes heavy write traffic during business hours.
Two clients depend on it:
- An internal service that writes transactions continuously. You own its code, but you want to avoid large changes to its business logic.
- A third-party analytics tool that only reads. Its vendor cannot realistically change its code or make it query more than one database. You may only influence where it connects.
Goals
- No user-visible downtime during the move.
- Strict consistency: no lost, duplicated or reordered transactions.
- A tested way to go back if PostgreSQL misbehaves after the switch.
- Both databases stay in sync for the duration of the migration.
- The vendor's tool ends up reading from PostgreSQL without any vendor-side code change.
What to deliver
- A high-level architecture and migration path. Compare options such as change data capture, application-level dual writes and logical replication, and justify your choice.
- A strategy for mapping data types and handling logic differences between the engines, including stored procedures, triggers, identity columns and collation.
- A way to continuously verify that the two databases hold the same data, and to keep replication lag small.
- A step-by-step cutover plan with preconditions, and a rollback plan for failures after the cutover.
State any assumptions you make, such as peak transaction rate and what "zero downtime" means in practice.
Hints
Hint 1
Size the problem first: at a realistic copy speed, how long does moving 2 TB take, and what happens to writes in the meantime? That tells you a one-off copy is not enough.
Hint 2
Dual writes from the application cannot be atomic across two engines. Consider reading the source's transaction log instead, and make the applier on the target idempotent.
Hint 3
The vendor can't change code, but it can change a connection string or DNS name. Think about a stable endpoint you control, and about which protocol the vendor speaks.
Hint 4
A rollback is only real if data keeps flowing in the opposite direction after cutover. Plan reverse replication and rehearse it.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
- Data and copy time: 2 TB at about 100 MB/s effective is roughly 6 hours. Writes continue during that time, so the plan is snapshot plus continuous change capture, not a single copy.
- Write rate: assume 1-5k TPS at peak. Size the pipeline for about 3x headroom.
- "Zero downtime": agree it means no user-visible outage. A write pause of a few seconds at cutover is acceptable and far safer than running dual writes for weeks.
- Vendor reader: it speaks the SQL Server wire protocol (TDS) with T-SQL. Its connection target is configuration; its code is fixed.
- Consistency goal: at cutover, PostgreSQL contains exactly the transactions committed in SQL Server up to the cutover log position.
2. Architecture: CDC, not dual writes
Why not dual writes? There is no atomic commit across two engines. A crash between the writes leaves them divergent, and concurrent ordering can differ per database. They also require invasive changes to the writer.
Why CDC? Reading the transaction log preserves SQL Server's commit order, misses nothing, and requires no change to business logic.
Pipeline:
- Enable SQL Server CDC on all tables.
- A connector (e.g. Debezium) publishes one Kafka topic per table, keyed by primary key, so per-row order is preserved within a partition.
- A sink applies idempotent upserts and deletes by primary key and stores the last applied log position (LSN). Redelivery is harmless, which gives effectively-once behavior.
- Tables without a primary key get one (or a surrogate) first; otherwise you can neither upsert nor reconcile them.
Initial load:
- Record the current max LSN.
- Bulk-load a consistent snapshot in parallel by PK range (export, then
COPY), creating indexes and foreign keys after loading. - Start CDC replay from the recorded LSN. Idempotent upserts make the overlap safe.
3. Mapping and logic differences
| SQL Server | PostgreSQL | Watch out for |
|---|---|---|
DATETIME | timestamp(3) | About 3.33 ms rounding; normalize before comparing |
DATETIME2 / DATETIMEOFFSET | timestamp / timestamptz | Decide on UTC normalization |
NVARCHAR / VARCHAR(MAX) | varchar / text | UTF-16 to UTF-8 |
BIT | boolean | |
UNIQUEIDENTIFIER | uuid | Sort order differs |
MONEY | numeric(19,4) | |
IDENTITY | GENERATED ... AS IDENTITY | Reset sequences to max+1 at cutover |
VARBINARY | bytea |
- Collation: SQL Server defaults are usually case-insensitive; PostgreSQL is case-sensitive. A unique index on email may accept
A@xanda@xin PostgreSQL. Usecitextor a nondeterministic ICU collation where the app relies on it. - Stored procedures and triggers: inventory them, port those the writer uses to PL/pgSQL, and test the same cases against both engines. Disable triggers on the target during replication (
session_replication_role = replica), because their effects already arrive via CDC. - T-SQL idioms (
TOP,ISNULL,GETDATE(),@@IDENTITY,MERGE) need rewriting. - Generate DDL and sink transformations from one per-column mapping spec so they cannot drift.
4. The vendor reader
- Weeks ahead, give the vendor a stable DNS name pointing at a TCP proxy (e.g. HAProxy) in front of SQL Server. This is a config-only change for them.
- At cutover, retarget the proxy to a TDS-compatible endpoint on PostgreSQL, such as Babelfish for PostgreSQL.
- Before cutover, replay the vendor's captured query log against Babelfish and compare results.
- Fallback if Babelfish cannot handle their queries: keep a SQL Server read replica fed by reverse CDC from PostgreSQL. The vendor stays on SQL Server, while PostgreSQL becomes the system of record.
5. Verification and lag
- Lag: monitor applied LSN versus source LSN and alert on sustained lag. Scale consumers by partitioning on key.
- Row counts per table, continuously.
- Chunked hashes: split by PK range (about 10k rows), hash canonicalized values (rounded timestamps, normalized types) on both sides, and bisect on mismatch.
- Random sampling of hot tables for fast signal.
- In-flight tolerance: compare only after the sink's applied LSN passes the source position you sampled, or re-check mismatches after the lag window. Only persistent mismatches alert and enter a repair queue.
6. Cutover
Preconditions: lag under 1 s sustained, zero persistent mismatches for several days, vendor query replay passing, reverse CDC built and tested, runbook rehearsed on staging.
Steps:
- Choose a low-traffic window.
- Put the data access layer in write-pause mode (requests queue briefly or get retryable errors).
- Wait until the applied LSN equals SQL Server's max LSN.
- Run a final checksum on hot tables and reset all sequences to max+1.
- Start reverse CDC (PostgreSQL to SQL Server) from the current position.
- Flip the feature flag so the writer uses PostgreSQL, then unpause. Target a pause of seconds.
- Retarget the vendor proxy.
- Keep SQL Server running, kept current by reverse CDC, for a soak period of days to weeks.
7. Rollback
- Because reverse CDC keeps SQL Server current, rollback is the same procedure reversed: pause writes, wait for reverse lag to reach zero, flip the flag and proxy back, unpause.
- Define triggers up front: error-rate or latency thresholds, verification failures, or vendor query failures.
- After the soak period passes with clean verification, decommission reverse CDC and SQL Server.
Trade-offs and common mistakes
- Dual writes look simple but cause silent divergence; use them only with an outbox pattern, and even then CDC is simpler.
- Skipping reverse replication makes rollback a data-loss event after the first PostgreSQL writes.
- Ignoring collation, timestamp precision and identity sequences produces subtle bugs after cutover.
- Verifying during lag creates false alarms; compare against a fixed log position.
- Not validating the vendor's real queries before cutover is the most common surprise.
- Not rehearsing the cutover and rollback on staging with production-like load.