Systemsfor Aravinda
0 / 78 core
Week 2 · Storage

Partitioning and sharding

2.5 hours · core path

Read first: Replication, Load balancing

In one sitting

Partitioning cuts the key space so one machine does not hold every byte or every write. A hash spreads keys and sends range scans to every shard, while a range keeps scans local and concentrates hot ranges. More shards do not move a hot key, and a secondary index is either local, so the read scatters, or global, so the write pays an extra path.

Partitioning exists when one machine cannot hold the bytes or the write rate. You cut the key space into pieces and send each key to one piece. Replication copies a piece so a disk can die. It does not make the piece smaller. The cut is by range or by hash, and a key hotter than the rest still lands on exactly one piece no matter how many pieces you add.

Core concepts

A partition, a shard, and a tablet are the same idea in different systems: a subset of the key space that one process owns. The process usually has its own primary and its own replicas. The hard choice is the key you cut on. Get it wrong and every request visits every shard, or one shard takes the only request that matters.

The router that sends a request to a stateless app server is a different problem. Load balancing spreads requests that any server can handle. A partition map spreads keys that only one shard can handle. Power of two choices does not move a hot key. The map does, and only if you change which shard owns that key.

Hash and range

Range partitioning slices the key in sorted order. Users A through F on one shard, G through M on the next. A range scan stays on one shard, or on a short run of neighbors. “Messages from this user in this hour” is local if the key starts with the user and then the time. The failure mode is a hot range. Time as the first component of the key puts all of the current hour on one shard. Names are uneven. A sequential id puts every insert on the shard that owns the high end, which is the rightmost page of a B-tree all over again, at cluster scale.

Hash partitioning applies a hash to the key and uses the hash to pick the shard. Adjacent keys land far apart, so one busy prefix does not cook a single range, and the shards stay even when the keys are even. The range scan dies. “Everyone’s messages in the last hour” has to ask every shard and merge. “This user’s messages in the last hour” can still be local, if you hash the user id and keep time inside the shard as a sort key. Hash the wrong field, the user and the time together as one blob, and you lose that range too.

Bigtable splits by row range. Tablets are ranges, a master assigns them, and a hot prefix sits in one tablet until the key changes. That is the range side of this choice, published. The hash side is what you reach for when the prefixes are not uniform and the query you care about is a point or a short range on a hashed key.

Hot keys

A hot key is one key whose traffic is a large fraction of a shard. Hashing does not dilute it. The hash of that key is one number, and one number is one shard. Adding shards moves other keys. It does not move this one, unless this key’s hash now falls on a boundary, which is luck, not a plan.

The published shape is a hot partition, not a mysterious slow node. Discord stored messages with a partition key of channel id plus a time bucket, so one channel’s window landed together. A hot channel made one node fall behind. Reads in that LSM store touch the memtable and possibly many files, so the writes were not the whole cost. Everything else on that node slowed down with it. The Discord’s message store page is that incident in full. Slack’s published lesson is the workspace version: do not put every channel of a large workspace on one shard. Shard messages by channel id so one big customer spreads out. Their published peak, from that writeup, was 2.3 million queries a second, about 2 million reads and 300,000 writes, median 2 ms, p99 11 ms. Those are their numbers, not a target you should invent for your own product.

What actually helps a hot key:

  • Change the key so the hot traffic splits into pieces you can read back. A time bucket spreads history across shards and does not spread a single burst. A small set of sub-keys spreads the burst, and the read fans out to that set.
  • Isolate the key on its own shard. The neighbors recover. The hot key does not get faster.
  • Cache the read. Caching takes read traffic off the shard. The writes still land on one primary.
  • More shards, with the same key, do not help. Say that sentence before you draw a bigger cluster.

Resharding

Changing the number of shards moves bytes. There is no config flag that only changes the map. Until the bytes move, the old shard is still the owner.

Modulo hashing, shard equals hash mod N, moves almost every key when N changes. The remainder for almost every key is different. You copy the dataset.

