Video in progress
A badly chosen shard key is causing problems in a running system. How do you replace it?
I build a parallel set of shards on the new key, stream the data over with CDC, compare, and move traffic gradually. I don't "rehash in place": a new set and a way back are mandatory.
📖 Answer
A typical case: the shard key was merchant_id. A few big merchants appeared, and their shard takes 30 times more load than the others. Or the opposite: the key was order_id, and the query "all orders of a merchant" fans out to every shard each time (scatter-gather).
The first question is whether you really need to change the key. Sometimes there are cheaper routes:
- move the hot merchants to a separate, bigger shard (directory-based routing: a
merchant → shardtable); - make the key more complex:
merchant_id + bucket(order_id) % 16, so a big merchant is spread over 16 shards; - for scatter queries, a separate table or a search system as a secondary index.
If you still have to change it:
- A new set of shards with the new key, empty.
- A CDC stream from the old shards (Debezium → Kafka → writer). Each record is placed by the new key. The Kafka key is the record's ID, so changes to one record arrive in order.
- Snapshot + stream: first a full copy, then the changes from the moment of the snapshot.
- Compare with checksums: the row count and a hash sum per tenant.
- Move reads, then writes, by groups of tenants. After writes move, reverse CDC (new → old) runs for a while, for rollback.
Unique IDs and sequences are a separate problem: if the old shards use local auto-increment, they collide in the new set. That's why I move to a global ID generator (Snowflake or UUIDv7) before the migration.
This can be one team's work for a whole quarter. Explain it to leadership not as "technical work" but as a concrete revenue risk (a big merchant is running slowly).
Sign up to mark studied questions and save your progress.