Sharding

Split a team chat app's messages over 8 machines. Hash each message ID and every machine takes an even share, but reading one channel asks 5.7 machines. Shard by workspace and a channel read asks one machine, but the machine with the biggest workspace carries 2.2 times its share. The shard key decides which you get.

Pick a shard key and read a channel. Then we build each part from zero: tenants, ranges that split, hash shards, hot keys, rebalancing, routing, secondary indexes and replica placement.

You need a little Python and what a database key is. We build the rest from zero.

Choose the shard key

Illustrative and seeded: 500 workspaces and 20 channels each, both with a long-tailed (Zipf) activity; 20,000 messages of history, then 2,000 new writes counted per machine. A channel read fetches the channel's last 50 messages; the average is over 1,000 reads.

Chapter 0

Too Big for One Machine

Split the data over machines, and count the operations that now need two of them

A team chat service keeps every message in one database. It holds 4 TB and takes 30,000 writes a second at peak. With made-up limits, one server holds 2 TB and takes 10,000 writes a second. Read replicas do not help: each one holds all 4 TB and applies every write.

Sharding splits the data so that each machine holds a part. Each part is a shard. A rule called the shard key decides which shard owns each record. MongoDB and Elasticsearch say shard. Cassandra says partition, HBase region, Bigtable tablet and CockroachDB range. With 4 shards, each holds 1 TB and takes 7,500 writes a second.

Sharding has a price: an operation on records in two shards must coordinate two machines. Posting a message touches three records: the message, the channel's summary row and the poster's counter. Where do they land?

Count one-shard operations

Each row is one operation; each dot is a record it touches, placed in its shard's column. Green rows stay on one shard; pink rows must coordinate. Pick a placement, then move the sliders.

3
8

Illustrative and seeded: 10,000 operations per setting. "Shared row" means one record, such as a user directory entry, lives outside the workspace.

If the system places each record by its own hash, how often do all of an operation's records share a shard? Call the number of shards N and the records one operation touches k. Call the chance that all k land on one shard Pone.

Say it aloud

P-one equals one over N, to the power k minus one.

Pone
P-one the chance that one operation touches only one shard.
1/N
one over N the chance that a record lands on one given shard, with N shards: 8 here.
k − 1
to the power k minus one multiply 1/N by itself once for each record after the first. k is 3 here.
In plain words

The first record lands somewhere. Each of the other k − 1 records must land on that same shard, with chance 1/N each. Multiply those chances to get P-one.

With numbers

N = 8 and k = 3: P-one = (1/8)2 = 1/64 = 1.6%. Our 10,000 seeded operations gave 1.4%. Shard all three records by workspace and P-one is 100%; add one shared row and it falls to 1/8 = 12.5%.

The shard key decides which records live together. This lesson follows Chapter 7 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). We explain its ideas in our own words, with our own examples and simulations. Chapter 6 copied the data; this chapter splits it. Partitioning & Storage simulates the mechanics: ranges, the hash ring, data movement. We link to it and focus on the choices.

Failure. Symptom: after sharding, write latency doubles and some writes half-apply. Measure: the share of operations that touch more than one shard. Cause: a shard key that scatters records one operation needs together. Fix: shard by the key that groups them, such as the workspace.

  1. Tenants: one customer per shard, and the customer too big for one.
  2. Ranges: key ranges that split as they grow, and pre-splitting.
  3. Fixed shards: hash first, then pick a shard count you can grow into.
  4. Skew: one hot key no hash can spread.
  5. Rebalance: who decides to move data, and the timeout trade.
  6. Routing: how a request finds its shard.
  7. Indexes: local or global secondary indexes.
  8. Replicas: copies of every shard, placed apart.
  9. The showcase: shard the chat app with every knob (the hero, extended).
  10. The field guide: numbers, checklist, code and links.
With 8 shards and records placed at random, how often does an operation on 3 records stay on one shard?

Chapter 1

One Tenant per Shard

Shard by customer, pack the small ones together, and split the one that does not fit

A business app serves many customers, and each customer's data is separate. Each customer is a tenant: a company, a team, a chat workspace. Sharding by tenant puts all of one tenant's data on one shard.

