Sub topic 3
Why and how to partition data
This chapter assumes you know hash maps and sorted lists, and that you understand basic client-server networking. You should also be comfortable with simple Python. By the end, you should be able to choose a partitioning scheme for a key-value store and explain what each choice costs.
Why partition at all
A single node has hard limits: disk capacity, memory, network bandwidth, and CPU. A key-value store that targets more data or traffic than one machine can handle must split its key space across several machines. This split is called partitioning, or sharding. Each piece is a partition (or shard), and each node is responsible for one or more partitions.
Partitioning gives you three things:
- Capacity. Total storage grows with the number of nodes.
- Throughput. Reads and writes for different keys go to different nodes and run in parallel.
- Fault isolation. A failed node affects only the partitions it owns, not the whole key space.
Partitioning is different from replication. Partitioning decides which nodes own a given key. Replication, covered in a later chapter, decides how many copies of that key exist. The two combine: each partition is typically stored on several nodes.
What a good partitioning scheme must do
Before comparing schemes, fix the criteria. A scheme should:
- Map every key to an owner deterministically. Any node or client with the same view of the cluster must compute the same answer.
- Spread load evenly. No node should hold much more data or take much more traffic than the others.
- Move little data when the cluster changes. Adding or removing a node should relocate only the keys that must move.
- Be cheap to compute. The lookup sits on the path of every request.
- Support the access patterns you need. If clients scan ranges of keys, the scheme must keep neighboring keys together, or at least make range queries possible.
These goals pull against each other. Even spread favors hashing. Range scans favor ordered keys.
Approach 1: range partitioning
Range partitioning assigns each node a contiguous interval of the key space. For example, keys beginning with a through f go to node 1, g through m to node 2, and so on.
Advantages:
- Range scans are efficient, because adjacent keys live on the same node.
- The mapping is easy to understand and inspect.
Disadvantages:
- Hot spots. If keys are timestamps or sequential IDs, all new writes land in the last range, and one node takes all the write traffic.
- Skew. Real key distributions are uneven, so equal-width ranges hold unequal amounts of data.
- Manual or complex rebalancing. You must split busy ranges and move them. Systems such as Bigtable and HBase do this automatically, but they need a metadata service to track the ranges.
Range partitioning fits systems where ordered scans matter more than uniform load. A Dynamo-style key-value store, which this tutorial builds toward, mostly serves point lookups, so it usually chooses hashing.
Approach 2: hash partitioning with modulo
Hash partitioning applies a hash function to the key and uses the result to pick a node. The hash scrambles the keys, so even sequential or clustered keys spread out evenly.
The simplest form is modulo:
import hashlib
def h(key: str) -> int:
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
def node_for(key: str, num_nodes: int) -> int:
return h(key) % num_nodes
keys = [f"user:{i}" for i in range(10_000)]
before = {k: node_for(k, 4) for k in keys}
after = {k: node_for(k, 5) for k in keys}
moved = sum(1 for k in keys if before[k] != after[k])
print(f"{moved / len(keys):.0%} of keys moved when going from 4 to 5 nodes")Run this and you will see roughly 80% of keys change owner. The reason is that hash % 4 and hash % 5 agree only occasionally. When the divisor changes, nearly every key maps somewhere new.
That is the central weakness of modulo hashing. Adding one node to a cluster of N moves about N/(N+1) of the data. In a store holding terabytes, that means a massive data shuffle just to grow by one machine, and the cluster is under heavy load while it happens.
Modulo hashing has two further drawbacks. Range scans become impossible, because adjacent keys are scattered. And it gives no way to give a larger machine a larger share of the keys, since every node gets the same slice.
Approach 3: a fixed number of partitions
A common improvement separates two mappings:
- Hash the key into one of a fixed, large number of partitions, say 1,024.
- Maintain a separate table that assigns partitions to nodes.
Because the number of partitions never changes, step 1 never changes. Adding a node means reassigning some whole partitions to it, and only the data in those partitions moves. Systems such as Elasticsearch, Couchbase, and Riak (with its ring of partitions) work this way.
The trade-offs:
- The partition count must be chosen up front. Too few limits how far the cluster can scale. Too many adds per-partition overhead.
- The assignment table must be stored and distributed to every node or client that routes requests.
- A node can own a different number of partitions, so a stronger machine can take more.
Approach 4: consistent hashing
Consistent hashing removes the fixed table by placing both keys and nodes on the same circular hash space, called the ring. A key belongs to the first node found going clockwise from the key's position. When a node joins or leaves, only the keys between it and its neighbor change owner.
The next chapter covers the ring in detail. For now, the property that matters is the one the criteria above asked for: adding a node moves roughly 1/(N+1) of the keys, not nearly all of them.
Comparing the schemes
| Scheme | Load spread | Data moved on resize | Range scans | State to maintain |
|---|---|---|---|---|
| Range | Uneven without splitting | Moderate, by splitting ranges | Efficient | Range-to-node map |
| Hash modulo | Even | Almost everything | Not possible | Node count only |
| Fixed partitions | Even if partitions are small | Whole partitions | Not possible | Partition-to-node table |
| Consistent hashing | Even with virtual nodes | About 1/(N+1) of keys | Not possible | Ring membership |
Edge cases and gotchas
Hot keys. Hashing spreads different keys evenly, but it cannot spread traffic to a single key. If one celebrity account receives a large share of reads, the node owning that key is overloaded no matter how well the data is balanced. Mitigations include caching in front of the store, splitting a hot key into several sub-keys (for example key#0 to key#7), and spreading reads across replicas.
Choosing the hash function. Partitioning needs a hash with good uniformity, not cryptographic strength. MD5 is fine here for its distribution, as the example above shows. Avoid language built-ins whose output varies between processes. Python's built-in hash() for strings is randomized per process, so two nodes would disagree about ownership. Use a stable hash such as MD5, MurmurHash, or xxHash.
Skewed data sizes. Even key counts do not guarantee even storage. A few values may be very large. Monitor bytes per node, not just keys per node.
Disagreeing views of the cluster. If two clients hold different node lists, they route the same key to different nodes. Writes land in the wrong place and reads miss them. Any partitioning scheme needs a way to distribute membership changes reliably. Later chapters cover gossip and routing.
Rebalancing under load. Moving data competes with live traffic. Throttle transfers, and keep serving reads from the old owner until the new owner has the data.
Multi-key operations. Once keys are scattered, operations that touch several keys (transactions, batch updates) may span nodes. A key-value store with a simple get/put/delete API avoids this, but if you add multi-key features, you pay for cross-node coordination.
Choosing a scheme
Pick based on the workload:
- Mostly point lookups, elastic cluster, no need for scans: consistent hashing or fixed partitions.
- Frequent range scans over ordered keys: range partitioning, accepting hot-spot management.
- A small, static cluster where downtime for resizing is acceptable: modulo hashing can work, but it is rarely the right choice for a store designed to grow.
The store designed in this tutorial serves point lookups and must grow and shrink without large data movements. That points to consistent hashing, which the next chapter builds.
Exercise
A cluster of 4 nodes uses hash(key) % 4 to pick the owner. You add a fifth node and switch to hash(key) % 5. Roughly what fraction of keys changes owner, and what fraction would move in an ideal scheme?
Show answer
About 80% of keys change owner under modulo hashing, because a key keeps its owner only when its hash gives the same remainder mod 4 and mod 5, which happens for about 1 in 5 keys. In an ideal scheme only the share the new node should own moves, about 1/5, or 20% of keys. Consistent hashing approaches that ideal.
Exercise
Your keys are time-ordered event IDs, and clients mostly read the latest few hours of events as a range. Why would hash partitioning hurt reads, and why would range partitioning hurt writes?
Show answer
Hash partitioning scatters adjacent IDs across all nodes, so a range read must contact every node and merge the results. Range partitioning keeps the range on one node, which makes reads efficient, but all new writes carry the highest IDs and land on the last range, so one node takes all the write load. A common compromise is to prefix the key with a small bucket value or to partition on a different attribute.