Search

Search papers and lessons

Data Partitioning

Level 2 · 12 min read

Data partitioning splits one large collection of records into pieces on different machines, so each request touches only the machine that holds its piece.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Algorithms
  • Distributed systems
  • ReadReady to readNot yet

TL;DR

Data partitioning splits one large collection of records into smaller pieces, called partitions or shards, and places each piece on a different machine. A request then touches only the machine that holds its piece, so the system can store and serve more data than any single machine can handle. The hard part is the rule that maps each record to its piece.

Builds on: Hash Function, Modular Arithmetic · Leads to: Consistent Hashing, Distributed Hash Table, Quorum

Where it's used

A user table in a large service. Suppose a service has 500 million accounts at about 1 kilobyte each. That is 500 gigabytes, more than one database server should hold while also serving reads. Splitting the table into 50 partitions by user ID gives each partition about 10 million accounts, or about 10 gigabytes. A request for one user goes to one partition.

Amazon's Dynamo key-value store. The 2007 Dynamo paper describes a store spread over a ring of many nodes. Each key is hashed to a position on the ring, and the node that owns that arc of the ring stores the key. Virtual nodes spread the arcs evenly across machines. This is partitioning with a hash rule that survives machines joining and leaving.

Kafka topics. A Kafka topic is split into partitions, and each partition is an ordered log on one broker. The producer hashes each record's key to choose the partition. All events for one customer therefore land in the same partition, and their order is kept, while different customers are spread across the partitions.

How it works

Take a table of eight records with IDs 1 to 8, and three machines. The rule is: partition = ID mod 3, which is the remainder after dividing by 3. Machine 0 holds the IDs whose remainder is 0, machine 1 the remainder 1, machine 2 the remainder 2.

  1. Write record 7. Divide 7 by 3. It is 2 with remainder 1, since 7 = 2 × 3 + 1. The partition is 1, so the record goes to machine 1. Check: machine 1 now holds records 1, 4 and 7, because 1, 4 and 7 all leave remainder 1.
  2. Read record 5. Divide 5 by 3. It is 1 with remainder 2, since 5 = 1 × 3 + 2. The partition is 2, so only machine 2 is asked. Check: machines 0 and 1 are never contacted, and the read cost is one machine.
  3. Read all records with ID above 5. The matching IDs are 6, 7 and 8, and they sit on machines 0, 1 and 2 respectively. Every machine must be asked, and the answers are merged. Check: this query costs three machines, not one. Partitioning by a key helps point lookups and hurts queries that scan a range across keys.
  4. Add a fourth machine. The rule becomes ID mod 4. Compare the two rules for each ID: 1 (1 and 1), 2 (2 and 2), 3 (0 and 3), 4 (1 and 0), 5 (2 and 1), 6 (0 and 2), 7 (1 and 3), 8 (2 and 0). Only IDs 1 and 2 keep their machine. Check: six of eight records must move, which is 75 percent.

Step 4 is the problem the rest of this lesson is about. Changing the number of partitions moves most of the data, and that is expensive.

flowchart LR
  R[Record with key k] --> F[Partition rule: h of k, mod N]
  F -->|0| M0[Machine 0]
  F -->|1| M1[Machine 1]
  F -->|2| M2[Machine 2]

The math

Definition: Partition
A partition is a subset of the records, chosen by a partition function pp. Given a partition key kk for each record, the partition function sends kk to one of NN partitions, numbered 00 to N−1N - 1. Every record belongs to exactly one partition.

Step 1 in symbols: the rule

Let hh be a Hash Function that turns a key into a whole number. The rule is

p(k)=h(k) mod Np(k) = h(k) \bmod N

so p(k)p(k) is the partition index. For the tiny example in the walkthrough, take hh as the identity, so h(7)=7h(7) = 7. Then p(7)=7 mod 3=1p(7) = 7 \bmod 3 = 1, which matches step 1.

Step 2 in symbols: a read by key

A read for key kk computes p(k)p(k) and asks only that partition. The other N−1N - 1 machines are not contacted, which is why a read costs one machine however large the cluster grows.

Step 3 in symbols: the cost of a query