That buys four things:

The cost is the size of tenants: a few are huge and most are tiny. Systems pack many tiny tenants into one shard, but a huge one can outgrow a whole shard. A query across all tenants, such as a usage report, asks every shard.

How big is the biggest tenant? A common model is a long tail: the tenant ranked i has a size proportional to 1/i. This is the Zipf pattern. Call the number of tenants T. Call the biggest tenant's share of all data s1.

Say it aloud

s-one equals one over H-T, where H-T is one plus a half plus a third, and so on up to one over T.

s1
s-one the biggest tenant's share of all the data.
HT
H-T the harmonic number: the sum of every tenant's size, measured in units of the biggest tenant.
1 + 1/2 + …
one plus a half plus a third tenant 2 is half as big as tenant 1, tenant 3 a third, and so on.
T
T the number of tenants: 200 here.
In plain words

Measure every tenant against the biggest one: 1, a half, a third, down to 1/T. Add those up to get H-T. The biggest tenant holds 1 of those H-T parts, so its share s-one is 1 over H-T.

With numbers

With made-up numbers: T = 200 gives H-T = 5.878, so s-one = 17.0%. On 10 shards the fair share is 10%. The biggest tenant alone needs 1.7 shards, whatever you do with the rest.

Place 200 tenants

Each column is a shard; each purple block is a tenant, the biggest at the bottom. The dashed line is a shard's capacity, 1.5 times the fair share. Pick a placement and change the shard count.

10

Illustrative: 200 tenants with Zipf sizes (exponent 1). Packing places the biggest first onto the emptiest shard. Splitting cuts a tenant above 0.8 of a shard's capacity into pieces of at most 0.6 of it, on different shards.

Packing beats hashing, which can drop two big tenants on one shard. But at 10 shards, packing still leaves the biggest tenant at 17% against a 15% capacity. The fix is a second key inside the big tenant, such as (tenant, channel): its pieces go to different shards, and its queries ask several.

Failure. Symptom: one enterprise customer's requests time out while the other shards idle. Measure: data and requests per tenant against one shard's capacity. Cause: a tenant bigger than a shard. Fix: give big tenants a second-level key, or a group of shards of their own.

Tenant sizes follow 1/i over 200 tenants. You grow from 10 shards to 20. What happens to the biggest tenant?

Chapter 2

Ranges That Split as They Grow

Let the data choose the boundaries, and pre-split a new table so its first writes spread

Key range sharding gives each shard a continuous range of keys, like the volumes of an encyclopedia: A to C, D to F. A key's shard is the range it falls in. A range scan, such as every user from "Kim" to "Lee", asks only the shards that cover it.

Ranges have a well-known trap: keys that arrive in order, such as timestamps, all land in the last range. Split by Ranges of the Key shows that hot spot. Here is the other question: where do the boundaries go?

Even spacing fails, because far more surnames start with S than with X. So systems let the data choose. When a range grows past a size limit, the system splits it at its middle key into two ranges. HBase and Bigtable work this way. CockroachDB splits a range at 512 MiB by default. Spanner adds and removes split boundaries based on size and on load.

Splitting starts from one range. In MongoDB, ranged sharding of an empty collection creates one empty chunk that covers every key. Until the first splits, every write goes to one machine. The fix is to pre-split: create several ranges up front, with boundaries taken from a sample of real keys.

Split ranges as names arrive

The strip is the alphabet; each purple segment is one range, labelled with its machine. The bars show each machine's share of the writes so far. Scrub through the 4,000 writes, then turn on pre-splitting.

500

Illustrative and seeded: first letters drawn from made-up weights (S and M common, Q and X rare). A range splits at its median key past 250 names; the new half goes to the machine holding the fewest names. Pre-splitting cuts at the quartiles of the same weights.

The worked number. Without pre-splitting, machine A takes 73% of the first 500 writes; the other three take what splits hand them. With four ranges cut at the quartiles, the busiest machine takes 28%. After 4,000 names the two runs have 22 and 24 ranges, each holding 125 to 250 names. A split leaves two halves of about 125, and a half splits again past 250.

