Partitioning & Storage

Split 20,000 users over four nodes. Ranges of user ID send every new user to one node. A hash ring with virtual nodes spreads them, and when a fifth node joins it moves about 20% of the keys, where hash mod N moves 80%.

Pick a scheme and watch where new users land. Then add or remove a node and count the keys that move. Then we build, piece by piece, ranges, hashing, the ring, rebalancing, hot keys, secondary indexes, the storage engine inside each node, and erasure-coded blobs.

You need what a hash function is and what a key-value store is. Caching & CDNs helps. We build the rest from zero.

Spread users over nodes

Simulated live in your browser on 20,000 stored user IDs and the next 400 new IDs, with a 32-bit hash. Blue bars are each node's share of new writes; purple bars its share of stored keys. Chapters 1 to 4 work each number.

Chapter 0

The Single-Node Wall

Count how many machines your writes and your data need

Your database stores 500 million user profiles of 2 KB each. That is 500,000,000 × 2,000 bytes = 1012 bytes, or 1 TB. This lesson uses decimal units: 1 GB = 109 bytes. Your server has 256 GB of memory, so most reads go to disk.

The writes hurt too. The app needs 40,000 writes a second, and one server handles about 10,000. Replication (keeping full copies on several nodes) adds read capacity, but every copy must apply every write. It does not add write capacity.

The fix is to split the data. Each node holds a subset of the keys and takes the writes for that subset. This is partitioning, also called sharding; each subset is a partition. A rule, the partition key, decides which partition owns each record.

How many partitions? Call the write rate the app needs W and the rate one node can take w. Call the total data D and the data one node should hold d. You need enough partitions for whichever limit is tighter.

Say it aloud

P equals the ceiling of the larger of W over w, and D over d.

P
P the smallest number of partitions that fits the load.
⌈ ⌉
the ceiling of round up to the next whole number. You cannot run 3.9 nodes.
max
the larger of take whichever of the two ratios is bigger.
W
W the writes per second the app needs: 40,000 here.
w
small w the writes per second one node can take: 10,000 here.
D
D the total data, in GB: 1,000 here.
d
small d the data one node should hold, in GB: 256 here, so it fits in memory.
In plain words

Divide the needed write rate W by one node's rate w. Divide the data D by one node's share d. Take the larger result and round it up. That is P.

With numbers

W / w = 40,000 / 10,000 = 4. D / d = 1,000 / 256 = 3.9. The larger is 4, so P = 4 partitions. Writes set the count here, by a small margin.

Count the nodes you need

Each box is one node. The blue bar is its share of the writes against 10,000 a second; the purple bar is its data against 256 GB. Drag the two loads.

40,000
1,000 GB

Illustrative capacities: 10,000 writes a second and 256 GB of memory per node, an even split, and no headroom. Real clusters keep spare capacity.

This count assumes an even split. The rest of the lesson is about keeping it even: when keys arrive in order, when nodes join, and when one key gets most of the traffic.

Failure. Symptom: you add read replicas and write latency does not move. Measure: writes per second on the primary against its limit. Cause: every replica applies every write, so replicas add read capacity only. Fix: partition the writes by key.

  1. Range partitioning: fast range scans, and a hot spot when keys arrive in order.
  2. Hash partitioning: an even spread, and why mod N moves most keys.
  3. The hash ring: move about 1 in N + 1 keys, and even it out with virtual nodes.
  4. Rebalancing: fixed partitions, splits, and the hours data takes to move.
  5. Hot keys: one key no hash can split, and salting.
  6. Secondary indexes: local or global, and the cost of asking every partition.
  7. Inside a partition: the LSM tree, the B-tree, and write amplification.
  8. Blob storage: extents and erasure coding.
  9. Showcase: a cluster you can grow and break.
  10. The field guide: numbers, choices, code and links.
One node takes 10,000 writes a second. The app needs 40,000, and the data is small. What is the fewest number of partitions?

Chapter 1

Split by Ranges of the Key

Give each node a slice of the key order, and watch ordered keys pile onto one slice

The simplest rule: sort the keys and cut the order into slices. Take user IDs from 0 to 99,999 and four partitions. Partition 0 owns 0 to 24,999, partition 1 owns 25,000 to 49,999, and so on. This is range partitioning. A router keeps the list of boundaries and sends each key to its slice.

