Video in progress

Strong Junior 🏗️ System design

What is the downside of sharding data with the `userId % N` formula?

int shardFor(long userId, int shardCount) {
    return (int) (userId % shardCount);
}
// we started with 4 shards, now we want to add a 5th

When the shard count changes, almost all keys move to a different shard: going from 4 to 5, you have to move about 80% of the data. Consistent hashing, or splitting into many virtual buckets up front, reduces this problem.

📖 Answer

Check it yourself: for userId = 13, 13 % 4 = 1 and 13 % 5 = 3. For userId = 20: 0 and 0. A key stays in place only when both results happen to match — roughly one in every 5. The rest have to move.

What that means: moving terabytes of data to new places, routing reads and writes correctly during that time, and the caches suddenly going "cold" all at once.

Two typical solutions:

Consistent hashing. Shards and keys are placed on the same hash ring, and a key belongs to the nearest shard clockwise. When a new shard is added, only part of its neighbor's keys move — about 1/N.

Many logical buckets. From the start you create, say, 1024 logical partitions and distribute them to physical servers through a mapping. When a new server is added, some partitions move to it whole, and the key → partition formula doesn't change.

The second way is easier to understand in practice and easier to manage — many distributed databases work like this.