What it is
Partitioning (sharding) splits a dataset into pieces that live on different machines. The partitioning strategy decides which partition owns which key. The two basic strategies are range partitioning, where each partition owns a contiguous range of keys, and hash partitioning, where a hash of the key decides. Most real schemas combine them with a compound key. The database sharding lesson covers why and when to shard; this lesson is about how to split.
Why it exists
The strategy decides two things that matter more than anything else about a partitioned system: whether load spreads evenly (or piles onto one partition) and which queries stay on one partition (or must ask all of them). Both follow directly from the key and the scheme, so they can be reasoned about before any data exists.
How it works
Range partitioning. Keys are kept in sorted order, and each partition owns a range such as [08:00, 16:00). A router or metadata service holds the range boundaries. Range queries are cheap: one or two partitions, reading contiguous sorted data. HBase regions, Bigtable tablets, Spanner splits and CockroachDB ranges all work this way, and split a range in two when it grows too large.
The sequential-key problem. If the key always increases (timestamps, auto-increment ids, time-ordered UUIDs), every new row belongs to the newest range. All inserts hit one partition while the others serve only reads of old data. In the lesson, 360 inserts per second land on a partition that can absorb about 200.
Hash partitioning. The router hashes the key and maps the hash to a partition, usually through hash ranges or a consistent-hash ring. Adjacent keys get unrelated hashes, so sequential inserts spread evenly. DynamoDB, Cassandra and Kafka partition by key hash. Point lookups still go to exactly one partition.
The range-query problem. Hashing destroys order. A query for a key range can match rows on any partition, so the router must scatter the query to all of them and gather the results. It costs work on every partition and is only as fast as the slowest one. Adding partitions makes it more expensive, not less.
Compound keys. Pick the partition key from the main access pattern and sort within the partition by a second column: (sensor_id, timestamp), (conversation_id, sent_at), (customer_id, order_date). The partition is chosen by hashing the first part, so writes spread across entities, and a range query within one entity reads a contiguous run on one partition. This is Cassandra's partition key plus clustering columns and DynamoDB's partition key plus sort key.
Hot keys. Hashing spreads keys, not load. When one key gets a large share of traffic (a celebrity account, a viral product, a busy sensor), its partition gets that share too, whatever the scheme. Adding partitions doesn't help: the hot key still has exactly one home. Options: salt the key (key#0 … key#k−1) so its writes spread over k partitions, and read all k sub-keys back; cache its reads; or give its partition a bigger machine. Managed stores do some of this automatically (DynamoDB adaptive capacity can split partitions and isolate frequently accessed items), but no system can split a single item.
Rebalancing. When nodes are added, data has to move. hash(key) mod N is the wrong tool: going from N to N + 1 changes the home of most keys (about 75% from 3 to 4). Better options:
- Fixed number of partitions, many more than nodes (Elasticsearch shards, Riak's ring, Couchbase's 1,024 vBuckets). A new node takes over a few whole partitions; keys never change partition.
- Dynamic splitting of range partitions when they grow (HBase, CockroachDB, Spanner), then moving one half.
- Consistent hashing with virtual nodes, where a new node takes over only its slices of the ring.
In every case the move itself, copying while serving and then switching ownership atomically, is the slow and risky part.
When to use it
- Range when range scans or ordered reads dominate (time series per device, sorted listings) and the key is not monotonically increasing, or is prefixed so that it isn't.
- Hash for key–value access with even write spread, when range queries over the whole key space are rare.
- Compound for almost every entity-centric schema: hash the entity, sort its children.
When not to
- Range on a sequential key for write-heavy data without a prefix or salt.
- Hash when range scans across all keys are a main query. Use a range-partitioned secondary structure or an analytics copy instead.
- Salting by default. It multiplies read cost; apply it only to keys known to be hot.
Trade-offs
| Strategy | Strengths | Weaknesses |
|---|---|---|
| Range | Cheap range scans, ordered data, natural splits | Sequential keys hot-spot the last partition; skewed ranges need splitting |
| Hash | Even spread of keys and writes; simple point lookups | Range queries scatter to all partitions; order lost |
| Compound (hash + sort) | Spread across entities, cheap ranges within one entity | Queries across entities still scatter; a huge entity is one hot partition |
| Salting a hot key | Spreads one key's writes over k partitions | Reads of that key fan out k ways; must track salted keys |
| Fixed partitions | Rebalancing moves whole partitions only | Partition count chosen up front; too few limits growth, too many costs overhead |
Alternatives
- Don't partition yet: a bigger machine, read replicas and caching often postpone it for years.
- Directory-based partitioning: a lookup service maps each key (or tenant) to a partition explicitly, which allows moving individual tenants at the cost of another dependency.
- Secondary indexes: local (per partition, queries scatter) or global (partitioned by the indexed value, writes update another partition asynchronously).
Failure modes
- Hot partitions from sequential keys or popular keys: one partition throttles or times out while others idle.
- Scatter-gather tail latency: a query over all partitions waits for the slowest; with many partitions some partition is almost always slow.
- Unbalanced ranges: data grows unevenly, one range becomes huge until it is split.
- Rebalancing storms: moving too much data at once saturates networks and disks; mod-N schemes move almost everything.
- Large partitions: one entity (a giant customer, an always-on sensor) outgrows a single partition under a compound key; bucket it by time (
(sensor_id, day)).
In production
Choose the partition key from the top queries and the expected key distribution, then check both with real data: the share of traffic for the top 1% of keys, and how many partitions each main query touches. Monitor per-partition throughput and throttling, not only cluster averages, because hot partitions hide in averages. Bucket unbounded time series by period, prefix or hash sequential ids, and keep a short list of known-hot keys that get salting or caching.
Common misconceptions
- "Hashing fixes hot spots." It fixes hot ranges from sequential keys. A single hot key stays hot.
- "More partitions means faster queries." Point lookups don't care; scatter-gather queries get more expensive.
- "Range partitioning is outdated." Many modern distributed SQL databases are range-partitioned, because ordered scans and splits are valuable.
- "Rebalancing is just changing N." With mod N it moves most of the data; real systems move whole partitions.
Interview angle
When you shard, name the partition key and justify it from the access pattern: "partition by user_id, sort by created_at: a user's timeline is one partition read, writes spread across users." Then raise the risks yourself: sequential keys (don't range-partition on timestamps), hot keys (celebrities: salt or cache), cross-partition queries (scatter-gather or a separate index), and how you'd add capacity (fixed partitions or consistent hashing, never mod N).
Model assumptions
The engine parts of this lesson are a simplified model, not a benchmark. The ingest service writes readings with Poisson arrivals; every partition is a database with 6 connections and a 30 ms mean write (lognormal, cv 0.4), so it absorbs about 200 writes per second; a write that waits more than 300 ms for a connection fails. Range partitioning by timestamp is modelled by sending every write to the partition that owns the newest range, since each new reading's key is "now". Hash partitioning uses a consistent-hash ring with 64 virtual nodes per partition. Keys are unique per reading until the hot-key step, where they are 1,000 sensor ids with a Zipf(1.5) popularity (the busiest sensor sends about 39% of writes). The range query, scatter-gather, compound key, salting and data-movement steps are scripted illustrations: the engine routes single requests by key and does not model scans, sub-keys or copying data. Adding a partition moves traffic instantly in the simulation. Numbers show behaviour and orders of magnitude only.