The same arithmetic sizes a real table. With CockroachDB's 512 MiB limit, a 1 TiB table that only grows ends up with between 2,048 and 4,096 ranges.

Failure. Symptom: a bulk import into a new table runs one machine at 100% CPU for its first hour. Measure: writes per machine per minute during the import. Cause: one empty range, split only as it fills. Fix: pre-split from a sample of the keys you will load.

Why do range-sharded systems split at the middle key of the data, not the middle of the alphabet?

Chapter 3

Hash First, Then Pick the Count

Hash keys into more shards than machines, and see what the count costs as the cluster grows

Hash sharding runs each key through a hash function first. Neighbouring keys get unrelated hashes, so ordered keys spread evenly. The price: a range scan over the key now asks every shard.

The obvious rule, shard = hash(key) mod N machines, moves most keys when N changes: 80% when a fifth machine joins four. Hash the Key First measures it. Systems avoid it in three ways:

You must choose a fixed count early. Call the number of shards P and the number of machines N. Some machines get one more shard than others. Call the busiest machine's load divided by the mean the skew.

Say it aloud

Skew equals the ceiling of P over N, divided by P over N.

skew
skew how many times the fair share the busiest machine carries. 1 is perfect.
⌈P/N⌉
the ceiling of P over N P shards divided by N machines, rounded up: the shards on the busiest machine.
P/N
P over N the mean shards per machine, a fraction if N does not divide P.
In plain words

Divide the P shards by the N machines and round up: that is the busiest machine's count. Divide it by the unrounded mean P over N. When N passes P, some machines hold nothing.

With numbers

P = 256: at N = 10, skew = 26 / 25.6 = 1.02. At N = 100, 3 / 2.56 = 1.17. At N = 200, 2 / 1.28 = 1.56. Past 256 machines, the extra ones sit idle.

Grow a cluster on fixed shards

The curve is the skew as the cluster grows; the dot is your cluster. Below, machines grouped by how many shards they hold. Pick a shard count and drag the machines.

100

Computed from the formula. Shard size assumes 50 TB in the cluster and copies at 100 MB/s (decimal units, illustrative).

Too few shards also makes each one big. With 50 TB in 16 shards, one shard is 3.1 TB and takes 8.7 hours to move at 100 MB/s. In 256 shards, a shard is 195 GB and moves in 33 minutes. Each shard costs metadata and overhead, so pick P for the largest cluster you expect.

Failure. Symptom: you grow a search cluster from 8 to 40 machines and queries get no faster. Measure: shards per machine for the busy index. Cause: the index has 8 primary shards, so 32 machines hold none of it. Fix: split the index to a multiple of 8, or choose hash ranges that split.

64 fixed shards on 50 machines. What is the skew?

Chapter 4

One Hot Key Stays Hot

Add shards against a popular key and watch the busiest shard get worse, not better

Hashing spreads keys. It cannot spread requests to one key: every request for that key goes to the same shard. A celebrity's account, a viral channel and a global counter are all one key.

Skew is the busiest shard's load divided by the mean load. A shard with skew 2 runs out of capacity when the cluster is half used. A shard that carries much more than the others is a hot spot.

Popularity is often long-tailed, like tenant size in Chapter 1. Then the top key carries a fixed share of all requests, whatever the shard count. Call the top key's share p1 and the number of shards N. If every other key spread evenly, call the skew of the top key's shard S.

Say it aloud

S equals N times p-one, plus one minus p-one.

S
S the hot shard's load divided by the mean load, if the other keys spread evenly.
N
N the number of shards.
p1
p-one the top key's share of all requests: 10.2% here.
1 − p1
one minus p-one the rest of the requests; the hot shard gets 1/N of them.
In plain words

The hot shard carries the top key's share p-one, plus 1/N of the rest. The mean shard carries 1/N. Divide the first by the second: N times p-one, plus one minus p-one. S grows with N.

With numbers

With made-up numbers: 10,000 keys with Zipf popularity give p-one = 1/9.79 = 10.2%. At N = 10, S = 1.02 + 0.90 = 1.92. At N = 100, S = 11.1. Our 100,000 seeded requests measured 1.71 and 10.8, because the other keys are lumpy too.

