Video in progress

How do you migrate a big monolithic database to a sharded schema without downtime?

Step by step: first prepare the code so every query carries the shard key, then dual write to the new schema and backfill the old data, then compare with shadow reads, then move reads, and writes last. Every step must be reversible.

📖 Answer

A single "big night" migration is almost always postponed or ends badly. I build it as a plan that runs for several months, with each step reversible on its own.

  1. Choose the shard key and prepare the code. Usually tenant_id or user_id. I list the cross-shard JOINs and global queries, because they're the biggest chunk of work. Every query must know the shard key; the ones that don't get rewritten or moved to a separate search index.
  2. A routing layer. The application connects through a single ShardRouter; at first it sends everything to the old database. This changes nothing on prod, but the later steps can be controlled with a flag.
  3. Dual write. New writes go to both places. The old database is still primary; an error writing to the new one doesn't affect the user, it only goes to the log and a retry queue. The alternative is a stream from the old database to the new one via CDC, which adds less code to the application.
  4. Backfill. Old data is moved in batches, by version or updated_at, so that you don't overwrite a new value written by dual write with an old one.
  5. Shadow reads and comparison. Reads come from the old place, but in the background you also read from the new one and record the differences in a metric. I don't move to the next step until the difference is close to zero.
  6. Move reads: first 1% of tenants, then 10%, then everyone.
  7. Move writes: the new database becomes primary, and a reverse dual write to the old one stays for a while, in case you need to roll back.
  8. After a few quiet weeks, remove the old path.

In practice the technical side isn't what eats the most time; reports and admin queries do. They work "across all tenants", and in a sharded world they need a separate analytical store.