If a query asks for a single key kk, it touches exactly one partition, p(k)p(k). If a query asks for a set of keys SS that spreads over mm partitions, it touches mm partitions. For a range query over many keys, mm is usually all NN. So the cost of a query grows with the number of partitions it touches, not with the number of records it returns.

Step 4 in symbols: how much moves when N changes

Compare the rule with NN partitions and the rule with N+1N + 1. A key kk stays put exactly when

k mod N=k mod (N+1).k \bmod N = k \bmod (N+1).

Look at the block of keys 0,1,…,N(N+1)−10, 1, \ldots, N(N+1) - 1. Suppose kk stays, and let r=k mod Nr = k \bmod N. Then k−rk - r is a multiple of NN, and it is also a multiple of N+1N + 1. Because NN and N+1N + 1 are consecutive integers, they share no factor, so k−rk - r is a multiple of N(N+1)N(N+1). Inside the block, the only such value is k−r=0k - r = 0, which means k=rk = r and k<Nk < N. So exactly the keys 0,…,N−10, \ldots, N-1 stay, which is NN keys out of N(N+1)N(N+1). The fraction that stays is

NN(N+1)=1N+1,\frac{N}{N(N+1)} = \frac{1}{N+1},

and the fraction that moves is NN+1\dfrac{N}{N+1}. With N=3N = 3 going to 44, that is 34\tfrac{3}{4}, which is the 75 percent in step 4 of the walkthrough.

Worked examples

Example
Two partitions by parity
  1. Six records have IDs 1 to 6. Use two partitions and the rule p(k)=k mod 2p(k) = k \bmod 2.
  2. Odd IDs have remainder 1, so partition 1 holds 1, 3 and 5.
  3. Even IDs have remainder 0, so partition 0 holds 2, 4 and 6.
  4. Look up ID 4. Its remainder is 0, so only partition 0 is read. The answer is found after touching one partition.
  5. Look up IDs 2 and 3 together. Their remainders are 0 and 1, so both partitions are read. The query costs two partitions.
  6. Interpretation: a lookup by one key is cheap, and a query over a mix of keys is as expensive as the number of partitions it spans.
  7. Try it: a seventh record has ID 9. Which partition holds it, and what does a query for IDs 8 and 9 touch? Answer: 9 mod 2 is 1, so partition 1 holds it. ID 8 has remainder 0, so the query touches partitions 0 and 1, which is both of them.
Example
Growing a cluster of ten partitions to eleven
  1. A table has 1,000,000 user records spread over 10 partitions by h(k) mod 10h(k) \bmod 10. Each partition holds about 100,000 records.
  2. The team adds an eleventh partition and switches to h(k) mod 11h(k) \bmod 11.
  3. By the result above, the fraction of keys that move is 1011≈0.909\dfrac{10}{11} \approx 0.909.
  4. The number of records that move is about 1,000,000×0.909≈909,0001{,}000{,}000 \times 0.909 \approx 909{,}000.
  5. Each of those records is read from its old partition and written to its new one, so almost the whole table is copied while the system is serving reads and writes.
  6. Interpretation: a plain modulo rule makes adding one partition a near-total reshuffle. This is the cost that consistent hashing was invented to avoid.
Example
Ordered events in a streaming topic
  1. An order-events topic has 12 partitions. Each event carries a customer ID, and the producer sends it to partition h(customer ID) mod 12h(\text{customer ID}) \bmod 12.
  2. Every event of one customer lands in the same partition, and a partition is read in the order it was written. So the events of one customer are read in order.
  3. The topic receives 60,000 events per second. If the keys are spread well, each partition gets about 60,000/12=5,00060{,}000 / 12 = 5{,}000 events per second.
  4. Suppose one large customer sends 20,000 events per second by itself. All of them go to one partition, which now carries 20,000 plus the share of other customers, far above 5,000.
  5. Interpretation: the ordering guarantee is paid for with a risk. A key that is much more popular than the rest overloads its partition, however many partitions there are.
  6. Try it: with 60,000 events per second over 12 partitions and one customer sending 20,000 per second, how many events per second does that customer's partition carry if the other customers' events are spread evenly over all 12 partitions? Answer: the other customers send 40,000 per second, and the customer's own partition receives 40,000 divided by 12, about 3,333, plus the customer's 20,000, about 23,333 per second.