Ranges make scans cheap. A query for IDs 24,000 to 26,000 touches two partitions, not four. Bigtable (Chang and others, 2006) and HBase store rows in key order and split them into ranges they call tablets or regions. Bigtable splits a tablet when it grows past about 100 to 200 MB.

Ranges have one weakness. If keys arrive in order, every new key lands in the last slice. Auto-increment IDs and timestamps do this. One node takes all the writes while three sit idle. That node is a hot spot.

We measure it with skew. Call the load on the busiest partition Lmax and the mean load over all partitions L̄.

Say it aloud

Skew equals L-max divided by L-bar.

skew
skew how many times the fair share the busiest partition carries. 1 is perfect; N means one partition takes everything.
Lmax
L-max the writes (or keys) on the busiest partition.
L̄
L-bar the mean over all partitions: the total divided by the number of partitions.
In plain words

Find the busiest partition's load L-max. Divide the total load by the partition count to get L-bar. Divide the first by the second. The cluster runs out of capacity when its busiest node does, so skew tells you how much of the cluster you can use.

With numbers

100 new users with IDs 100,000 to 100,099 go to four range partitions. All 100 land on partition 3: L-max = 100, L-bar = 100 / 4 = 25, skew = 4.0. The cluster writes as fast as one node.

Write into four ranges

Each column is one range partition. Blue dots are writes on their way; the purple bar counts the writes each partition took. Pick a key pattern and write 100 rows.

Simulated in your browser. Boundaries at 25,000, 50,000 and 75,000; the last partition owns every ID above 75,000. Random IDs are uniform over 0 to 99,999.

The prefix fix puts a small number in front of the key: (ID mod 4, ID). Writes now spread over four slices. The price: a scan over an ID range must now ask all four slices and merge the results.

Failure. Symptom: one region server runs at 100% CPU while the rest idle. Measure: writes per second per partition. Cause: the row key starts with a timestamp, so all new rows share the last range. Fix: lead the key with something that spreads, such as a sensor ID or a small hash prefix, and keep the timestamp second.

Four range partitions on an auto-increment user ID. 100 new users sign up each second. Where do their writes go?

Chapter 2

Hash the Key First

Scramble the keys so ordered input spreads evenly, then see what mod N does when a node joins

A good hash function turns a key into a number that looks random. IDs 100,000 and 100,001 get unrelated hashes. If you partition by the hash, ordered keys spread evenly. This is hash partitioning. Cassandra hashes the partition key with Murmur3; DynamoDB hashes its partition key too.

The price is range scans. Neighbouring keys now live on different nodes, so "IDs 24,000 to 26,000" must ask every partition. Cassandra keeps one middle path: a compound key. It hashes only the first part and keeps the rest sorted inside the partition.

The obvious way to pick a node is the remainder: partition = hash(key) mod N, for N nodes. It spreads well. It fails when N changes.

Why? A key stays put only if its hash gives the same remainder for N and for N + 1. Take hashes from 0 to N(N + 1) − 1: only the N smallest give the same remainder both times. So 1 in N + 1 keys stay, and the rest move.

Call the node count before the change N.

Say it aloud

Moved-mod equals N divided by N plus one.

movedmod
moved-mod the share of keys whose node changes when one node joins a hash-mod-N cluster.
N
N the number of nodes before the new one joins.
N + 1
N plus one the number of nodes after. Only 1 key in N + 1 keeps its remainder.
In plain words

Count the nodes N before the change. One key in N + 1 keeps its node. All the others move, so the moved share is N over N + 1.

With numbers

N = 4: 4 / 5 = 80% of keys move to add one node. N = 8: 8 / 9 = 88.9%. On 1 TB, adding a fifth node copies 800 GB, when the new node needs only 200 GB.

Add a node under mod N

Each column is a node and each purple dot a key in it. Press the button: blue dots are keys that move to another node. Then change N and try again.

4

Simulated: the dots are 120 sample keys; the read-out counts 20,000 keys with the same 32-bit hash.

