Course contents

05. Distributed Databases Lesson 8 of 10

Partitioning Strategies

Range vs hash partitioning: watch sequential keys pile onto one partition, hashing spread them, range scans fan out, and a hot key defeat both.

17 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Range partitioning keeps adjacent keys together: cheap range scans, but sequential keys pile onto the last partition.
  • Hash partitioning spreads keys evenly, but range queries must ask every partition and wait for the slowest.
  • A compound key (hash one part, sort by another) gives both for queries within one entity.
  • One key always lives on one partition, so hot keys make hot partitions; salting splits them at the cost of fan-out reads.
  • Rebalance by moving whole partitions (fixed count or splits), never by re-hashing every key with mod N.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Range partitioning: neighbours stay together

    A table of sensor readings is too big for one database, so it is split into three partitions by key range: each partition owns a contiguous slice of the timestamp key. Partition 1 holds midnight to 08:00, Partition 2 08:00 to 16:00, Partition 3 everything from 16:00 on.

    The router keeps that range map. A query for 09:00–10:00 maps to exactly one range, so it goes to Partition 2 only (scripted packets). Range scans are cheap because neighbouring keys sit together, sorted. HBase, Bigtable, Spanner and CockroachDB split data by key range.

    Scene: Scripted: three partitions own consecutive time ranges. A query for 09:00 to 10:00 goes through the router to Partition 2 only and comes back.

    Key idea: Range partitioning keeps adjacent keys on the same partition, so range queries touch one or few partitions.

  2. 2. Every new row lands on the last partition

    The ingest service now writes 360 readings per second. Each reading’s key is its timestamp, and *now* is always in the newest range, so every write goes to Partition 3.

    One partition absorbs about 200 writes per second. Partition 3 is saturated, writes wait for connections and many fail with pool timeouts, while Partitions 1 and 2 sit idle. Three machines, the write capacity of one.

    Any monotonically increasing key does this under range partitioning: timestamps, auto-increment ids, time-ordered UUIDs.

    Scene: All 360 writes per second go to Partition 3, which is saturated and fails many writes with pool timeouts. Partitions 1 and 2 receive nothing.

    Key idea: Range partitioning on an ever-increasing key sends all new writes to one partition.

  3. 3. Hash partitioning spreads the writes

    Switch the router to hash partitioning: it hashes each key and places it on a hash ring. Consecutive timestamps produce unrelated hashes, so the writes spread over all three partitions, each 60–80% busy (the ring’s slices are not perfectly equal), and the errors stop.

    This is how DynamoDB, Cassandra and most key–value stores place data by default. (How the ring keeps data movement small when partitions are added is covered in the consistent hashing lesson.)

    Scene: The router hashes each key. Writes spread over all three partitions, each 60 to 80 percent busy, and nothing fails.

    Key idea: Hashing the key destroys key order, which spreads sequential writes evenly.

  4. 4. Range queries now hit every partition

    The price of hashing: neighbouring keys are scattered. The same query for 09:00–10:00 can no longer be sent to one partition; its rows could be anywhere. The router has to ask every partition and merge the results (scatter-gather; scripted packets).

    The query is now only as fast as the slowest partition: two answer in about 20 ms, but Partition 1 is busy and takes about 55 ms, so the whole query waits for it. Every range query also costs work on every partition, so adding partitions does not make these queries cheaper.

    Scene: Scripted: the range query is sent to all three partitions. Partitions 2 and 3 answer quickly, Partition 1 answers last, and only then does the router return the merged result.

    Key idea: Hash partitioning turns range queries into scatter-gather across all partitions, paced by the slowest one.

  5. 5. Hash one part, sort by the other

    Most queries ask for one sensor’s readings over a time range. So use a compound key: (sensor_id, timestamp). The router hashes only sensor_id to pick the partition; inside the partition, rows are sorted by timestamp.

    “Sensor 42, 09:00–10:00” now goes to one partition (scripted) and reads a contiguous run of rows. Writes still spread, because thousands of sensors hash to different partitions. This is Cassandra’s partition key plus clustering columns, or DynamoDB’s partition key plus sort key.

    Scene: Scripted: with the compound key (sensor id, timestamp), the query for sensor 42 between 09:00 and 10:00 goes to Partition 1 only.

    Key idea: Choose the partition key from your main access pattern; a compound key gives both spread writes and cheap range reads within one entity.

  6. 6. One popular key, one hot partition

    Traffic resumes at 400 writes per second, now keyed by sensor. But sensors are not equally chatty: a few (a busy turnstile, a high-frequency trading feed) send most of the readings. Here popularity follows a Zipf curve over 1,000 sensors, and the busiest one alone sends over a third of all writes.

    Hashing spreads keys, not load. Every write for that sensor goes to the same partition, Partition 3, which saturates and fails writes while Partition 1 is mostly idle. A better hash function cannot fix it: one key always maps to one partition.

    Scene: Writes are keyed by 1,000 sensors with very uneven popularity. Partition 3 owns the busiest sensor, is saturated and fails some writes; Partition 1 is mostly idle.

    Key idea: A hot key makes a hot partition under any partitioning scheme, because one key always lives on one partition.

  7. 7. Split a hot key by salting it

    For a key you know is hot, add a salt: write sensor 7’s readings under 7#0, 7#1 and 7#2 in turn. The three sub-keys hash to different partitions, so the hot key’s writes spread three ways (scripted packets).

    Reads pay for it: to get sensor 7’s data the router must read all three sub-keys and merge them. So salt only the few keys that need it, and keep track of which ones are salted. Managed stores do a version of this automatically (DynamoDB splits hot partitions and isolates frequently accessed items), but no system can split a single item.

    Scene: Scripted: three writes for the hot sensor go to Partitions 1, 2 and 3 under salted sub-keys. A read for that sensor then asks all three partitions and merges the answers.

    Key idea: Salting spreads one hot key over several partitions, at the cost of fan-out reads for that key.

  8. 8. Adding a node: move whole partitions

    Data grows and a fourth node joins. How much data has to move?

    With hash(key) mod N, going from 3 to 4 changes the home of about three quarters of all keys. Two common ways to avoid that: create many more partitions than nodes up front (say 12 partitions on 3 nodes) and move a few whole partitions to the new node; or split a range partition when it grows too large and move one half (dynamic partitioning, used by HBase, CockroachDB and others). Consistent hashing is a third.

    In the scripted packets, three partitions’ worth of data is copied to the new node in parallel. Copying while still serving traffic, then switching ownership atomically, is the slow and risky part of every rebalance.

    Scene: Scripted: a fourth node joins. Data is copied from Partitions 1, 2 and 3 to the new Partition 4 in parallel.

    Key idea: Rebalance by moving whole partitions (fixed count, or split on growth), never by re-hashing every key.

  9. 9. Choosing a strategy

    Back to live traffic: 400 writes per second over four partitions on the hash ring. Partition 3 is still saturated: the fourth partition took some keys, but not the busiest sensor. More partitions do not fix a hot key.

    The choice in short: range partitioning for range scans and ordered data, with care for sequential keys; hash partitioning for even writes, at the price of scatter-gather range queries; a compound key to get both for per-entity queries. Watch for hot keys whatever you pick, and rebalance by moving whole partitions.

    Scene: Four partitions on the hash ring take 400 writes per second keyed by sensor. Partition 3 still owns the busiest sensor and stays saturated; the others have spare capacity.

    Key idea: Pick the partitioning scheme from your queries and key distribution; no scheme fixes a single hot key.