Consistent hashing, from Karger and others in 1997, places keys and nodes on a ring. Adding a node takes a share of its neighbors and leaves the rest where they were. About 1/N of the keys move, not almost all of them. Virtual nodes give one machine many small arcs so the share is even and a departure does not take one contiguous chunk of the ring. The ring itself is in Load balancing. The point here is the move: resharding is a data copy of whatever fraction your function invalidates, done while writes continue.

During the copy a key has a source and a destination. A read has to know which one is authoritative, or it has to check the new place and then the old. A write should land on one of them, not both, or you need a rule for the double write. Cut over one range at a time and you can abort one range. Cut over by changing a modulo in one step and every key is in flight together.

A range store reshard by splitting a tablet. The hot range splits into two ranges, and the master assigns the new half away. That fixes a hot range whose keys are different. It does not fix a hot key, because a single key cannot be split by a range cut. The key has to change.

Local and global secondary indexes

Inside one shard, an index is still the B-tree or the LSM from Indexes: B-trees and LSM trees. Partitioning decides where that index lives.

A local secondary index is partitioned with the rows. The shard that holds the user holds the index entries for that user. A write updates the index on the same shard, in the same transaction, cheaply. A query that is not the partition key cannot use it alone. “Every message with this campaign tag” has to ask every shard, because each shard’s index only knows its own rows, and then merge the answers. The read scatters. You wait on the slowest shard.

A global secondary index is partitioned by the indexed column, not by the row’s partition key. One shard holds every entry for one campaign tag, so the query is a single read. The write path pays for that. Updating a message also updates an index entry that lives somewhere else. That is an extra network hop, and it fails separately from the row write. If you require them to commit together, you are in a distributed transaction. If you do not, the index lags the row. Uber’s Schemaless store publishes the second choice: secondary indexes are eventually consistent. Uber Schemaless and Ringpop is the writeup, including the 4,096-shard configuration. Eventual here means the same thing it means everywhere: if the writes stop, the index converges. It does not mean the next read sees the tag you just attached.

A global index can recreate the hot key. If every message during a launch carries the same campaign id, the index shard for that id takes the whole launch. You moved the hotspot. You did not delete it.

flowchart LR
  celeb[Celebrity user id]
  hashfn[Hash picks a shard]
  hot[That shard takes every write]
  neighbors[Other keys on that shard wait]
  celeb --> hashfn --> hot --> neighbors

A worked example

An inbox is keyed by user id. The hash of the user id picks the shard. Ordinary users are fine. One celebrity is not, and you are about to propose “add shards” in an interview. Do the arithmetic first and kill that proposal with it.

Assumptions, all of them. 20 million users. 200 shards. An ordinary user receives 10 messages a day. One celebrity receives 5 million messages a day. That celebrity figure is an assumption you invented for the estimate, not a measured public figure. Peak during a broadcast is 5 times the celebrity’s average, and 5x is the top of the band you must state. A message is 400 bytes. The dataset you will reshard later is 8 TB, also an assumption.

ordinary day    20,000,000 * 10 = 200,000,000 messages
per second      200,000,000 / 86,400 = 2,314.8
shortcut        200,000,000 / 100,000 = 2,000
per shard       2,314.8 / 200 = 11.6/s if the hash is even

celebrity       5,000,000 / 86,400 = 57.9/s on one shard
versus a shard  57.9 / 11.6 = 5.0 times one average shard
peak 5x         57.9 * 5 = 289.5/s, about 25 times the average shard

neighbors       20,000,000 / 200 = 100,000 users on that shard
their traffic   about 11.6/s beside the celebrity's 57.9/s
shard total     11.6 + 57.9 = 69.5/s, against about 12/s on a quiet shard

bytes at peak   289.5 * 400 = 115,800 bytes/s, about 116 KB/s

A day is 86,400 seconds. The shortcut of 100,000 seconds would have said 2,000 a second instead of 2,315. Use the shortcut out loud, and know which way it rounded.

Read the celebrity line again. About 58 writes a second is not a scary cluster-wide number. Spread across 200 shards it would be 57.9 divided by 200, about 0.3 a second each. It is not spread. The hash of one user id is one shard, and that shard does about six times the work of a quiet one before you apply the peak. At the peak, about 290 writes a second and about 116 KB/s hit one primary. The other 199 shards cannot take a single one of those writes.