Add shards against a hot key

Bars are shards, busiest first; the dashed line is the fair share and red bars carry over 1.5 times it. Raise the tail, then add shards.

1.0
10

Illustrative and seeded: 100,000 requests over 10,000 keys, each key hashed to a shard. Exponent 0 is uniform popularity. The chart shows up to 40 bars.

No shard count fixes a hot key. Three things do:

Failure. Symptom: throttling errors on one partition while the table uses a fifth of its capacity. Measure: requests per key, from a sampled access log. Cause: one key above one partition's limit. Fix: cache or split that key; more partitions do not help.

One key gets 10% of all requests. The other keys spread evenly over 20 shards. What is the hot shard's skew?

Chapter 5

Who Decides to Move Data

Let a timeout declare machines dead, and count the terabytes it moves for nothing

Rebalancing moves shards between machines: when one joins, when one leaves, when one dies. Move Whole Partitions counts the shards that move and the hours the copy takes. This chapter asks who presses the button.

Fully automatic rebalancing is convenient. It is also dangerous when it trusts automatic failure detection. A machine pauses, because of overload or garbage collection. Its heartbeats stop for a while. The system declares it dead and copies its shards to the others. The copying loads the other machines, so they slow down, and more of them look dead.

The middle way: the system proposes a plan, and an operator approves it. That is slower when a machine truly dies. How much does the automatic way move for nothing?

Say pauses come at r per hour across the cluster, and their length averages m seconds, with long pauses rare (an exponential spread). A pause longer than the timeout τ (tau) looks like a death. Each false death moves one machine's data: the cluster's data D over the machine count N. Call the data moved for nothing each day M.

Say it aloud

M equals twenty-four times r times e to the minus tau over m, times D over N.

M
M data copied each day because the system declared a paused machine dead, in TB.
24
twenty-four hours in a day.
r
r pauses per hour across the cluster: 4 here.
e−τ/m
e to the minus tau over m the chance one pause outlasts the timeout τ, when lengths are exponential with mean m = 4 s.
D/N
D over N one machine's data: 20 TB over 10 machines, 2 TB.
In plain words

Count the pauses in a day, 24 times r. Multiply by the chance that one outlasts tau, e to the minus tau over m. Each such pause copies one machine's data, D over N.

With numbers

With made-up numbers: at τ = 10 s, 96 × e−2.5 = 7.9 false deaths a day, so M = 15.8 TB a day. At τ = 30 s, 0.053 a day, one every 19 days, and 0.11 TB a day. Our seeded 30 days gave 237 and 4 false deaths.

Set the dead-machine timeout

Top: 30 days of pauses, by length; a pause above the yellow timeout triggers a move (red). Bottom: the data moved, piling up. Drag the timeout, then make an operator approve moves.

10 s

Illustrative and seeded: 2,880 pauses (4 an hour for 30 days), exponential lengths averaging 4 s; 2 TB per machine. With approval, a real death waits for an operator, 30 minutes here.

Approval removes the false moves and costs response time: a machine that truly dies leaves its shards one copy short until someone acts. Replication (Chapter 8) is what makes that wait safe.

Failure. Symptom: every night during the backup, the cluster copies terabytes and latency climbs. Measure: machine pause lengths against the dead-machine timeout. Cause: a timeout below the long pauses, with automatic moves. Fix: raise the timeout, throttle copies, and approve large moves by hand.

Pauses come 4 an hour, average 4 s, and each false death moves 2 TB. Why does raising the timeout from 10 s to 30 s cut moved data about 150 times?

Chapter 6

Find the Right Shard

Send a request to any machine, a router, or straight to the owner, and count the hops

A client holds a key. Which machine owns its shard? The answer changes whenever a shard moves. There are three designs:

  1. Ask any machine. The client picks a machine; if it does not own the shard, it forwards the request. In Cassandra a coordinator node hashes the key to find the owners.
  2. A routing tier. The client talks to a router that knows the shard map. MongoDB's mongos caches the shard map from config servers and routes each operation.
  3. A shard-aware client. The client library keeps the map and connects to the owner.

