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.
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
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?
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.
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.
P-one equals one over N, to the power k minus one.
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.
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.
Chapter 1
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.
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.
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 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.
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.
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.
Chapter 2
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.
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.
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.
Chapter 3
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:
hash(_routing) % num_primary_shards. You set the count when you create the index; to grow it, the split API builds a new index with a multiple of the count.-80 and 80-. MongoDB's hashed sharding starts an empty collection with two chunks per shard.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.
Skew equals the ceiling of P over N, divided by P over N.
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.
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.
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.
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.
Chapter 4
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.
S equals N times p-one, plus one minus p-one.
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 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.
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.
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.
Chapter 5
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.
M equals twenty-four times r times e to the minus tau over m, times D over N.
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 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.
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.
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.
Chapter 6
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:
mongos caches the shard map from config servers and routes each operation.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.
h equals two minus one over N.
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.
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.
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.
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.
Chapter 7
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*.
r-star equals f over f plus N minus one.
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 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.
Two lines: requests per operation as the lookup share grows, local (purple) and global (teal). The dot is your workload. Drag the sliders.
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.
Chapter 8
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.
q equals n choose R, over N choose R.
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 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.
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.
Chapter 9
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?
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
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.
| Idea | Rule | This lesson's number |
|---|---|---|
| One-shard operations | Pone = (1/N)k − 1 | 8 shards, 3 records: 1.6%; grouped by workspace: 100% |
| Biggest tenant | s1 = 1 / HT | 200 tenants: 17.0%, 1.7 shards out of 10 |
| Range splits | split at the median key past a size limit | early 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 skew | S = N · p1 + (1 − p1) | p1 10.2%: 1.92 at 10 shards, 11.1 at 100 |
| False rebalancing | M = 24 · r · e−τ/m · D/N | τ 10 s: 15.8 TB a day; 30 s: 0.11 TB |
| Routing hops | h = 2 − 1/N | 10 machines: 1.9; router 2; shard-aware client 1 |
| Index break-even | r* = f / (f + N − 1) | 10 shards, 2 fields: 18% lookups |
| Rack loss | q = C(n, R) / C(N, R) | 3 racks of 3, R 3: 1/84 per shard; rack-aware: 0 |
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
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.