Doubling to 400 shards moves other users onto new homes. This user still hashes to exactly one shard. That shard, old or new, still takes the whole 58 a second, now with fewer neighbors beside the same celebrity. You spent a reshard to decorate the outage.

What a time bucket does and does not do. Change the partition key to user id plus a day. Tuesday’s celebrity traffic is one shard, Wednesday’s is another. History spreads. The broadcast on Tuesday afternoon does not. That day’s shard still takes the whole 58 a second, and the whole 290 at the peak. Discord’s channel-plus-time-bucket key has the same shape: a window lands together, which is what makes the read local, and a hot window is a hot partition.

What a small fanout does. Split the celebrity across 8 sub-keys, an assumption of a fanout you are willing to read. Writes fall to 58 divided by 8, about 7 a second each, and about 36 a second each at the peak. The inbox read now asks 8 shards and waits on the slowest. A fanout of 8 is a product decision you can price. A fanout of 200, which is what a local index does for a query that is not the partition key, is the decision you are trying not to make on the send path. Isolating the celebrity on a dedicated shard does not drop the 58. It takes the other 100,000 users off that disk, so when the node falls behind, the blast radius is the celebrity and not their neighbors. Discord’s pain was the shared fate: the hot partition dragged latency for everything else on the node.

The query that is not the partition key. “Inbox for this user” is one shard. “Every inbox that contains this campaign” is not. A local index answers it by asking all 200 shards. A same-datacenter round trip is 0.5 ms when the call is healthy, and you wait on the max, not the average. p99 means about 1 in 100 requests on a shard is slower than the line you drew. Across 200 independent shards you expect 200 times 0.01, which is 2 shards sitting at or past that line, on a typical scatter. The chance that every shard is faster than its own p99 is about 0.99 to the 200th. That is close to e to the minus 2, about 0.14, if the tails are independent. About one scatter in seven has nobody in that tail. The other six wait on a slow shard. Correlated stalls, a shared deploy or a shared disk, make it worse. This is why a user-facing search does not scatter to every shard of the inbox.

A global index on campaign id makes that query one shard. Each message write also writes the index, on whatever shard owns the campaign. Do that synchronously and the send path waits on a second shard, and a failure of the index write is a failure of the send unless you have a transaction across them. Do it asynchronously and the campaign view lags the inbox, which is the eventual index Uber published. If the campaign id is the launch itself, the index shard is the new celebrity. The hotspot moved with the key.

Resharding the 8 TB. You have 200 shards and you add capacity with consistent hashing. About 1/N of the keys move. Take N as 200 and the fraction as 1/200.

moved by the ring    8 TB / 200 = 0.04 TB = 40 GB
moved by new modulo  almost all of the 8 TB

Forty gigabytes is a copy you can drain, throttle, and abort. Almost 8 TB in one modulo change is a migration that touches every user, and a mistake in the cutover is a mistake for the whole product. Virtual nodes change the balance of the 40 GB, not the fact that modulo moves the rest. While the 40 GB is in flight, a read of a moving key checks the destination and then the source, or you freeze that key, copy it, and flip. You do not change N and hope.

Slack’s channel id and Discord’s channel-plus-bucket are the same lesson as the inbox. The key is the unit the product reads together, and it is also the unit that can get hot. A large workspace sharded by workspace id is the celebrity. A workspace sharded by channel id is the 8-way split, done with a key the product already has.

Tradeoffs

Choice What you keep What you pay
Range partition A range scan on one shard or a few Hot ranges, and the current slice of a time key on one shard
Hash partition An even spread when keys are even A range across keys becomes a scatter to every shard
More shards, same hot key Nothing for that key A reshard that moves everyone else and leaves the outage in place
Local secondary index A write that stays on the shard, in one transaction A query on the indexed column scatters and waits on the slowest
Global secondary index One shard answers the non-primary query An extra write path, lag if it is async, a distributed transaction if it is not
Time bucket in the key History spreads, and a window stays readable The burst inside one window is still one shard
Consistent hashing when you add a node About 1/N of the keys move Virtual nodes to balance, and a cutover for the keys that do move

