Design a pipeline to migrate data from a SQL database to a key-value store
System DesignModel answerLast updated
Move rows from a relational database into a NoSQL key-value store with a consistent one-time snapshot followed by ongoing CDC replication from the write-ahead log.
You need to build a system that copies data from a relational database (e.g., PostgreSQL or MySQL) into a NoSQL key-value store (e.g., DynamoDB, Bigtable, or Spanner used as KV). The target key is table#primary_key and the value is the row serialized as JSON.
The migration has two phases:
- One-time consistent snapshot — Read every row from every table at a single logical point in time and write it to the target store.
- Ongoing change data capture (CDC) — Tail the source database's write-ahead log (WAL) or binlog to stream inserts, updates, and deletes into the target so it stays in sync.
You should address the following concerns in your design:
- Snapshot consistency: How do you ensure the snapshot is a point-in-time image without locking the entire database for the full duration?
- Ordering between snapshot and CDC: How do you prevent a stale snapshot row from overwriting a newer CDC update, and how do you handle a late snapshot row resurrecting a key that was already deleted?
- Idempotency and exactly-once semantics: Components can crash and replay events. How do you guarantee the target converges to the correct state despite at-least-once delivery?
- Schema evolution: The source schema can change during the migration. How do you handle additive changes, type changes, and incompatible changes?
- Backfill catch-up and cutover: How do you know when the target has caught up to the source, and how do you decide it's safe to switch reads to the new store?
- Failure recovery: What happens when a worker dies mid-chunk, the queue loses data, or the source WAL is truncated?
Include in your design: a queueing layer with partitioning, a control plane for coordination and checkpointing, monitoring metrics, and a discussion of trade-offs for key decisions.
Hints
Hint 1
Use a replication slot or equivalent to establish a consistent LSN before the snapshot starts, so the snapshot and CDC stream share a common logical cut point.
Hint 2
Partition the queue by key hash so all events for the same row land on the same partition, preserving per-key ordering.
Hint 3
Version each event with its source commit position and use conditional writes at the sink to apply only if the incoming version is newer than the stored version.
Hint 4
Represent deletes as versioned tombstones rather than physical deletes, so a late snapshot row cannot resurrect a deleted key.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Requirements and Scale
Start by stating assumptions clearly. Suppose the source is PostgreSQL with roughly 10 TB across 200 tables and 5 billion rows, peaking at 20k rows/s (~20 MB/s of change volume). The target is a key-value store where each row becomes a JSON document keyed by table#pk. The correctness goal is that the target converges to exactly the source state, including deletes. The freshness goal is p99 end-to-end lag under 5 seconds once caught up. The source stays online with minimal load impact, and every component must survive crashes and resume.
Back-of-envelope: a snapshot at 200 MB/s aggregate (40 parallel readers at 5 MB/s each) takes roughly 14 hours. During that window the source generates about 1 TB of change data. Both WAL retention on the source and queue retention must cover this with margin. This is a critical number to surface because if WAL is truncated before CDC consumes it, data is lost.
Control Plane API
A control plane coordinates workers, tracks progress, and stores checkpoints:
StartMigration(source, tables[], target, options)returns a migration ID.GetStatus(migration_id)returns phase, chunks completed, CDC lag in bytes and seconds.PauseandResumefor controlled rollouts.Verify(migration_id, table, pk_range)returns mismatch details.
Data Model
Each target record has a key of the form table#pk and a value containing the row as JSON plus metadata: a version field (the source commit position as (commit_LSN, sequence_within_transaction)), a deleted boolean for tombstones, and a schema_id linking to a schema registry.
Type mapping matters: NUMERIC becomes a string to preserve precision, timestamps become ISO-8601 UTC, bytea becomes base64, and NULL is an explicit null rather than a missing field so it is distinguishable from an absent column.
The control plane also maintains a chunk state table tracking (migration_id, table, pk_lo, pk_hi, status, row_count, checksum) and a checkpoint table storing the last durably committed source LSN and consumer offsets.
Architecture
┌─ Snapshot workers (N) ──┐
Postgres ───┤ ├──► Kafka (partitioned by table#pk) ──► Sink writers ──► KV store
(WAL) └─ CDC reader (repl slot) ┘ │ │
Schema Registry DLQ / parked keys
Control plane: coordinator, chunk state, checkpoints, verifier, metrics
Step one is creating the replication slot before anything else. On Postgres, CREATE_REPLICATION_SLOT ... LOGICAL pgoutput EXPORT_SNAPSHOT returns a snapshot name and a consistent LSN, call it L0. Every change after L0 is retained and streamed by the slot. The snapshot workers all open BEGIN ISOLATION LEVEL REPEATABLE READ and adopt that shared snapshot, then read PK-range chunks in parallel. Every snapshot row is emitted with version (L0, 0). The CDC reader decodes WAL starting from L0 and emits committed transactions only, each carrying its (commit_LSN, seq).
Both snapshot and CDC events go to the same Kafka topic, partitioned by hash of table#pk (e.g., 64 partitions). This preserves per-key ordering and enables horizontal scaling. Sink consumers read from Kafka and write to the KV store with a conditional put: apply only if incoming.version > stored.version.
Snapshot Consistency
All workers share one MVCC snapshot, so the snapshot is a single point-in-time image at L0 with no table locking. The trade-off is that the exporting session must stay open for the full duration (14 hours in this example), which prevents vacuum on the source and means chunks are lost if that connection drops.
An alternative is the watermark approach used by systems like DBLog: read chunks in short transactions, write low and high watermark rows into a signal table around each chunk read (which places them in the WAL), then in the CDC stream drop any chunk rows whose keys were modified between the two watermarks. This removes long transactions and makes chunks independently restartable. A strong candidate mentions both options and picks based on source constraints.
Ordering Between Snapshot and CDC
The versioned conditional write makes merge order irrelevant. Every snapshot row has version L0, and every CDC event has a version greater than L0. So even if a CDC update is applied before the snapshot row for that key arrives, the conditional write ensures the newer version wins. CDC can therefore run concurrently with the snapshot — no buffering or "snapshot then replay" phase is needed.
Deletes must be represented as tombstones with a version, not physical deletes. Otherwise a late snapshot row resurrects a deleted key. Tombstones are garbage-collected only after the snapshot completes and a safety window passes.
Idempotency and Exactly-Once
Delivery is at-least-once: Kafka producer retries, consumer restarts, and CDC re-reads after crashes all mean events can be delivered more than once. Combined with idempotent, version-gated writes, the result is effectively exactly-once state. Replaying any event is a no-op once a newer or equal version exists. Kafka transactions alone do not solve this because they cover only Kafka-to-Kafka, not the external KV store.
Commit discipline matters: the CDC reader advances the slot's confirmed_flush_lsn only after Kafka acknowledges the events (acks=all, idempotent producer). Sink consumers commit offsets only after the KV write succeeds. Primary key updates are emitted as a delete of the old key plus an insert of the new key, both carrying the same commit version.
Schema Evolution
Use a schema registry with versioned schemas. Each record carries a schema_id. Additive changes (new nullable column) are backward compatible; old records lack the field and readers default it. Type changes or renames require an explicit migration plan: dual-write a new field, then backfill. Postgres logical decoding does not stream DDL, but pgoutput sends Relation messages with the current column list, which can drive registry updates. On an incompatible change, pause that table's stream and alert rather than silently corrupting data.
Backfill Catch-Up and Cutover
Track three numbers: chunks completed, slot lag in bytes (pg_current_wal_lsn() - confirmed_flush_lsn), and lag in seconds (current time minus commit timestamp of the last applied event). Size the sink so CDC throughput is at least 3x peak write rate so backlog drains after the snapshot. Before cutover, run the verifier to compute per-chunk checksums on the source at a known LSN and compare against the target. Cutover is safe when all chunks are verified, lag is below threshold, and the verifier passes across sample ranges.
Failure Recovery
If a worker dies mid-chunk, the chunk is retried from scratch by another worker. If the queue loses data, CDC re-reads from the last committed LSN (the slot retains WAL). If the source WAL is at risk of truncation, increase wal_keep_size and monitor slot lag closely. A dead-letter queue captures poison messages that cannot be parsed or written, and an alert fires so an operator can intervene rather than silently dropping data.