Failure. Symptom: you add one cache or database node and the backend falls over. Measure: keys moved, or cache misses, in the minutes after the change. Cause: hash mod N reassigned about N / (N + 1) of all keys at once. Fix: a hash ring (Chapter 3) or fixed partitions (Chapter 4).

You partition with hash(key) mod 8 and add a ninth node. About what share of keys moves?

Chapter 3

The Hash Ring and Virtual Nodes

Move only the keys the new node needs, then even out the arcs with many points per node

Consistent hashing (Karger and others, 1997) bends the hash range into a circle. Each node hashes its name to a point on the circle. Each key hashes to a point too, and belongs to the first node point clockwise from it.

When a node joins, it takes only the keys between its point and the point before it. With N nodes owning equal arcs on average, the new node takes its fair share of N + 1.

Say it aloud

Moved-ring equals one divided by N plus one.

movedring
moved-ring the expected share of keys that move when one node joins a ring. All of them move to the new node.
1
one one new node's share.
N + 1
N plus one the node count after the join.
In plain words

The new node takes one fair share, 1 over N + 1 of the keys. No key moves between old nodes. It is an average: one node's arc can be larger or smaller.

With numbers

10 nodes and 10,000 keys, add an eleventh: 10,000 / 11 = 909 keys move. Mod N would move 10,000 × 10 / 11 = 9,091.

One point per node gives lumpy arcs. Dynamo (DeCandia and others, 2007) fixed this with virtual nodes: each node takes V points, so its share is the sum of V small arcs. Call its share's spread σ and the fair share μ.

Say it aloud

Sigma over mu is about one over the square root of V.

σ
sigma the standard deviation of one node's share: how far it typically lands from fair.
μ
mu the fair share, 1 / N of the ring.
≈
is about close to, for more than a few nodes.
1
one the spread with one point per node: about one whole fair share.
√V
the square root of V V is the number of points (virtual nodes) per node.
In plain words

Each node's share is a sum of V random arcs. Adding V random pieces shrinks the relative spread by the square root of V. So to halve the spread, use four times as many virtual nodes.

With numbers

V = 1: σ / μ ≈ 1. V = 16: 1 / 4 = 0.25. V = 256: 1 / 16 = 0.0625. The exact value for 10 nodes, √((N − 1) / (NV + 1)), gives 0.90, 0.24 and 0.059, and 4,000 random rings in our check script agree.

Turn the ring

Orange ticks are node points; purple dots are keys. The bars show each node's share of the ring against the fair line. Raise the virtual nodes, then add a node: blue keys moved.

1

Simulated: node points from a 32-bit hash of the node and point number; 20,000 keys counted, 160 drawn. One fixed set of hashes, so the lumps you see are one real draw, not an average.

Virtual nodes buy a second thing. A joining node takes many small arcs from many nodes, so the copy load spreads. The cost is metadata: V points per node in every router. Cassandra's default num_tokens is now 16 per node, with a token allocator that places them for balance.

Failure. Symptom: one node in a 4-node ring fills its disk first. Measure: each node's share of the token ring. Cause: one point per node, so arcs differ by twice or more. Fix: more virtual nodes, or a token allocator that places points on purpose.

A ring has 10 nodes and 10,000 keys. You add an eleventh node. About how many keys move, and where?

Chapter 4

Move Whole Partitions

Cut the data into many more partitions than nodes, then move partitions instead of keys

Rebalancing moves data so each node holds a fair share again, while the cluster serves traffic. DDIA (Kleppmann, chapter 6) lists three ways to do it.

  1. Fixed partitions. Hash keys into P partitions, with P much larger than the node count. A new node steals whole partitions. Keys never change partition, so the cluster rehashes nothing. Riak, Elasticsearch and Couchbase work this way; Redis Cluster's 16,384 slots are the same idea.
  2. Dynamic splitting. Split a range partition when it grows too large, like a B-tree page. HBase and Bigtable do this. An empty table starts as one partition, so early writes all hit one node.
  3. Partitions per node. Each node owns a fixed number of ranges, and a joining node splits some. Cassandra's tokens work this way.

Steal partitions

Each column is a node; each purple tile one partition. Add a node: the blue tiles are partitions that moved. Try 12 partitions, then 1,024.

