AlgoViz

Partitioning strategies

medium 25 min

Range, hash and list partitioning are three rules for placing rows.

Video lesson · Chapter 1 of 5

The first number across the fence

0:00 / 3:14

Theory

Read or listen first. About 2 min.

What it is

A partitioning strategy is the rule that turns a key into a partition. Three rules cover most systems. Range places keys by intervals, hash places them by a computed number, and list places them by a table of values.

A list whose table is stored as data and can change at any time is also called a directory or lookup strategy.

Rules can be stacked. For example, a hash of the tenant chooses the shard, and a range of months chooses the part inside it.

Why it exists

No rule is best for everything. A rule that keeps neighbours together makes range questions cheap, and it also sends neighbouring writes to the same place. A rule that scatters neighbours does the opposite.

The rule is also hard to change later, because every row has been placed by it. So it is worth an hour of thought about the queries before the first row is stored.

A short history

  1. 1983

    Teradata delivers the first shared-nothing database system, with the data divided over nodes.

  2. 1997

    Karger and colleagues introduce consistent hashing, a hash rule that moves little when nodes change.

  3. 2006

    Google's Bigtable paper describes tables split into row ranges called tablets.

  4. 2017

    PostgreSQL 10 adds declarative partitioning.

  5. 2018

    PostgreSQL 11 adds partitioning by hash, and a default partition for values that match no other.

Words to know

Range
A partition owns all keys between two bounds.
Hash function
A fixed calculation that turns a key into a number that looks random.
Modulo
The remainder of a division: 42 mod 3 is 0.
List or directory
A table that says which value belongs to which partition.
Point lookup
Reading one row by its exact key.
Range query
Reading all rows between two keys.
Locality
Rows that are used together live together.
Hot spot
A partition that gets far more work than the others.

How it works

Step through the idea, or press Play.

Step 1 of 3

Take the key. For example user_id, a date or a region

Understand it

Start here

Seeds in three beds

Asha has nine packets of seeds and three garden beds. There are several ways to decide which seed goes where, and each makes one kind of search easy.

Nine packets, three beds
BED 1BED 2BED 3BEANCHIVEDAISYKALEMINTPEAROSESAGETULIP9 packets, 3 beds

The same choice appears with a box of toys: by size, by a number computed from each toy, or by kind, with cars here and dolls there.

The idea

Three rules side by side

  • Range

    By intervals: 0 to 999, 1000 to 1999, 2000 and up.

  • Hash

    By a computed number: hash of the key, modulo N.

  • List

    By a table you write: US is 0, EU is 1.

Where does 42 go, with three shards?

RuleCalculationShard
Range42 is between 0 and 9990
Hash42 mod 3 = 00
Range, key 1500between 1000 and 19991
Hash, key 15011501 mod 3 = 11
List, region EUthe table says 11
The plain remainder stands in for a hash here, so you can check it in your head.

Range

Range partitioning

Each partition owns an interval of the key: dates, numbers or letters. Intervals must touch without overlapping. The usual habit is to include the lower bound and exclude the upper.

Orders of 2024 by date

ShardFromUp to, not including
02024-01-012024-05-01
12024-05-012024-09-01
22024-09-012025-01-01
January to April, May to August, September to December.

Ids 900 to 1100 with a range rule

A range query for ids 900 to 1100 reaches a router with a range rule. Shard 0 holds 0 to 999 and shard 1 holds 1000 to 1999, and both are asked. Shard 2 holds 2000 and up and is skipped.
Two shards answer and one is skipped.

Range is good at

  • Range queries touch few partitions
  • Easy to understand and to build
  • Natural for time-series data
  • Old ranges can be dropped whole

Range is bad at

  • A hot spot on the newest range when keys only grow
  • Ranges can be uneven in size
  • Splits and moves are needed as data grows

A range can be split at any key, and systems such as MongoDB and CockroachDB do that by themselves. That makes growing easier than with modulo, not harder. How splits work is in advanced partitioning.

Hash

Hash partitioning

The rule

shard=hash⁡(key) mod N42 mod 3=0,43 mod 3=1\text{shard} = \operatorname{hash}(\text{key}) \bmod N \qquad 42 \bmod 3 = 0,\quad 43 \bmod 3 = 1
Neighbours 42 and 43 land on different shards. That is the point, and also the price.

user_id mod 3

ShardIds
00, 3, 6, 9 ...
11, 4, 7, 10 ...
22, 5, 8, 11 ...

Ids 900 to 1100 with a hash rule

The same range query for ids 900 to 1100 reaches a router with a hash rule. The matching ids are scattered, so shard 0, shard 1 and shard 2 are all asked.
All three shards are asked, because neighbours were scattered.

Hash is good at

  • An even number of keys per shard
  • Finding the shard in constant time
  • Simple code, nothing to store
  • Keys that only grow are spread out

Hash is bad at

  • Range queries ask all shards
  • Adding shards with modulo moves most keys
  • Neighbours lose each other
  • One very busy key is still one busy shard

Choosing a hash

  1. 1

    Stable

    The same result on every server, in every version of your program, for years.

  2. 2

    Well spread

    MurmurHash, xxHash and CRC32 are common choices. A cryptographic hash also works and is slower.

  3. 3

    Not negative

    A remainder of a negative number is negative in Java, Go and JavaScript. In Java even Math.abs of the smallest int is negative. Use Math.floorMod.

  4. 4

    Not modulo the machines

    Use fixed slots or consistent hashing, so that growth moves a fair share only.