All three need a correct map. Many systems keep the authoritative map in a coordination service such as ZooKeeper or etcd, which tells watchers when it changes. Others let nodes spread the map to each other by gossip; Cassandra's gossip teaches nodes which endpoints own what data. Either way, a cached map goes stale for a moment after a move, and a request reaches the old owner. The old owner must forward it or answer with the new owner.

How many network hops does each design take? Call the number of machines N. With "ask any machine", call the mean hops per request h.

Say it aloud

h equals two minus one over N.

h
h the mean network hops from the client to the owner, asking a random machine first.
2
two one hop to the chosen machine, one more to forward.
1/N
one over N the chance the first machine is the owner, so it does not forward.
In plain words

Every request takes one hop to some machine. It takes a second hop unless that machine is the owner, which happens 1 time in N. So the mean is 2 minus 1 over N.

With numbers

N = 10: h = 2 − 0.1 = 1.9 hops; our 1,000 seeded requests took 1.89. A router always takes 2. A shard-aware client takes 1, and 1.12 in the minute after one of 10 shards moves.

Route 24 requests

Blue lines are requests from the client on the left; a bend is a forward. Pick a design, change the machine count, then move a shard.

10

Illustrative and seeded: each machine owns one shard; 1,000 requests to random shards. After a move, a client's cached map, or half of the machines' gossiped maps, still name the old owner, which forwards. The router learns the move from the coordination service.

Hops are not the only cost. A router is one more service to run, though routers hold no data and you can run several. A shard-aware client is the fastest and the most complex to write. Asking any machine needs nothing extra but adds a hop most of the time.

Failure. Symptom: a burst of "wrong shard" errors after every rebalance. Measure: redirects per second against shard moves. Cause: clients cache the map and do not refresh it. Fix: return the new owner with the error, and refresh the cache on it.

20 machines; the client sends each request to a random machine, which forwards if needed. Mean hops?

Chapter 7

Local or Global Index

Make reads ask every shard or make writes touch two, and find the read share where they cost the same

The chat app shards messages by workspace. Now a user wants every message by one author, which needs a secondary index: a lookup by a field that is not the shard key. There are two ways to build it.

A local index lives in each shard and covers only that shard's rows. A write updates one shard. A lookup by author must ask every shard and merge the answers: scatter/gather. Cassandra builds its secondary indexes locally on each node. Each Elasticsearch shard holds its own index, so a search goes to every shard unless a routing value names one. Find Rows by Something Else shows the tail-latency cost.

A global index takes its shards from the indexed value: all entries for one author live in one index shard. A lookup asks that one shard. A write now touches the row's shard and an index shard, often on another machine. DynamoDB updates its global secondary indexes asynchronously: changes usually arrive within a fraction of a second, so an index read can miss a fresh write.

Which costs fewer requests? Call the shard count N, the share of operations that are lookups by the index r, and the indexed fields each write updates f. Count requests per operation:

local: (1 − r) · 1 + r · N    global: (1 − r) · (1 + f) + r · 1

Set the two equal and solve for the lookup share where they tie, r*.

Say it aloud

r-star equals f over f plus N minus one.

r*
r-star the share of index lookups at which both designs cost the same requests. Above it, global wins.
f
f index entries a write updates: the extra requests a global index adds to each write. 2 here.
N − 1
N minus one the extra requests a local index adds to each lookup: N shards instead of 1.
In plain words

A global index adds f requests to every write. A local index adds N − 1 requests to every lookup. They tie when the lookups' extra cost equals the writes' extra cost, at a lookup share of f over f plus N minus 1.

With numbers

With made-up numbers: N = 10 and f = 2 give r* = 2/11 = 18%. At r = 30%, local costs 0.7 + 3.0 = 3.7 requests per operation and global 2.1 + 0.3 = 2.4. Our 10,000 seeded operations gave 3.70 and 2.40.

Count requests per operation

Two lines: requests per operation as the lookup share grows, local (purple) and global (teal). The dot is your workload. Drag the sliders.

30%
10
2

Illustrative and seeded: 10,000 operations per setting. We assume a lookup needs only the index entry; fetching full rows would add requests to the global side.