Common mistakes and tradeoffs

It is tempting to think that more partitions always makes a system faster. In fact more partitions spreads many point lookups over more machines, but a range query or a full scan must ask every partition. More partitions can make those queries slower, since each one now waits on more machines.

It is tempting to think any field can be the partition key. In fact the key must spread the load. If one value is far more common than the rest, its partition becomes a hot spot, and hashing does not fix that, because the hash sends every copy of the same key to the same place.

It is tempting to think that partitioned data supports transactions across partitions for free. In fact a transaction that writes to two partitions needs the partitions to agree on the outcome, which takes coordination such as Two-Phase Commit. Such a transaction is slower and can fail when a machine is unreachable.

There are three common ways to choose the rule.

RuleHow records are placedGood forWeak at
Hash partitioningHash the key, then take the remainder or find the ring positionSpreading load evenly; point lookupsRange scans; adding partitions moves data
Range partitioningKeys sorted, each partition holds a contiguous rangeRange scans; ordered readsHot spots when keys are sequential, such as timestamps
Lookup tableA directory records which partition holds each keyFull control over placementEvery request reads the directory, which must itself be kept up to date

Use hash partitioning when the workload is mostly lookups by key and the data is large. Use range partitioning when range scans matter more. Avoid a plain modulo rule for a system whose number of machines will change, and use Consistent Hashing instead.

History

Partitioning is older than the web. Parallel database systems in the 1980s split tables across disks and processors, so that each one could work on a part of a query at the same time. The problem returned in the 2000s, when large web services stored data on many ordinary machines and needed a placement rule that still worked when machines were added or lost. In 1997, David Karger and colleagues at MIT introduced consistent hashing for distributed caches, which solved the reshuffling problem for changing machine counts. Amazon's Dynamo paper in 2007 described a production key-value store that partitioned its data with a ring of this kind. The idea caught on because it made the cost of growth proportional to the data that actually moves.

Recap

  • A large collection is split into partitions, and each partition lives on one machine.
  • A rule maps each record's key to a partition. A simple rule is h(k) mod Nh(k) \bmod N, built from a Hash Function and Modular Arithmetic.
  • A lookup by one key touches one partition. A query over many keys can touch all of them.
  • Changing NN with a modulo rule moves a fraction N/(N+1)N/(N+1) of the keys, which is close to all of them.
  • A hot key or a skewed key overloads one partition however the rule is chosen.

Read next: Consistent Hashing for a placement rule that moves only the keys near a change, Distributed Hash Table for a system built on that idea, and Quorum for how replicas of a partition agree on a value.

Check yourself

QuestionWhy does a lookup by one key get cheaper as the number of partitions grows, while a query for all keys above some value does not?Show answer

A lookup by one key is sent to the single partition its rule picks, so it touches one machine no matter how many there are. A range query does not name one partition, because its keys are spread across the partitions, so it must ask every partition and merge the answers. More partitions means more machines to ask.

QuestionA table is split by h(k) mod 5h(k) \bmod 5 over 5 partitions. The team moves to 6 partitions with h(k) mod 6h(k) \bmod 6. What fraction of keys move, and how many of 600,000 records is that?Show answer

The fraction is 56\dfrac{5}{6}, since the fraction that moves is N/(N+1)N/(N+1) with N=5N = 5. The count is 600,000×56=500,000600{,}000 \times \dfrac{5}{6} = 500{,}000 records. That is most of the table.

QuestionWhy can hashing the key still leave one partition overloaded?Show answer

A hash sends every copy of the same key to the same place. If one key receives a large share of the traffic, its partition receives that share no matter how evenly the other keys are spread. Hashing spreads distinct keys, not the load of a single popular key.

QuestionApplied: a service stores messages keyed by the sender's user ID and must read the last 50 messages of one user quickly. Is a hash rule on the user ID a good choice, and what would you check first?Show answer

Yes for this read pattern. The last 50 messages of one user share one key, so the query touches one partition, and the hash spreads different users across partitions. The check is skew: if a few accounts send far more messages than others, their partitions will be hot. Measure the message count per user before settling on the key.

Sources

Data Partitioning — explained simply · ungoon.me