List

List and directory partitioning

A table says where each value lives. If the table is part of the schema, it is a list. If it is kept in a service and can change while you run, it is a directory.

A directory of regions

A client's request with region EU reaches the router. The router keeps a cached copy of the map from the directory, which says US is 0, EU is 1, and ASIA and LATAM are 2. It sends the request to shard 1. Shard 0 holds US and shard 2 holds ASIA and LATAM.
LATAM shares a shard with ASIA today. One changed line, plus a move of its rows, can give it a shard of its own.

List is good at

  • Full control over placement
  • New values are one more line
  • Locality by business: a region, a large customer
  • Moving one value without touching others

List is bad at

  • Somebody must maintain the table
  • Uneven if values differ in size
  • A directory asked on every request can become a bottleneck
  • Unknown values need an answer

A lookup that does not overload the directory

The map is small, so each router keeps all of it. The directory is asked for changes, not for requests.

Compare

The three rules in one table

RangeHashList
Spread of keysCan be unevenEvenAs you decide
Range queriesFew partitionsAll partitionsDepends on the values
Finding the partitionBinary search, O(log p)O(1)O(1) in a map
Hot spotsLikely with growing keysOnly from hot keysPossible
Adding capacitySplit a rangeModulo: most keys; slots: a fair shareMove one value
Typical useTime seriesUser dataRegions, tenants
p is the number of partitions. Inside the shard, the row itself is still found by an index.

Range search is not slow

log⁡21024=10 comparisons for 1024 ranges\log_2 1024 = 10 \ \text{comparisons for } 1024 \text{ ranges}
Finding the range costs next to nothing compared with one network call.

Decide

A short guide

Which rule?

Owner means a user, a tenant or a device.
  1. 1

    Need range queries?

    Use range.

  2. 2

    Need an even spread?

    Use hash.

  3. 3

    Need a place by geography or contract?

    Use a list.

  4. 4

    Need two of these?

    Combine them.

Together

Two rules at once

Messages are read as the newest 50 of one channel. Hash the channel to choose the shard, and keep rows sorted by time inside it. The channel's messages are together, and channels are spread out.

Hash outside, range inside

Cassandra, DynamoDB and others build this in: a partition key to choose the place, and a sort or clustering key for the order inside.

Very long partitions are cut by adding a time bucket to the first part, such as channel and month. Discord described this for its messages, with a bucket of about 10 days.

SQL
-- Hash, then range, in PostgreSQLCREATE TABLE events (  tenant_id  bigint,  created_at date,  body       text) PARTITION BY HASH (tenant_id);CREATE TABLE events_0 PARTITION OF events  FOR VALUES WITH (MODULUS 4, REMAINDER 0)  PARTITION BY RANGE (created_at);CREATE TABLE events_0_2026 PARTITION OF events_0  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');-- ListCREATE TABLE users (id bigint, region text) PARTITION BY LIST (region);CREATE TABLE users_eu PARTITION OF users FOR VALUES IN ('EU');CREATE TABLE users_rest PARTITION OF users DEFAULT;
PostgreSQL supports range, list and hash, and partitions of partitions.

Second questions

Queries on another field

Users are sharded by id, and somebody searches by city. Two kinds of secondary index exist.

Local indexGlobal index
StoredOn each shard, for its own rowsOn its own shards, by city
Read by cityAsk every shardOne index shard, then the rows
WriteOne shardTwo places to update
FreshnessWith the rowOften a little behind
DynamoDB has both. Its global secondary indexes are updated after the write, so reads from them are eventually consistent.

Choosing an index

The last choice makes each write a cross-shard transaction, so use it rarely.

Worked example

A school bus tracker

Assume 20,000 buses that report a position every 10 seconds. The main query is the route of one bus today. The second is the last position of all buses of one school.

The load

20,00010 s=2,000 writes/s\frac{20{,}000}{10\ \text{s}} = 2{,}000\ \text{writes/s}
Reports are steady while buses drive, so this is already the busy rate.
  1. 1

    Range by time

    All 2,000 writes a second hit today's partition. Rejected for shards.

  2. 2

    Hash by bus

    Writes are even, and one bus's day is one sorted read. Chosen.

  3. 3

    Days inside each shard

    Local ranges by day, so old days can be dropped.

  4. 4

    Second query

    A small table with the last position, keyed by school and bus, sharded by school.

Moving on: what to do when a partition gets too large or too hot is in advanced partitioning, and routing on real clusters is in sharding.

Summary

The whole topic in one minute.

Range keeps order: good for intervals and time, with a risk of a hot end. Hash spreads keys evenly: good for single lookups, bad for intervals. A list gives control: good for regions and large tenants, with a table to look after.

Start from the question you ask most. If it is an interval, look at range. If it is a single key, look at hash. If law or a customer decides the place, use a list. Combine two rules when one is not enough.

  • Range keeps neighbours together, hash spreads them, a list puts them where you say.
  • Range queries: few partitions with range, all with hash.
  • A hash spreads keys, not the traffic of one busy key.
  • Use a stable hash, never a negative remainder, and fixed slots instead of modulo machines.
  • Hash the owner, then sort by time: the most useful combination.

Sources