Failure. Symptom: a user posts a message, searches for it at once, and it is missing. Measure: the lag between a row write and its index entry. Cause: a global index updated asynchronously. Fix: show the user's own fresh writes from the primary data, as read-your-writes did in Chapter 6.

20 shards, one indexed field (f = 1). Above what lookup share does a global index cost fewer requests?

Chapter 8

Every Shard Needs Copies

Replicate each shard, then lose a whole rack and see which placement keeps every shard

Sharding and replication run together. The system copies each shard to several machines with the methods of Chapter 6. One machine holds copies of many shards: it leads some and follows others.

With made-up numbers: 1,000 shards, 3 copies each, on 12 machines. Each machine holds 1,000 × 3 / 12 = 250 copies and leads about 83 shards. When one machine dies, only the shards it led elect new leaders. The rest carry on.

Copies of one shard must sit on different machines, and better on different racks or zones: a rack shares power and a network switch. Placement that ignores racks can put all copies of a shard in one rack. How likely is that?

Say a rack holds n machines, the cluster has N, and each shard has R copies on R different machines, chosen at random. Call the chance that all R copies of one shard sit in one given rack q.

Say it aloud

q equals n choose R, over N choose R.

q
q the chance that one shard has every copy inside one given rack, so losing that rack loses the shard.
C(n, R)
n choose R the ways to pick R machines inside the rack of n. "a choose b" counts the ways to pick b of a.
C(N, R)
N choose R the ways to pick R machines anywhere in the cluster of N.
In plain words

Count the sets of R machines that fit inside the rack. Divide by all sets of R machines. That share of shards dies with the rack.

With numbers

With made-up numbers: 9 machines in 3 racks of 3, and R = 3. q = 1/84 = 1.19%. With 24 shards, a rack failure loses at least one shard 1 − (83/84)24 = 25% of the time; 10,000 seeded placements gave 25.1%. With 1,000 shards, it loses about 12.

Lose a machine, then a rack

Each box is a machine in its rack; each small square a shard copy, filled for the leader. Pick a placement, then fail one machine or a whole rack.

Illustrative and seeded: 24 shards, 3 copies each; the first copy listed leads. "New placement" draws the next seed.

Failure. Symptom: a power cut in one rack makes some shards unreadable, though every shard had 3 copies. Measure: shards whose copies share a rack or zone. Cause: placement that spreads copies over machines only. Fix: rack-aware or zone-aware placement.

9 machines in 3 racks of 3, three copies per shard, placed one per rack. A rack loses power. How many shards are lost?

Chapter 9

Shard the Chat App

Choose a key, a shard count and an index, then let one channel go viral

Back to the hero's chat app, with every knob from the lesson. 500 workspaces with 20 channels each, 20,000 messages of history and 2,000 new ones. Four questions: how even are new writes? How many shards does a channel read ask? How many does a workspace export ask? What does a search by author cost?

Shard a chat app

Bars are shards' shares of new writes; red bars carry over 1.5 times the fair share. The table scores the four questions. Change anything.

Illustrative and seeded, same engine as the hero. Viral: 30% of the new writes go to one channel of a mid-sized workspace. "Big ones split" hashes (workspace, channel) for workspaces above a quarter of a shard's fair share, and the workspace alone for the rest. Export is averaged over all workspaces.

At 8 shards. Hashing the message ID is even (skew 1.08) but a channel read asks 5.7 shards and an export 6.5. Time ranges send every new write to the last shard: skew 8. Hashing the workspace makes reads and exports ask 1 shard, but the biggest workspace pushes the skew to 2.2.

Workspace plus channel brings the skew to 1.30 and keeps channel reads on 1 shard, but an export asks 5.2. Splitting only the big workspaces gives skew 1.46 with exports on 1.05 shards: most of both worlds. Grow to 32 shards and the hashed workspace's skew climbs to 5.4, as Chapter 4 predicts.

Now let a channel go viral. Message ID hashing does not notice. Every key that keeps a channel together puts its 30% on one shard: skew 2.9 to 3.2 at 8 shards. The fix is the hot-key toolkit of Chapter 4, not a new shard key. A local author index makes each search ask every shard; a global one asks 1 and adds one index write per message.

