Partitioning and sharding strategies
Split data across machines by range, hash or directory, and rebalance without downtime.
20 min readWhy partition
Replication copies the same data to more machines, which scales reads but not writes or size. Partitioning (sharding) splits the data so each machine holds a subset. If one node handles 10 000 writes per second and you need 150 000 at peak with 30% headroom, you need about 150 000 / 7 000, so 22 partitions. If the dataset is 40 TB and a node comfortably holds 2 TB, you need at least 20. Take the larger number, then add replicas on top.
Range, hash and directory
Each strategy is a different function from key to partition, and the right one depends on whether your hottest queries are point lookups or range scans. Compound keys can mix them: Cassandra hashes the partition key to pick a node, then stores rows in clustering-key order within it.
- Range: partition by key ranges (A to F, G to M). Range scans are efficient, but sequential keys such as timestamps send every write to the last partition
- Hash: partition by hash(key) mod partitions. Load spreads evenly, but range scans must query every partition
- Directory: a lookup service maps each key or tenant to a partition. Maximum flexibility, but the directory must be fast, cached and highly available
Rebalancing without moving everything
Naive hash mod N is a trap: going from 10 to 11 nodes changes the home of about 91% of keys. Instead, create many more partitions than nodes up front, for example 1 024 partitions on 16 nodes, and move whole partitions when nodes are added. Only the moved partitions transfer data. Systems like Elasticsearch, Riak and Couchbase work this way. Alternatively, split partitions dynamically when they exceed a size threshold, as HBase and DynamoDB do.
Hot spots
Even perfect hashing cannot spread one celebrity's key across machines. If one key receives 50 000 writes per second, salt it: append a random suffix 0 to 9 on write so it spreads across 10 partitions, then read all 10 and merge. Detect hot partitions with per-partition metrics, not just cluster averages; a cluster at 30% average can have one partition at 100%. Choose partition keys with high cardinality and even access, such as user_id rather than country.
Key takeaways
- Size partitions from peak write rate and data volume, whichever needs more
- Range partitioning keeps scans cheap but risks hot tails; hashing spreads load but scatters scans
- Pre-split into many fixed partitions so rebalancing moves whole partitions, not most keys
- Watch per-partition load and salt hot keys deliberately
Sign in to track lessons and earn badges.