Simulated: the new node takes partitions one at a time from the node with the most. The time assumes 10 TB in the cluster, equal partitions, and copies throttled to 100 MB/s in total (illustrative).

The worked number. 1,024 partitions on 4 nodes, 256 each. A fifth node wants 1,024 / 5 = 204.8, so it takes 51 from each node: 204 partitions, 19.9% of the data. The old nodes keep 205 each.

That data has to travel. Call the cluster's data D, the node count after the join N + 1, and the copy rate the operator allows B:

t = D / (N + 1) / B = 10 TB / 5 / 100 MB/s = 2,000,000 MB / 100 MB/s = 20,000 s, about 5.6 hours

The throttle protects live traffic, so a rebalance takes hours.

Too few partitions leave lumps. With 12 partitions on 5 nodes, two nodes hold 3 and three hold 2: skew = 3 / 2.4 = 1.25. With a 13th node, one node holds nothing. Choose P well above the largest cluster you expect, but each partition costs routing metadata.

Failure. Symptom: latency rises for hours after you add a node. Measure: copy bandwidth against client traffic on the donor nodes. Cause: rebalancing reads and sends a fifth of the data at full speed. Fix: throttle the copy, and add capacity before you need it.

100 fixed partitions on 5 nodes, 20 each. A sixth node joins. What does it get?

Chapter 5

One Key No Hash Can Split

Salt a hot key into k keys, and pay for it with k reads

Hashing spreads many keys. It cannot spread one. Every write to the same key hashes to the same partition. A celebrity's post, a viral product, a global counter: one key can carry more writes than one partition can take.

The limits are real. A DynamoDB partition serves at most 1,000 write units a second (one unit is one write of up to 1 KB). A key that gets 5,000 writes a second is five times over, and more partitions do not change that.

The fix is salting (AWS calls it write sharding): append a suffix from 0 to k − 1 to the hot key, chosen at random on each write. The k new keys hash to different partitions. Call the hot key's write rate Rhot and the number of suffixes k.

Say it aloud

L-part equals R-hot divided by k.

Lpart
L-part the hot key's writes per second that land on each partition after salting.
Rhot
R-hot the writes per second to the one hot key.
k
k the number of suffixes, so the number of keys the hot key becomes.
In plain words

Split the hot key's write rate R-hot evenly over k salted keys. If each lands on its own partition, each takes R-hot over k. Two suffixes that hash to the same partition put double on it.

With numbers

R-hot = 5,000 writes a second, k = 10: L-part = 500 per partition, under the 1,000 limit. But each read of that key must now fetch all 10 salted keys and merge them.

Salt the hot key

Each bar is one of 32 partitions. Purple is the steady load from other keys; blue is the hot key's share. Red marks load over the dashed limit. Raise the hot rate, then add salts.

5,000
1

Illustrative: 32 partitions, 300 writes a second each from other keys, a 1,000 writes a second limit as on a DynamoDB partition. A real hash places the salted keys, so two salts can share a partition.

Salts hash like any key, so two can share a partition. Here 8 salts land on 8 partitions and all fit; at 10 salts two share one, and it goes over. Leave margin in k.

Salt only the keys that need it. Every reader must know which keys carry salts, and a read costs k requests. DDIA notes that systems rarely do this for you; the app must track which keys are hot.

Failure. Symptom: throttling errors on one key while the table is far below its total capacity. Measure: per-key traffic, from a sampled access log or a hot-key metric. Cause: one key's rate exceeds one partition's limit. Fix: salt that key, or cache its reads in front of the store.

A key gets 3,000 writes a second, and a partition takes 1,000. You salt it with k = 4. What do you gain and pay?

Chapter 6

Find Rows by Something Else

Ask every partition with a local index, or one partition with a global index

You partition users by user ID. Now you want every user in London. City is a secondary index: a lookup by a field that is not the partition key. There are two ways to partition it.

A local index lives in each partition and covers only that partition's rows. A write updates one partition. A query by city must ask every partition and merge the answers. This is scatter/gather. DDIA lists MongoDB, Cassandra, Elasticsearch and Riak as users.

