Partitioning and Sharding
Replication copies all data to every node, so it can't help when the data set or the write rate is too big for one machine. Partitioning (called sharding when the partitions live on different servers) splits the data so that each node owns only a part of it. Ten shards mean roughly a tenth of the data and a tenth of the writes per node.
+------------- router / client library -------------+
| shard = f(partition key) |
+----------------------------------------------------+
| | |
[shard 0] [shard 1] [shard 2] each shard is usually
users 0-33M users 33-66M users 66-99M also replicatedThe partition key is the most important choice: every query that includes it goes to one shard; every query without it must ask all shards (scatter-gather).
Range vs hash partitioning
| Range partitioning | Hash partitioning | |
|---|---|---|
| Rule | Key ranges: A-F, G-M, … or date ranges |
hash(key) mod N or hash ranges |
| Range queries | Efficient (adjacent keys on one shard) | Must query every shard |
| Hot spots | Likely with sequential keys (all new rows hit the last shard) | Rare; keys spread evenly |
| Used by | HBase, Bigtable, Spanner, MongoDB ranged | Cassandra, DynamoDB, Redis Cluster |
Let's distribute 10,000 sequential order ids both ways and look at where today's writes land:
import hashlib
from collections import Counter
N_SHARDS = 4
def hash_shard(key):
digest = hashlib.md5(str(key).encode()).hexdigest()
return int(digest, 16) % N_SHARDS
def range_shard(key, boundaries=(2_500, 5_000, 7_500)):
for shard, upper in enumerate(boundaries):
if key < upper:
return shard
return len(boundaries)
all_orders = range(10_000)
todays_orders = range(9_000, 10_000) # newest ids, where the write traffic is
for name, f in [("range", range_shard), ("hash", hash_shard)]:
total = Counter(f(k) for k in all_orders)
today = Counter(f(k) for k in todays_orders)
print(f"{name:<5} all data: {[total[s] for s in range(N_SHARDS)]} today's writes: {[today[s] for s in range(N_SHARDS)]}")range all data: [2500, 2500, 2500, 2500] today's writes: [0, 0, 0, 1000]
hash all data: [2518, 2460, 2474, 2548] today's writes: [243, 265, 247, 245]
Both layouts store about the same amount per shard, but with range partitioning all of today's writes hit shard 3, the hot shard, while the others sit idle. Hashing spreads them out.
The problem with mod N
Hashing with hash % N has a nasty property: when you add a shard, almost every key changes shard, so almost all data must move.
import hashlib
def shard(key, n):
return int(hashlib.md5(key.encode()).hexdigest(), 16) % n
keys = [f"user:{i}" for i in range(10_000)]
for old, new in [(4, 5), (10, 11), (10, 20)]:
moved = sum(shard(k, old) != shard(k, new) for k in keys)
print(f"{old:2} -> {new:2} shards: {moved / len(keys):5.1%} of keys move") 4 -> 5 shards: 79.6% of keys move
10 -> 11 shards: 90.6% of keys move
10 -> 20 shards: 49.5% of keys move
Going from 10 to 11 shards moves over 90% of keys, while only about 9% needed to move to fill the new shard. Two standard fixes:
- Many fixed partitions: create, say, 1,024 logical partitions up front (
hash % 1024) and assign partitions to nodes. Adding a node moves whole partitions; keys never change partition. Used by Elasticsearch, Riak, Couchbase and Kafka. - Consistent hashing (next lesson): nodes and keys share a hash ring, and adding a node moves only the keys in its new slice.
Fixed partitions in practice
import hashlib
from collections import Counter
N_PARTITIONS = 12
def partition(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16) % N_PARTITIONS
assignment = {p: f"node{p % 3}" for p in range(N_PARTITIONS)} # 3 nodes
def add_node(assignment, new_node):
per_node = len(assignment) // (len(set(assignment.values())) + 1)
moved = []
for p in sorted(assignment):
if len(moved) == per_node:
break
donors = Counter(assignment.values())
if donors[assignment[p]] > per_node: # take from the busiest nodes
moved.append(p)
assignment[p] = new_node
return moved
keys = [f"user:{i}" for i in range(10_000)]
before = {k: assignment[partition(k)] for k in keys}
moved = add_node(assignment, "node3")
after = {k: assignment[partition(k)] for k in keys}
print("partitions moved:", moved)
print("partitions per node:", dict(sorted(Counter(assignment.values()).items())))
print(f"keys that moved: {sum(before[k] != after[k] for k in keys) / len(keys):.1%}")partitions moved: [0, 1, 2]
partitions per node: {'node0': 3, 'node1': 3, 'node2': 3, 'node3': 3}
keys that moved: 25.4%
Only the moved partitions' keys travel, about a quarter of the data, which is exactly the share the new node should own.
Hot keys and other pitfalls
- Celebrity keys: one user with 50 million followers puts all their traffic on one shard. Split hot keys by adding a suffix (
user:42#0…user:42#9) and merge on read, or cache them aggressively. - Cross-shard queries: joins and aggregates across shards are slow and complex. Choose a key that keeps related data together (all of a customer's orders on the customer's shard).
- Cross-shard transactions need two-phase commit or sagas (see Distributed Transactions).
- Secondary indexes: a local index per shard means scatter-gather reads; a global index partitioned by the indexed value means writes touch several shards.
- Rebalancing costs network and disk; throttle it and do it gradually.
Tip: Shard as late as you can and as early as you must. A single well-tuned primary with read replicas goes a long way; sharding adds permanent complexity to every query.
Test yourself
Why do sequential keys cause a hot spot with range partitioning?
- Hashing them is slow
- All new keys fall into the last range, so one shard takes every write
- They can't be indexed
- They make shards unequal in size
What happens with hash(key) % N when N changes from 10 to 11?
- About 9% of keys move
- About half of the keys move
- Over 90% of keys move
- No keys move
How do fixed logical partitions make rebalancing cheaper?
- Keys never change partition; only whole partitions move between nodes
- They compress data
- They avoid replication
- They use range queries