Database Partitioning and Sharding Strategies
What you will learn
- What partitioning and sharding mean
- Range partitioning and hash partitioning
- Why the spread can be uneven and what a hot key is
- Why adding a shard can move most of the data
- The idea of consistent hashing
The Python blocks in this lesson are simulations that imitate an idea; they are not a real database. You can run each Python block on its own. The SQL blocks in section 3 count rows on the sample database you chose in lesson 4.1.
1. Splitting data instead of copying it
Replication (lesson 14.2) keeps copies of the same data. Partitioning does the opposite: it splits one large dataset into pieces, and each piece lives on a different place. When the pieces live on different machines, the technique is usually called sharding, and each piece is a shard.
| Replication | Partitioning (sharding) | |
|---|---|---|
| Each machine holds | all the data | part of the data |
| Helps with | availability, read capacity | data too big for one machine, write capacity |
| Needs a rule for | which copy to read | which shard owns each row |
Real systems usually do both: every shard is itself replicated.
The rule that decides which shard owns a row is based on a partition key, a column such as user_id. The choice of rule and key decides how well the system works.
2. Two basic rules
Range partitioning gives each shard a range of key values, for example surnames A to H on shard 0, I to R on shard 1 and S to Z on shard 2. Hash partitioning runs the key through a hash function and uses the result to pick a shard (for example hash(key) % number_of_shards). A hash function turns a key into a number that looks random but is always the same for the same key.
import zlib
def hash_shard(key, shards):
return zlib.crc32(key.encode()) % shards
print("Hash partitioning over 3 shards:")
for key in ["user1", "user2", "user3", "user4", "user5", "user6"]:
print(f" {key:7} -> shard {hash_shard(key, 3)}")
Hash partitioning over 3 shards:
user1 -> shard 1
user2 -> shard 2
user3 -> shard 2
user4 -> shard 0
user5 -> shard 1
user6 -> shard 0
(zlib.crc32 is a simple, repeatable hash from Python's standard library. Python's built-in hash() for text changes between runs, so it is not suitable here.)
Neighbouring keys such as user1 and user2 land on different shards. That is the point of hashing: it scatters keys evenly. The cost is that a query like "all users from user1 to user3" must ask several shards. With range partitioning, neighbouring keys stay together, so a range query often needs only one shard, but the spread can be uneven.
| Range | Hash | |
|---|---|---|
| Keeps neighbouring keys together | yes | no |
| Range queries | efficient | must ask many shards |
| Even spread | only if the data is evenly spread across the ranges | usually very even |
3. Uneven spread
Counting how many keys each shard gets shows the difference:
import zlib
def hash_shard(key, shards):
return zlib.crc32(key.encode()) % shards
def spread(assign, keys, shards):
counts = [0] * shards
for key in keys:
counts[assign(key)] += 1
return counts
keys = [f"user{n}" for n in range(1, 1001)]
print("1000 keys, hash over 4 shards:", spread(lambda k: hash_shard(k, 4), keys, 4))
names = (["Ahmed"] * 30 + ["Akter"] * 25 + ["Begum"] * 20 + ["Chowdhury"] * 10 + ["Hossain"] * 40
+ ["Islam"] * 35 + ["Khan"] * 50 + ["Rahman"] * 90 + ["Sultana"] * 5 + ["Uddin"] * 5)
def range_shard(name):
return 0 if name[0] <= "H" else 1 if name[0] <= "R" else 2
print("Range partitioning by first letter (A-H, I-R, S-Z):", spread(range_shard, names, 3))
print("Hash partitioning of the same names: ", spread(lambda n: hash_shard(n, 3), names, 3))
1000 keys, hash over 4 shards: [249, 251, 250, 250]
Range partitioning by first letter (A-H, I-R, S-Z): [125, 175, 10]
Hash partitioning of the same names: [130, 90, 90]
The made-up names are not evenly spread over the alphabet, so the range shards hold 125, 175 and only 10 rows: shard 2 is almost empty and shard 1 is the busiest. Hashing the same names gives 130, 90 and 90, which is more even. The hashed result is still not perfectly even because the list has only ten distinct names, repeated: identical keys always go to the same shard.
The same idea on a real table
The simulation used made-up keys. A real table shows the same effect, and SQL can count how many rows each "shard" would get. Below, range partitioning cuts the rows by a date or year, and hash-style partitioning uses id % 4, the remainder after dividing the id by 4, as a simple stand-in for hash(key) % number_of_shards. The queries only count; no data moves. (This part runs on the sample database you chose in lesson 4.1: use the Example data picker at the top.)
Orders, split by the month of the order (range) and by customer_id % 4 (hash-style):
SELECT substr(order_date, 1, 7) AS month, COUNT(*) AS orders FROM orders GROUP BY month ORDER BY month LIMIT 6;
SELECT customer_id % 4 AS shard, COUNT(*) AS orders FROM orders GROUP BY shard ORDER BY shard;
month orders
------- ------
2024-01 17
2024-02 18
2024-03 27
2024-04 24
2024-05 43
2024-06 40
(6 rows)
shard orders
----- ------
0 691
1 609
2 630
3 670
(4 rows)
The 33 months hold between 17 and 191 orders each, so whichever machine holds the busiest months works much harder than the one holding the first months. The four hash-style shards hold 609 to 691 orders: much more even.
Ledger entries, split by the year of the entry (range) and by account_id % 4 (hash-style):
SELECT substr(txn_date, 1, 4) AS year, COUNT(*) AS entries FROM transactions GROUP BY year ORDER BY year;
SELECT account_id % 4 AS shard, COUNT(*) AS entries FROM transactions GROUP BY shard ORDER BY shard;
year entries
---- -------
2018 84
2019 180
2020 352
2021 543
2022 657
2023 996
2024 1293
2025 1567
2026 1743
(9 rows)
shard entries
----- -------
0 1872
1 1920
2 1778
3 1845
(4 rows)
The bank grew year by year: 2018 holds 84 entries and 2026 holds 1,743, and all the new entries go to the newest range. The four hash-style shards hold 1,778 to 1,920 entries: much more even.
Students, split by the year they enrolled (range) and by student_id % 4 (hash-style):
SELECT enrolled_year, COUNT(*) AS students FROM students GROUP BY enrolled_year ORDER BY enrolled_year;
SELECT student_id % 4 AS shard, COUNT(*) AS students FROM students GROUP BY shard ORDER BY shard;
enrolled_year students
------------- --------
2023 83
2024 102
2025 86
2026 89
(4 rows)
shard students
----- --------
0 90
1 90
2 90
3 90
(4 rows)
Students enrol at a steady pace, so the four year ranges hold 83 to 102 students each: range partitioning works well here, because the data is evenly spread over the ranges. The hash-style shards hold exactly 90 each only because the ids are consecutive numbers; real hash values would be close to even, not exactly even.
Even spread of rows is not even spread of load: some keys are asked about far more than others. Count the rows of the busiest keys, next to the average:
SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id ORDER BY orders DESC, customer_id LIMIT 3;
SELECT ROUND(1.0 * COUNT(*) / COUNT(DISTINCT customer_id), 1) AS average_orders_per_customer FROM orders;
customer_id orders
----------- ------
72 17
292 17
134 15
(3 rows)
average_orders_per_customer
---------------------------
7.1
(1 row)
The three busiest customers have 17, 17 and 15 orders against an average of about 7: busier, but nowhere near a real hot key.
SELECT account_id, COUNT(*) AS entries FROM transactions GROUP BY account_id ORDER BY entries DESC, account_id LIMIT 3;
SELECT ROUND(1.0 * COUNT(*) / COUNT(DISTINCT account_id), 1) AS average_entries_per_account FROM transactions;
account_id entries
---------- -------
24 37
254 37
387 36
(3 rows)
average_entries_per_account
---------------------------
16.5
(1 row)
The three busiest accounts have 37, 37 and 36 ledger entries against an average of about 16.5: busier, but nowhere near a real hot key.
SELECT section_id, COUNT(*) AS attendance_rows FROM attendance GROUP BY section_id ORDER BY attendance_rows DESC, section_id LIMIT 3;
SELECT ROUND(1.0 * COUNT(*) / COUNT(DISTINCT section_id), 1) AS average_rows_per_section FROM attendance;
section_id attendance_rows
---------- ---------------
31 204
34 204
33 198
(3 rows)
average_rows_per_section
------------------------
146.6
(1 row)
The three busiest sections have 204, 204 and 198 attendance rows against an average of about 147: busier, but nowhere near a real hot key.
These tables have no real hot keys. The next section shows what one looks like.
4. The hot key problem
Even a perfect hash cannot help when one key is much more popular than the others, because all requests for the same key go to the same shard:
import zlib
def hash_shard(key, shards):
return zlib.crc32(key.encode()) % shards
requests = ["celebrity"] * 700 + [f"user{n}" for n in range(300)]
counts = [0] * 4
for key in requests:
counts[hash_shard(key, 4)] += 1
print("1000 requests, one key asked 700 times, hash over 4 shards:", counts)
1000 requests, one key asked 700 times, hash over 4 shards: [74, 76, 74, 776]
Three shards are nearly idle while one handles 776 of the 1000 requests. This is a hot key (or hot spot). The data is evenly spread, but the load is not. Typical remedies are to cache the popular key, or to split the hot key into several keys on purpose (for example celebrity#1 to celebrity#10) and combine the results when reading. Both add complexity, which is why a partition key should be chosen with the real access pattern in mind.
5. Changing the number of shards
With hash(key) % number_of_shards, adding a shard changes the result for most keys:
import zlib
def hash_shard(key, shards):
return zlib.crc32(key.encode()) % shards
keys = [f"user{n}" for n in range(1, 1001)]
moved = sum(1 for k in keys if hash_shard(k, 4) != hash_shard(k, 5))
print(f"Going from 4 to 5 shards moves {moved} of {len(keys)} keys")
Going from 4 to 5 shards moves 802 of 1000 keys
More than three quarters of the data would have to move to a different machine just because one machine was added. Moving data is slow and loads the network, so this is a poor design for a growing system.
Consistent hashing avoids most of that. Imagine the hash values arranged in a circle. Each node is placed at several points on the circle (here 50 points each, often called virtual nodes), and a key belongs to the first node point found going around the circle from the key's own position. Adding a node takes over only the stretches of the circle next to its new points:
import zlib, bisect
from collections import Counter
def h(text):
return zlib.crc32(text.encode())
def ring(nodes, points=50):
return sorted((h(f"{node}#{p}"), node) for node in nodes for p in range(points))
def owner(circle, key):
i = bisect.bisect(circle, (h(key), "")) % len(circle)
return circle[i][1]
keys = [f"user{n}" for n in range(1, 1001)]
four = ring(["A", "B", "C", "D"])
five = ring(["A", "B", "C", "D", "E"])
moved = sum(1 for k in keys if owner(four, k) != owner(five, k))
print("Adding a 5th node moves", moved, "of", len(keys), "keys")
print("Keys per node afterwards:", sorted(Counter(owner(five, k) for k in keys).items()))
Adding a 5th node moves 192 of 1000 keys
Keys per node afterwards: [('A', 244), ('B', 138), ('C', 197), ('D', 229), ('E', 192)]
Only 192 keys moved, close to the fifth that a new node should take over, and every key that moved went to the new node. The spread afterwards (138 to 244) is not perfectly even; using more points per node makes it smoother. Another common approach is to create many more small partitions than machines from the start and move whole partitions between machines when a machine is added.
Worked example: choosing a partition key
An online shop wants to shard its orders table. Compare three possible keys:
| Key | Good | Problem |
|---|---|---|
order_date (range) |
"orders this week" touches one shard | all new orders go to the newest shard: a hot spot |
customer_id (hash) |
even spread; one customer's orders stay together, so "my orders" asks one shard | a very large customer is heavy; "all orders today" asks every shard |
order_id (hash) |
very even spread | "my orders" must ask every shard |
If the most common question is "show this customer's orders", hashing on customer_id fits. The best key depends on what the application asks most often, not on the data alone. The shop and the keys are made up.
6. The costs of sharding
- Queries across shards (joins, totals, sorting) are harder and slower than on one machine.
- A transaction that changes rows on two shards needs extra coordination (lesson 14.6).
- Moving rows to rebalance shards takes time and care.
- Foreign keys and unique rules usually cannot be enforced across shards by the database alone.
For these reasons, sharding is normally a last resort after better indexes (chapter 7), a bigger machine, read replicas (lesson 14.2) and caching have been tried (lesson 14.1).
Common mistakes
- Using
hash % shardsand planning to add shards later. Most keys move; plan for consistent hashing or many small partitions. - Choosing a time-based range key for new data. All the writes go to the newest shard.
- Assuming a good hash means balanced load. A hot key still overloads one shard.
- Sharding too early. The extra complexity is permanent.
Key takeaways
- Partitioning splits data into pieces; sharding places the pieces on different machines. Replication copies the same data.
- Range partitioning keeps neighbours together but can be uneven; hash partitioning spreads evenly but scatters ranges.
- A hot key overloads one shard whatever the hash.
hash % shardsmoves most data when the number of shards changes; consistent hashing moves only about the new node's share.- Choose the partition key from the questions the application asks most.
Practice
1. What is the difference between replication and partitioning?
Show answer
Replication keeps copies of the same data on several machines. Partitioning splits the data so that each machine holds only part of it.
2. Why is a range query easy with range partitioning but harder with hash partitioning?
Show answer
Range partitioning keeps neighbouring keys on the same shard, so the query often needs one shard. Hashing scatters neighbouring keys across shards, so the query must ask several.
3. In section 3, why did range partitioning leave shard 2 with only 10 rows?
Show answer
The ranges were fixed by letter, and few of the made-up names start with S to Z. Range partitioning is only even when the data is evenly spread over the ranges.
4. A shop has an evenly hashed product_id key but one product is on sale and gets most of the requests. What problem is this, and name one remedy.
Show answer
A hot key: one shard receives most of the load. Remedies include caching that product, or splitting its key into several keys and combining the results.
5. Why does changing from 4 to 5 shards move 802 of 1000 keys with hash % shards, but only 192 with consistent hashing?
Show answer
With hash % shards the divisor changes, so the result changes for most keys. With consistent hashing a key stays with its node unless the new node's points fall next to it, so only about the new node's share (here close to one fifth) moves.
6. Give two reasons sharding is usually a last resort.
Show answer
For example: queries and transactions across shards are harder and slower, rebalancing moves data, and constraints such as foreign keys usually cannot be enforced across shards by the database alone.