Video in progress
The data is on 4 shards and now you need 8. How do you plan the redistribution without stopping the service?
You have to copy the data, catch up in the background, and then move reads and writes to the new place step by step. The easiest way is to start with many logical shards (for example, 256) and move them whole between physical servers.
📖 Answer
If shard = hash(userId) % 4, going to 8 moves half of the records. Doing that without downtime is a multi-stage job.
A better starting design is logical shards: logical = hash(userId) % 256, plus a logical → physical DB table. With 4 servers, each holds 64 logical shards. Expanding = moving some logical shards whole to a new server and updating the table. None of the keys is recomputed.
Moving one logical shard:
- Copy. Copy the shard's snapshot to the new server.
- Catch up. Continuously apply the changes made since the snapshot through CDC or logical replication, until the lag approaches zero.
- Verify. Row counts, checksums, spot comparisons.
- Cut over. Pause writes for this shard briefly (seconds), wait for the last changes to arrive, update the routing table, reopen writes.
- Observe and clean up. Keep the old copy for a while (for rollback), then delete it.
An alternative is dual write: the application writes to the old and the new place at the same time, the old data is copied in the background, then reads switch to the new place. But if one of the two writes fails, they diverge; you have to catch that with reconciliation. The CDC-based way is usually more reliable.
Risks:
- the routing configuration not reaching all instances at the same moment — an instance with the old map writes to the old shard. Making the moved shard read-only in its old location protects against this;
- cross-shard queries and unique constraints;
- the move loading the source DB — limit the speed.
Move each logical shard separately, starting with the smallest. The first move is to check that the plan works.
Sign up to mark studied questions and save your progress.