KatInterview

Design a pipeline to migrate data from a SQL database to a key-value store

System DesignModel answer
HardModel answerSystem Designchange-data-capturedata-migrationdistributed-systems

Last 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:

  1. One-time consistent snapshot — Read every row from every table at a single logical point in time and write it to the target store.
  2. 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.