NoSQL · Data models beyond tables
What is sharding and how do you choose a shard key?
Short answer
Sharding splits data across independent nodes so storage and throughput scale beyond one machine. A good shard key has high cardinality, even access and low cross-shard query needs.
Each shard holds a subset of the data and handles its own reads and writes. A router or the client maps a key to a shard. The design question is which key distributes load evenly without forcing most queries to visit every shard.
Choosing the key
- High cardinality, so there are many possible values and no single dominant key
- Even write distribution, so one shard does not absorb a disproportionate share
- Query alignment, so common reads can be served from one shard
- Stable values, because changing a shard key usually means moving the row
function shardFor(key, shardCount) {
let hash = 2166136261;
for (let i = 0; i < key.length; i += 1) {
hash ^= key.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return Math.abs(hash) % shardCount;
}
const shard = shardFor("customer:7", 16);Resharding is the hard part. Consistent hashing or virtual buckets reduce the amount of data that moves when nodes are added, but some migration is unavoidable. Plan for a routing layer that can move a key without changing application code.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you handle a query that spans shards?
- 2What is consistent hashing?
- 3How would you reshard without downtime?
- 4Why is a timestamp a poor shard key for a global feed?
Say it in the interview
Sharding splits data across nodes so capacity grows beyond one machine. I choose a key with high cardinality and even access that also aligns with the common queries, because a query that touches every shard loses much of the benefit. I also consider how the key will be rebalanced later. Before sharding I check whether indexes, caching or read replicas solve the problem, since sharding adds cross-shard queries, transactions and migration risk.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live NoSQL mock interview and get scored feedback on depth, clarity and confidence.