The hash-versus-range row is the one to decide from the query, not from taste. If the product cannot name a key, neither row saves you. You will scatter, and the table’s last rows are how expensive that scatter is.

Pitfalls

  • Partitioning on a column the query does not have. The symptom is every request scattering to every shard, and a p99 set by the slowest one.
  • Adding shards to fix a celebrity. The symptom is a new cluster map and the same 58 writes a second on one shard, because the hash of that user did not change in a way that moves them.
  • Hashing the entire key, user and time together, when the read is a time range for one user. The symptom is a range you used to answer locally becoming a scatter.
  • Using time as the only partition key. The symptom is the current window on one shard, every user, celebrity included, writing to the rightmost range.
  • A global index on a value that is itself hot. The symptom is the campaign shard melting while the inbox shards look idle.
  • Resharding with modulo. The symptom is a copy of almost the whole dataset, and errors on the keys that moved while a request was in flight.
  • Putting every channel of a large workspace on one shard. The symptom Slack named: one customer is one disk. Shard by channel id.
  • A local index behind a user-facing search. The symptom is the fanout math above, on the order of two shards past the per-shard p99 for every scatter of 200, when the tails are independent.
  • Splitting a tablet by range and expecting a single hot key to split with it. The symptom is a tablet of one key that no range cut will divide.

In the interview

Name the partition key in the first five minutes, and name it from the read. “The inbox is hashed by user id, so a user’s page is one shard. A range across users is not a query I will serve from this store.” Then the celebrity, with a number. At 5 million messages a day one user is about 58 writes a second on one shard, against about 12 a second for an even shard at this assumption, and about 290 a second at a 5x peak I state as an assumption. More shards do not move that key. A small fanout does, and the read pays it. Isolation stops the neighbors from paying it.

Skip the consistent-hashing proof. One sentence: adding a node moves about 1/N of the keys, modulo moves almost all of them, and on an 8 TB set that is 40 GB versus the dataset. Skip multi-region. If they want the campaign query, that is the deep dive you already prepared: local index scatters and waits on the max, global index adds a write and can lag, and a hot campaign id is a hot key with a new name.

The question that usually follows is “how do you query by the other column?” Answer with the two indexes and one choice. Say which one you picked and what broke. The question after that is the reshard. Answer with the fraction of bytes that move, and where a read goes while a key is in both places.

Check yourself

One user receives 5 million messages a day, hashed onto one shard among 200. You double the shard count. What happens to that user's write rate on the shard that holds them?

It stays about 58 a second, from 5 million divided by 86,400, unless their hash happens to cross a new boundary. Doubling the count moves other users. A hot key is one key, and one key is one shard. The peak you assumed, 5 times that, stays on that shard too.

The campaign query is not the partition key. What does a local secondary index cost on the read, and what does a global one cost on the write?

A local index only knows the rows on its shard, so the read asks every shard and waits on the slowest. A global index is partitioned by the campaign id, so the read is one shard, and every message write also updates that index. Synchronous, the send waits on the extra hop. Asynchronous, the index lags the row.

You add a node with consistent hashing, and a teammate instead changes a modulo. About how much of an 8 TB dataset moves in each plan if N is 200?

Consistent hashing moves about 1/N of the keys. 8 TB divided by 200 is about 40 GB. Changing the modulo moves almost every key, so almost all of the 8 TB. The 40 GB still needs a cutover. It does not need a full-dataset copy.

A hot channel shares a node with other channels, and each read of it touches many files. Who else slows down, and why does adding partitions fail to separate them?

Every other key on that node slows down, because the files, the disk, and the queue are the node’s. That is the Discord symptom. Adding partitions moves keys whose partition key changes home. The hot channel’s key still hashes or ranges to one place, so its reads and its files stay together until you change the key or isolate that key on its own node.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Karger and others, 1997; Discord message store; Slack Engineering; Bigtable, Chang and others; Uber Schemaless.