A global index takes its partitions from the indexed value. All "London" entries live in one index partition. A query asks that one partition. A write may now touch two partitions: the row's and the index entry's. DynamoDB updates its global secondary indexes asynchronously, so a read of the index can miss a write made a moment ago.

Scatter/gather has a hidden cost. The query waits for its slowest partition. Call the chance that one partition replies slowly p and the number of partitions asked n.

Say it aloud

P-slow equals one minus, one minus p, to the n.

Pslow
P-slow the chance the whole query is slow, because at least one partition was.
1 − p
one minus p the chance one partition replies fast. p is its chance of a slow reply: 1% here.
n
to the n multiplied by itself n times, once per partition asked: all must be fast.
In plain words

The query is fast only if all n partitions are fast. Multiply the chance of fast, 1 − p, n times. Subtract from 1 to get the chance that something was slow.

With numbers

p = 0.01, n = 100: 0.99100 = 0.366, so P-slow = 63%. A partition that is slow 1 time in 100 makes most scatter/gather queries slow. With a global index, n = 1 and P-slow = 1%.

Scatter, then gather

The coordinator sends blue queries to partitions; teal replies come back, pink ones late. Pick the index type and the partition count, then run 1,000 queries.

100

Illustrative: each partition replies in 10 ms, or in 200 ms with chance 1%, independently. We assume the global index holds the fields the query needs, so it asks one partition.

Failure. Symptom: the 99th percentile of search latency grows each time you add partitions. Measure: latency by number of partitions asked. Cause: scatter/gather waits for the slowest of n. Fix: a global index for hot lookups, or hedged requests to replicas of slow partitions.

100 partitions, a local index on city. How many partitions does a query by city ask?

Chapter 7

Inside One Partition

Follow a write into an LSM tree and count every byte it costs the disk

Each partition is a small database. Its storage engine decides how bytes reach the disk.

A B-tree keeps keys sorted in fixed pages, often 4 KB, and updates a page in place. With 500 keys per page, four levels reach 5004 × 4 KB = 256 TB, so a lookup reads about four pages. Postgres and MySQL's InnoDB use B-trees.

