What is sharding, and how is it different from partitioning?
MediumConceptNoSQL, Replication & Sharding
Answer
Partitioning splits one large table into smaller pieces. Sharding is horizontal partitioning across several servers: each server, called a shard, holds a subset of the rows, so both the data and the load are divided among machines.
- Horizontal partitioning splits rows (2023 orders in one piece, 2024 orders in another); vertical partitioning splits columns. Partitioning on a single server, as in MySQL or PostgreSQL table partitioning, mainly helps manageability and lets queries skip irrelevant pieces.
- The shard key decides where each row lives: by range (IDs 1 to 1,000,000 on shard 1), by hash (
hash(user_id) % 4) or through a lookup directory. - Sharding enables horizontal scaling (adding servers) instead of vertical scaling (buying a bigger server).
- Costs: cross-shard queries and joins are slow, cross-shard transactions are hard, and a poor shard key creates hot spots.
Example: Three shards with shard = user_id % 3:
user 10 -> 10 % 3 = 1 -> shard 1
user 11 -> 11 % 3 = 2 -> shard 2
user 12 -> 12 % 3 = 0 -> shard 0
All of user 10's orders live on shard 1, so loading that user's orders touches only one server.
More in NoSQL, Replication & Sharding
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between SQL and NoSQL databases? | Concept | Easy | Read the answer to What is the difference between SQL and NoSQL databases? | |||
| 2 | What are the different types of NoSQL databases? | Concept | Easy | Read the answer to What are the different types of NoSQL databases? | |||
| 3 | What is the CAP theorem? | Concept | Medium | Read the answer to What is the CAP theorem? | |||
| 4 | What is database replication, and what are its types? | Concept | Medium | Read the answer to What is database replication, and what are its types? | |||
| 5 | What is sharding, and how is it different from partitioning? | Concept | Medium | Read the answer to What is sharding, and how is it different from partitioning? |