Failure. Symptom: a shard key that tested well puts one machine at 100% when one big customer joins. Measure: write skew per shard, with your largest tenant and a viral channel replayed. Cause: tests with even, small tenants. Fix: test the key against your real size distribution, and plan the split for the big ones.

Chapter 10

The Field Guide

Keep the numbers, the rules and the code for the next database you shard

Sharding splits data and writes over machines, and the shard key decides which records live together. Tenants and ranges keep related data together but grow unevenly; hashing spreads keys but not hot keys. A fixed shard count must cover the largest cluster you expect. Rebalancing needs a guard against false deaths and routing needs a fresh map. A secondary index is local or global, and each shard needs copies placed apart.

Terms and numbers

IdeaRuleThis lesson's number
One-shard operationsPone = (1/N)k − 18 shards, 3 records: 1.6%; grouped by workspace: 100%
Biggest tenants1 = 1 / HT200 tenants: 17.0%, 1.7 shards out of 10
Range splitssplit at the median key past a size limitearly writes on one machine: 73%; pre-split: 28%
Fixed shard skew⌈P/N⌉ / (P/N)256 shards: 1.02 at 10 machines, 1.56 at 200
Hot key skewS = N · p1 + (1 − p1)p1 10.2%: 1.92 at 10 shards, 11.1 at 100
False rebalancingM = 24 · r · e−τ/m · D/Nτ 10 s: 15.8 TB a day; 30 s: 0.11 TB
Routing hopsh = 2 − 1/N10 machines: 1.9; router 2; shard-aware client 1
Index break-evenr* = f / (f + N − 1)10 shards, 2 fields: 18% lookups
Rack lossq = C(n, R) / C(N, R)3 racks of 3, R 3: 1/84 per shard; rack-aware: 0

Checklist

  1. Shard only when one machine cannot hold the data or the writes; replicas handle reads.
  2. Pick the shard key from your most frequent operations, so each touches one shard.
  3. With tenants, pack small ones together and give big ones a second-level key.
  4. With key ranges, pre-split new tables from a sample of real keys.
  5. With a fixed shard count, size it for the largest cluster you expect.
  6. Find hot keys from access logs; cache them or split them.
  7. Keep large data moves behind a long timeout or an operator's approval.
  8. Make the old owner of a moved shard forward or redirect, and refresh caches.
  9. Choose local or global indexes from the lookup share; expect a global index to lag.
  10. Place each shard's copies on different racks or zones.

The core as code

pythonfrom math import ceil, comb, exp

def one_shard(n_shards, k):            # records placed at random
    return (1 / n_shards) ** (k - 1)

def biggest_tenant(t):                  # Zipf sizes 1, 1/2, ..., 1/t
    return 1 / sum(1 / i for i in range(1, t + 1))

def fixed_skew(p, n):                    # p fixed shards on n machines
    return ceil(p / n) / (p / n) if n <= p else n / p

def hot_skew(p1, n):                      # the top key's shard, the rest even
    return n * p1 + (1 - p1)

def index_break_even(n, f):
    return f / (f + n - 1)

def rack_loss(n_rack, n, r):
    return comb(n_rack, r) / comb(n, r)

print(round(one_shard(8, 3), 4), round(biggest_tenant(200), 3))   # 0.0156 0.17
print(fixed_skew(256, 200), round(hot_skew(0.102, 10), 2))     # 1.5625 1.92
print(round(index_break_even(10, 2), 3), round(rack_loss(3, 9, 3), 4))  # 0.182 0.0119

Keep going

The takeaway. A shard key decides which records live together. Put together what your queries read together, then measure the skew your biggest tenant and your hottest key will cause.

Now press Present or Teach and explain four things from memory. Why does a random placement make most multi-record operations cross shards? Why does the biggest tenant not fit better on more shards? When does a global index beat a local one? Why can a short timeout move terabytes for nothing? Then go back to the hero and find the key that keeps channel reads on one shard with the lowest skew.

Data Sharding · following Designing Data-Intensive Applications, 2nd edition, Chapter 7
Previous: Replication · Next: Transactions · Back to Gleams