What is sharding, and how do you choose a shard key?
MediumConceptDatabases: Replication & Sharding
Answer
Sharding (horizontal partitioning) splits a table's rows across several database nodes, each holding a subset, so that storage and write capacity grow with the number of nodes. The shard key determines which node holds each row.
- Range-based: each shard owns a contiguous key range; range queries are efficient, but sequential keys such as timestamps create a hot shard.
- Hash-based: a hash of the key picks the shard; load spreads evenly, but range queries must visit every shard.
- Directory-based: a lookup service maps keys to shards; flexible, but it adds a dependency.
- A good shard key has high cardinality, distributes load evenly, and appears in most queries so each request touches one shard. For example, shard a chat app by conversation ID, not by message timestamp.
More in Databases: Replication & Sharding
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | How do you choose between a SQL and a NoSQL database? | Concept | Easy | Read the answer to How do you choose between a SQL and a NoSQL database? | |||
| 2 | What is database replication, and how do synchronous and asynchronous replication differ? | Concept | Medium | Read the answer to What is database replication, and how do synchronous and asynchronous replication differ? | |||
| 3 | What is sharding, and how do you choose a shard key? | Concept | Medium | Read the answer to What is sharding, and how do you choose a shard key? | |||
| 4 | What problems does sharding introduce, and how are they handled? | Concept | Hard | Read the answer to What problems does sharding introduce, and how are they handled? |