Choosing a shard key
The field the placement is computed from
Section titled “The field the placement is computed from”The last lesson placed user:3400 on a shard by looking at the whole key. In a real table the placement uses one field, or a few: the shard key. Every row with the same shard key value lives together, and rows with different values may be anywhere. The strategy (range, hash, directory) says how a value becomes a shard. The shard key says which values count as the same.
That makes the shard key the choice that is hardest to take back. A different strategy moves rows to other shards. A different key changes which rows belong together, so it can mean moving rows and rewriting the queries that name the old key. It is also the choice that decides whether adding shards helps at all, as the cache module found for one dominant key: a key lives on one shard, whatever the number of shards.
Mental model. The shard key is the unit of placement. Anything with the same value cannot be split, so it can only be as balanced as the values are. Pick a key whose values are many, evenly used and not clustered in time, and which your frequent queries can name.
Four questions to ask of a candidate
Section titled “Four questions to ask of a candidate”MongoDB’s guide to choosing a shard key lists the properties to look at. They apply to other systems, because they follow from how placement works.
- How many distinct values are there? The number of distinct values caps the number of pieces the data can be cut into. MongoDB’s example is a key that holds the continent, which has 7 values: it caps the data at 7 chunks, however many shards are added. A key with few values leaves shards idle.
- How often does the commonest value occur? If most rows share a few values, the shards holding those values become the bottleneck, and a single value that is too big for a shard cannot be split. MongoDB’s documentation names such oversized pieces jumbo chunks.
- Does the value only grow? A timestamp or an automatic sequence number increases for ever. For range placement all new rows go to the top range, and so to one shard. The documentation says so, and suggests hashed sharding for a key that changes monotonically.
- Do the frequent queries name it? A query that contains the shard key can go to the shards that hold it. MongoDB calls these targeted queries. A query that does not contain it is sent to all shards, and the documentation calls it scatter-gather. Lesson 5 comes back to that cost. Vitess describes the same thing from its side: without a vindex that fits the query, the request is scattered to every shard.
No single question settles it. The guide says plainly that a key with many values does not by itself guarantee an even spread, and that frequency and monotonic change also matter. It also offers a command, analyzeShardKey, to evaluate candidates on sampled queries before committing.
Try it: what a key cannot fix
Section titled “Try it: what a key cannot fix”The lab sends 40% of the requests to eight neighbouring keys, user:3400 to user:3407, like a burst of new accounts or one customer’s records, and the rest to any key. It starts with Range on four shards. Read Hottest shard.
A large share of the traffic goes to a few neighbouring keys. See which strategies keep them on one shard, then lower the number of hot keys to one.
What the last change did
Add or remove a shard, change the strategy, the virtual nodes or the traffic, or press Rebalance. This panel says how many keys the change moved.
- Hottest shard
- 55%Shard 2: 2.2× the fair share of 25%
- Keys moved by the last change
- —No change yet
- Keys per shard
- 2,500 most, 2,500 fewest10,000 keys on 4 shards
- Placement metadata
- 4 entriesOne boundary for each range.
fair share 25% Hottest shard
Keys arriving
A sample of the requests, and the shard that serves each key under the current layout. The chart and the table hold the figures.
- user:7539Shard 4
- user:4900Shard 2
- user:9833Shard 4
- user:3404Shard 2hot key
- user:3406Shard 2hot key
- user:7741Shard 4
- user:4536Shard 2
- user:3405Shard 2hot key
Look up a key
user:1234 is on Shard 1.
| Shard | Keys held | Share of requests | Keys moved in | Keys moved out |
|---|---|---|---|---|
| Shard 1 | 2,500 (25%) | 15% | 0 | 0 |
| Shard 2 · hottest | 2,500 (25%) | 55% | 0 | 0 |
| Shard 3 | 2,500 (25%) | 15% | 0 | 0 |
| Shard 4 | 2,500 (25%) | 15% | 0 | 0 |
Shards are numbered from 1 here. In the C# example the same shards are node-0, node-1 and so on. The keys moved in and out are those of the last change.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- The lab counts 10,000 keys, user:0 to user:9999, the same keys as the C# example. A key moves when the shard that holds it changes, and every key counts the same, whatever it holds.
- The hash is FNV-1a over the text of the key, and a virtual node sits at the hash of its number, a # and the name of its shard. This is the definition the C# example uses, so the same keys move. It is not a cryptographic hash.
- A shard's load is the share of requests that reach its keys, worked out from how popular each key is. It is what a very long stream converges to, not a measurement of a run. The stream shown beside it is a sample.
- Hot keys are neighbouring numbers, starting at user:3400, like a burst of new ids or one customer's records. The rest of the requests choose any key with equal chance.
Simplifications
- No data is copied and nothing takes time: a resize or a rebalance is instant. In a real system, moving keys copies data, competes with the traffic, and can take hours.
- Range and directory follow simple rules: split the busiest range, move the hottest keys first. Real systems choose when to split and move, and limit how much moves at once.
- FNV-1a puts labels that differ only in their last character close together, so with a few virtual nodes this ring is more lopsided than points placed at random would be. With 100 or more, the two agree more closely.
- Cross-shard queries, replicas and the cost of looking up a directory are not modelled: the lab counts where keys live and what changing that costs.
Parameter values are illustrative. They are not benchmarks of any real product.
With Range, the hottest shard receives 55% of the requests against a fair 25%. The eight keys are neighbours, so they share a range, and that shard also takes its quarter of the other 60%: 40% plus 15% is 55%. Switch Strategy to Hash mod N: the hottest shard falls to 25%, an even split, because a hash scatters neighbours and the eight keys land on different shards. With Consistent hashing it is 30.3%, not quite even, because this ring leaves the shards with different numbers of keys.
So for a burst of neighbouring keys, the choice of placement matters a great deal, and hashing the key is what spreads it. Now take away the neighbours. Set Hot keys to 1 and Requests to hot keys to 30%, one single key with 30% of the traffic. For Range, Hash mod N and Directory the hottest shard has 47.5%, and for Consistent hashing 45.8%. Nothing helps, because one key is one key: it lives on one shard, and that shard gets the 30% plus its share of the rest. The model for equal shards is 0.3 + 0.7 / 4, which is 47.5%. With more shards the share falls towards 30% and never goes below it.
Two different problems, then, and the shard key cannot fix both. Many keys that are close together is a placement problem, solved by hashing the key or, for a range layout, by spreading the range. One key that is simply too popular is a data problem, and it needs a different treatment: the key must be split into several, replicated for reads, or kept out of the hot path with a cache, as in the caching module’s lesson on hot keys.
What happens if the key has three values?
Section titled “What happens if the key has three values?”Say a table is sharded by country, and the business operates in three. Every row of a country has the same shard key value, so it lives on exactly one shard. With three values the data can occupy at most three shards, however many shards you buy. A fourth shard receives nothing under any of the three strategies, because no strategy can split a single value. If one of the three countries holds half the rows, the shard that holds it holds half the data, and for a hash, adding shards does not change that.
A compound key repairs this when there is a second field with many values: country plus customer id puts each customer on its own place, while all the rows of one customer still stay together. MongoDB’s guide suggests adding a field with unique or low-frequency values for a key whose values are too frequent. The price is that a query by country alone no longer names the whole key, and may have to ask several shards.
- The shard key is the field the placement is computed from. Rows with the same value stay together, so the key limits how finely the data can be split, and it is hard to change later.
- Ask four things of a candidate: how many distinct values it has, how often the commonest one occurs, whether it only grows, and whether the frequent queries contain it.
- A burst of neighbouring keys puts 55% of the requests on one of four shards under range placement, and 25% under hash mod N.
- One key with 30% of the traffic leaves the busiest of four shards with 47.5% (45.8% on the ring), and no placement strategy changes that. The share is
0.3 + 0.7 / 4. - A key with three values uses at most three shards. A compound key restores the spread, at the price of queries that name only part of it.
Next: consistent hashing, which keeps most keys in place when the shards change.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.