An LSM tree (O'Neil and others, 1996) never updates in place. A write goes to a log on disk (the WAL, for crash recovery) and to a sorted table in memory, the memtable. When the memtable fills, the engine writes it out as an immutable sorted file, an SSTable. Background compaction merges files into larger levels, each about 10 times the last. Bigtable, Cassandra and RocksDB use LSM trees.

Both write more bytes than the app sends. Call the bytes the disk writes Bdisk and the bytes the app writes Bapp.

Say it aloud

W-A equals B-disk divided by B-app.

WA
W-A the write amplification: disk bytes per app byte.
Bdisk
B-disk every byte written to disk: log, pages or files, and compaction rewrites.
Bapp
B-app the bytes of data the app asked to write.
In plain words

Add up every byte the engine writes to disk for a workload, B-disk. Divide by the bytes the app wrote, B-app. Disk bandwidth and SSD wear scale with WA.

With numbers

B-tree: a random 100-byte update rewrites a 4,096-byte page and logs 100 bytes, so WA = 4,196 / 100 = 42 if each update flushes its own page. LSM: the device below measures 13.6 after 1,000 MB of new keys.

Fill an LSM tree

Writes fill the memtable, flush to level 0 files, and compactions merge them down. Each purple bar is a level against its target size. Write 100 MB at a time, or 1,000 at once.

Simulated in MB: a 4 MB memtable, compaction after 4 level-0 files, level 1 at 16 MB, each level 10 times the last (RocksDB's default ratio), new unique keys only. Moving one file down rewrites the overlapping part of the next level. A toy, scaled down from real sizes.

Read the trade. An LSM write is sequential and batched, so it suits write-heavy partitions. A lookup may check the memtable, every level-0 file and one file per level. A Bloom filter per file answers "surely not here" for most of them: at 10 bits per key it lets through about 1% of misses (RocksDB wiki). With levels 10 times apart, about 90% of the data sits in the last level, which bounds the space old versions waste.

Failure. Symptom: write latency spikes, and the engine reports a write stall. Measure: pending compaction bytes and level-0 file count. Cause: compaction falls behind the write rate, so level 0 fills up. Fix: more compaction threads, faster disks, or fewer writes per partition.

An app writes 1,000 MB, and the engine writes 13,600 MB to disk. What is the write amplification?

Chapter 8

Store Blobs in Extents

Pack objects into large files, then trade three copies for erasure codes

Photos, videos and backups are blobs: opaque byte strings from kilobytes to terabytes. A blob store partitions by object name, like any key-value store, but it stores the bytes differently.

Windows Azure Storage (Calder and others, 2011) has three layers. A stateless front end checks the request and finds the partition. The partition layer maps each name to a place: (extent, offset, length). The stream layer stores extents, append-only files of about 1 GB, each written to three nodes. A delete marks the bytes dead; a background job reclaims them later.

Three copies cost 3 bytes of disk per byte of data. A sealed extent can be erasure coded instead: cut into k data fragments, add m parity fragments, and store all n = k + m on different nodes. Any k of them rebuild the data. Call the total fragments n and the data fragments k.

Say it aloud

Overhead equals n divided by k.

overhead
overhead bytes of disk per byte of data.
n
n the fragments stored: data plus parity. The scheme survives the loss of any n − k.
k
k the data fragments, and the number needed to rebuild.
In plain words

Count all the fragments you store, n. Divide by the data fragments k. The difference n − k is how many nodes can fail before data is lost.

With numbers

Three copies: n = 3, k = 1, overhead 3, survives 2 losses. HDFS's default RS-6-3: n = 9, k = 6, overhead 1.5, survives 3. For 1 PB of data, that is 1.5 PB of disk instead of 3 PB.

Fail the fragment holders

Each box is a node holding one purple fragment. Tap a box to fail it, or use the button. The data stays readable while k fragments survive.

Illustrative 1 GB extent. RS-6-3 is HDFS's default erasure coding policy; Facebook's f4 warm blob store used RS-10-4. Repair reads assume plain Reed-Solomon.

Erasure codes save disk and cost repair work. To rebuild one lost fragment, a node reads k others: 6 for RS-6-3, against one copy for replication. So hot, young data stays replicated, and sealed, cooler extents get coded.

Failure. Symptom: network traffic between racks jumps after a disk dies. Measure: repair bytes read per byte rebuilt. Cause: each lost fragment needs k fragments read from other nodes. Fix: spread repairs over time, and keep hot data replicated.

A blob store uses RS-6-3 (6 data, 3 parity). Two nodes fail. Can it read the data?

Chapter 9

A Cluster You Can Grow and Break

Choose a scheme and a workload, grow the cluster, and read the skew and the moved keys

The hero's cluster, with every knob from Chapters 1 to 5. Pick a scheme and a workload. Add or remove nodes. Each node shows its share of stored keys and of the next 2,000 writes, and the line under the chart reports what the last change moved.

Run the cluster

Purple bars: share of the 20,000 stored keys. Blue bars: share of the next 2,000 writes; red where a node takes over 1.5 times its fair share. Change anything, then add a node.

16

Simulated in your browser with the same engine as the hero: 20,000 stored IDs, a 32-bit hash, 2 to 10 nodes. Range adds a node by splitting the fullest range at its median, the last one on a tie.

Things to try:

  1. Range with new users. One node takes every write. Add a node: the last range splits, and the new node takes every write instead.
  2. Hash mod N, add a node: about 80% of keys move. Same with the ring: about 20%.
  3. Ring with 1 virtual node: storage skew near 1.6. Slide to 256: near 1.06.
  4. Celebrity on any hash scheme: one node takes about 47% of writes, nearly twice its fair share. Salt it 8 ways: the write skew falls from about 1.9 to between 1.2 and 1.3.

The worked number: ring with 64 virtual nodes, 4 nodes, then a fifth. The simulation moves 19.7% of 20,000 keys, all to the new node; the formula 1 / (N + 1) predicts 20%. The same step under mod N moves 79.9%, against a predicted 80%.

Failure. Symptom: after a capacity add, one node is still the bottleneck. Measure: write skew per node before and after. Cause: the load was a hot key or ordered keys, which more nodes do not split. Fix: change the key (prefix or salt), not the node count.

A ring cluster is balanced in storage, but one node takes 30% of writes. What most likely causes it?

Chapter 10

The Field Guide

Keep the numbers, the choices and the code for the next dataset you split

Partition when writes or data outgrow one node. Ranges keep scans cheap and turn ordered keys into a hot spot. Hashing spreads keys, and a ring or fixed partitions keep a join from moving most of them. Virtual nodes and many partitions even out the shares.

No scheme splits one hot key, so salt it. Secondary indexes cost reads when local and writes when global. Inside each partition, the engine trades write amplification for read cost, and blob stores trade disk for repair work.

Terms and numbers

TermWhat it isThis lesson's number
Partitions neededP = ⌈max(W / w, D / d)⌉40,000 writes/s, 1,000 GB: 4
SkewLmax / L̄ordered IDs on 4 ranges: 4.0
Mod N joinmoved = N / (N + 1)4 to 5 nodes: 80%
Ring joinmoved = 1 / (N + 1)10 to 11 nodes: 909 of 10,000
Virtual nodesσ / μ ≈ 1 / √VV = 256: about 6%
Rebalance timet = D / (N + 1) / B10 TB, 5 nodes, 100 MB/s: 5.6 h
SaltingLpart = Rhot / k5,000 / 10 = 500 writes/s
Scatter/gatherPslow = 1 − (1 − p)np 1%, n 100: 63%
Write amplificationWA = Bdisk / BappB-tree 42; LSM toy 13.6
Erasure codingoverhead = n / kRS-6-3: 1.5, survives 3

Which scheme for which workload

WorkloadSchemeExamples
Point lookups by keyhash: ring, or fixed partitionsDynamo, Cassandra, DynamoDB, Redis Cluster
Range scans, time seriesrange, with split on size or loadBigtable, HBase, Spanner
Search over many fieldshash plus local indexes, scatter/gatherElasticsearch
Large objectshash on name, extents, erasure codingAzure Storage, HDFS, f4

Corrections to common figures

Checklist

  1. Pick the partition key from the most common query, and check that it spreads writes.
  2. Never use hash mod N for a cluster that changes size.
  3. Create many more partitions than nodes, or many virtual nodes per node.
  4. Watch skew per node for both storage and writes.
  5. Find hot keys from traffic, and salt or cache them.
  6. Use a global index only where read speed is worth stale index reads.
  7. Throttle rebalancing, and add capacity before the disks fill.

The core as code

python# a hash ring with virtual nodes, and the keys a join moves (sketch)
import bisect, hashlib

def h(s):                                    # a 32-bit position on the ring
    return int.from_bytes(hashlib.md5(s.encode()).digest()[:4], "big")

class Ring:
    def __init__(self, nodes, v=64):
        self.v, self.pts = v, []                 # sorted (position, node)
        for n in nodes: self.add(n)

    def add(self, node):                      # V points per node: sigma/mu ~ 1/sqrt(V)
        for i in range(self.v):
            bisect.insort(self.pts, (h(f"{node}#{i}"), node))

    def owner(self, key):                    # first node point clockwise
        i = bisect.bisect_left(self.pts, (h(key), ""))
        return self.pts[i % len(self.pts)][1]

keys = [f"user{i}" for i in range(20000)]
r = Ring(["A", "B", "C", "D"])
before = {k: r.owner(k) for k in keys}
r.add("E")
moved = sum(before[k] != r.owner(k) for k in keys)
print(moved / len(keys))                     # about 1/5; every moved key now lives on E
modn = sum(h(k) % 4 != h(k) % 5 for k in keys)
print(modn / len(keys))                      # about 4/5 under hash mod N

Keep going

The takeaway. Choose the partition key from your queries, then check that it spreads writes. Hash it onto a ring with virtual nodes or into many fixed partitions, so growing the cluster moves only a fair share. Then find the one key no hash can split.

Now press Present or Teach and explain five things from memory. Explain why ordered keys make a hot spot under ranges. Explain why mod N moves 4 keys in 5 and a ring moves 1 in 5. Explain why virtual nodes even out the shares by the square root of V. Explain why a local index makes most queries slow at 100 partitions. Then go back to the hero, switch to Range, and add a node.

Partitioning & Storage
Dynamo 2007 · Bigtable 2006 · DDIA · Back to Gleams