System Design

Core Concepts

Partitioning and Sharding

Picking a shard key looks like a data placement problem. It is really a decision about which of your queries gets to stay fast and which ones you agree to break, and it is the least reversible choice in the system.

Why you are doing this at all

Most bad sharding decisions are made in the first 20 minutes. Someone scans the schema for the column with the most distinct values and picks it. That's the wrong question to ask, and the answer still gets defended for years, because by the time anyone notices the mistake, the whole system depends on it.

Picking a shard key looks like a question about data layout: where do the rows go? It isn't. A shard is one of the machines that each hold part of the data, and the shard key is the column that decides which shard a row lives on. Once you choose the key, every query you will ever write falls into one of two groups: the ones that mention the key, and the ones that don't. The first group gets faster for good. The router, the layer that sends each query to the right shard, can send it to exactly one machine, and that machine holds everything the query needs. The second group gets worse for good. No single machine can answer it, so the query goes to many machines, and its answer waits for the slowest of them.

Sharding does not split your data. It splits your queries. Storage is the easy half. The harder half is that you're about to sort your whole query workload into winners and losers, permanently, based on one column.

Two kinds of query
On the left, the query names workspace 42, so the router sends it to the one shard that holds that workspace, in orange, and the grey shards do nothing. On the right, the query names no workspace, so the router has to ask all six shards, in red, and the reply waits for the slowest of them.On the left, the query names workspace 42, so the router sends it to the one shard that holds that workspace, in orange, and the grey shards do nothing. On the right, the query names no workspace, so the router has to ask all six shards, in red, and the reply waits for the slowest of them.
The key decides which queries stay on one shard. On the left, the query names workspace 42, so the router sends it to the one shard that holds that workspace, in orange, and the grey shards do nothing. On the right, the query names no workspace, so the router has to ask all six shards, in red, and the reply waits for the slowest of them.

Everything in this article follows from this split. You'll pick a key, choose between hashing and ranges, and decide how many shards to have. You'll handle the celebrity user, and decide when to give up and keep a second copy of the data. Each of these is the same question in a different place: which queries carry the key, and what will you do about the ones that don't?

The word means five different things

Interviewers use these five words as if they mean the same thing, and candidates lose points by answering the wrong one. So start by separating them.

Vertical partitioning moves whole tables onto separate databases. Users go on one box and files on another. There's no key, no router, and nothing that crosses shards. It's the cheapest scaling move there is, and it's where Figma started. Instead of sharding, they moved groups of tables onto their own databases, and that worked for years.

Horizontal partitioning inside one machine is Postgres declarative partitioning, MySQL partitions and similar features. There's one server and one connection, with several physical tables behind one table name. You get partition pruning, where a query skips the partitions it can't match. You get per-partition vacuum, Postgres's background cleanup of dead rows. And you can drop old data instantly by dropping its partition. You get no extra capacity at all. This solves maintenance problems, not scale problems, and it's worth doing long before you shard.

Sharding is horizontal partitioning across machines. That means you've added a routing layer, and whether your system is correct now depends on that layer. The rest of this article is about sharding.

Replication keeps copies of the same data on several machines. It isn't partitioning. It buys availability and read throughput. It buys no write throughput and no extra storage room, because every copy holds all the data and takes every write. Mixing up the two is the most common vocabulary mistake in system design interviews.

What actually forces the split

You don't split because of some vague idea of "scale." You split because you've hit a specific ceiling, and you should be able to say out loud which one.

Storage. The dataset no longer fits on one machine, or it no longer fits with the spare room your backup and restore process needs.

Throughput. The write rate is more than one primary can commit. The primary is the single machine that accepts writes. Read throughput is usually not a sharding problem, because replicas solve it, and replicas are much simpler. If your reason for sharding is reads, first check that you've used up replicas and caching.

Working set. The working set is the data that queries touch often. When it no longer fits in RAM, every query starts touching disk, and read latency jumps sharply. This ceiling arrives much earlier than total storage, and people miss it all the time.

Maintenance time. This is the one nobody lists. Your vacuum takes longer than a day. Your index rebuild needs a window you can't get. Your backup restore takes hours. Your schema migration locks a table for 10 minutes. This is what pushed Figma to split. Some of their tables had reached several terabytes and billions of rows, and they were causing reliability problems during Postgres vacuum. That made the split urgent, not disk space.

When not to do this

In an interview, the most useful thing you can say about sharding is that you've checked whether you need it.

In 2020, Figma ran on a single Postgres database, on the largest physical instance AWS offered. Its database load then grew almost 100 times. By the end of 2022 Figma had added caching, read replicas and a dozen vertically partitioned databases, and it still hadn't sharded a single table. Notion, when it sharded, set a ceiling of 10 TB per machine and 500 GB per table. That tells you how much data they consider comfortable for one Postgres box.

So if your biggest table is 200 GB and you're drawing a shard router, you've skipped several cheaper steps. Roughly in order of cost, they are an index, a covering index that holds every column a query needs, a read replica and a cache. After those come dropping columns you never query, moving cold rows to a separate table, vertical partitioning by feature, and horizontal partitioning on one machine. Only then comes sharding. Every step on that list can be undone. Sharding is the first one that can't.

The toolkit

The four ways to split

The same eight keys, split four ways
Each row places users u1 to u8 on four shards. The blue bars mark the shards that a read of u3 to u5 has to visit, and the right-hand columns count them and say where new users are written. Splitting by feature or by range keeps the read on one or two shards, but sends every new user to one shard. Hashing spreads the writes but sends the read to three shards. A directory puts each key wherever its map says, at the cost of a map lookup on every query.Each row places users u1 to u8 on four shards. The blue bars mark the shards that a read of u3 to u5 has to visit, and the right-hand columns count them and say where new users are written. Splitting by feature or by range keeps the read on one or two shards, but sends every new user to one shard. Hashing spreads the writes but sends the read to three shards. A directory puts each key wherever its map says, at the cost of a map lookup on every query.
No layout keeps both the range read and the writes cheap. Each row places users u1 to u8 on four shards. The blue bars mark the shards that a read of u3 to u5 has to visit, and the right-hand columns count them and say where new users are written. Splitting by feature or by range keeps the read on one or two shards, but sends every new user to one shard. Hashing spreads the writes but sends the read to three shards. A directory puts each key wherever its map says, at the cost of a map lookup on every query.
strategyhow you routewhat stays cheapwhat breakswho runs it
by feature (vertical)static config per tableeverything, within a table groupany join across groupsFigma, as their first move
by rangecompare against boundariesordered scans, recent data, dropping old datauniformity, because sequential keys pile onto one shardHBase, Bigtable, Spanner
by hashhash the key, take the sloteven spread, no hotspot from key orderevery ordered scan and every range queryCassandra, DynamoDB, Figma
by directorylook the key up in a mapper key control, moving one key deliberatelythe map is now a dependency of every queryNotion, Pinterest, Vitess

Directory-based sharding is underrated. The directory, usually called the shard map, is a plain table. Notion's has 480 rows, and each row maps a logical shard, a fixed slice of the key space, to a physical host. It's simple on purpose. You can read it, override one entry, and move one noisy tenant tonight without touching a hash function. A tenant is one customer's data, such as a workspace, and a noisy one is a tenant whose load slows down its neighbours. Notion, Pinterest, Figma and Vitess all chose a shard map over a live hash ring, and their reasons were operational rather than theoretical.

Range against hash, and the composite that beats both

Range partitioning gives each shard a continuous range of keys, so ordered access comes for free. A created_at BETWEEN query becomes one shard, one seek and one sequential read. But if your key increases with time, range partitioning also guarantees that one shard takes all the writes, all the time. Google's Bigtable documentation says it directly: never put a timestamp at the start of a row key.

Hash partitioning runs the key through a hash function and uses the result to pick the shard. That spreads keys evenly for free, and it takes ordered access away completely. Figma accepted this on purpose. They hash their shard keys for routing, and they wrote down the cost: range scans on shard keys are less efficient, because sequential keys hash to different shards.

A composite key gets you both, and it's the most useful single idea in this article. A composite key has two parts, a prefix and a suffix.

A key in two parts
The hash of the prefix, channel 42, picks shard 3. Inside shard 3, rows are stored sorted by the whole key, so all of channel 42's messages sit next to each other in message order, in green. Reading the last 50 messages is one seek to the end of that run, then one scan.The hash of the prefix, channel 42, picks shard 3. Inside shard 3, rows are stored sorted by the whole key, so all of channel 42's messages sit next to each other in message order, in green. Reading the last 50 messages is one seek to the end of that run, then one scan.
The prefix picks the shard, and the suffix sorts the rows on it. The hash of the prefix, channel 42, picks shard 3. Inside shard 3, rows are stored sorted by the whole key, so all of channel 42's messages sit next to each other in message order, in green. Reading the last 50 messages is one seek to the end of that run, then one scan.

The prefix decides which machine holds the row. The suffix decides the order the rows sit in on that machine. So (channel_id, message_id) puts one channel's messages on one shard, in time order, and "the last 50 messages in this channel" is one seek and one scan. Channels spread across machines as if they were hashed, and inside a channel you get ordered access as if it were a range.

Every mature partitioned store gives you both parts, under different names.

storeprefix (picks the shard)suffix (picks the order)
Cassandrapartition keyclustering columns
DynamoDBpartition keysort key
Bigtablethe high cardinality prefix of the row keythe rest of the row key
Kafkathe message keyoffset within the partition
Redis Clusterthe hash tag inside {}not applicable

If someone asks for your shard key and you answer with a single column, you've probably given up ordered access and got nothing back for it.

Virtual shards, and why the count should be large and fixed

Don't shard directly onto machines. Shard onto a large, fixed number of logical shards, also called virtual shards. Then map the logical shards to machines with a table you can edit.

There are two reasons.

First, it separates two operations. Changing the number of logical shards changes which shard every key belongs to. Changing which machine holds a logical shard only moves files. If you keep the first number fixed forever, you never have to do the hard one.

Second, random placement is much less even than people assume. Hashing each shard to a machine is random placement. Say you place 100 shards on 100 machines that way, so there's one shard per machine on average. The fullest machine doesn't hold 1 percent of the data. It holds about 4 percent.

100 machines, three shard counts
Each bar is one machine's load in one random layout, sorted from fullest to emptiest, with the fullest in red. With one shard per machine, 38 machines get nothing and the fullest carries 4 times the average. With 16 shards per machine the fullest carries 1.7 times, and with 256 it carries 1.2 times. You buy hardware for the fullest machine, so that ratio is your hardware bill.Each bar is one machine's load in one random layout, sorted from fullest to emptiest, with the fullest in red. With one shard per machine, 38 machines get nothing and the fullest carries 4 times the average. With 16 shards per machine the fullest carries 1.7 times, and with 256 it carries 1.2 times. You buy hardware for the fullest machine, so that ratio is your hardware bill.
More shards per machine flattens the load. Each bar is one machine's load in one random layout, sorted from fullest to emptiest, with the fullest in red. With one shard per machine, 38 machines get nothing and the fullest carries 4 times the average. With 16 shards per machine the fullest carries 1.7 times, and with 256 it carries 1.2 times. You buy hardware for the fullest machine, so that ratio is your hardware bill.
Back of envelopeLoad imbalance from random shard assignment, 100 machines
Simulated: assign V x 100 shards to 100 machines uniformly at
random, 20,000 trials, measure fullest machine / average machine

  shards per machine     expected worst      worst trial seen
  ────────────────────────────────────────────────────────────
                   1              4.24x                 9.00x
                   2              3.15x                 6.00x
                   4              2.45x                 4.50x
                   8              1.99x                 3.13x
                  16              1.68x                 2.56x
                  64              1.33x                 1.70x
                 256              1.16x                 1.32x

Classic consistent hashing, one ring point per node:
                   1              5.17x                13.82x

At one shard per machine you buy 4x the hardware you need,
and in an unlucky layout, 9x. The fix costs nothing at design
time and is impossible to retrofit.

This is a classic result called balls into bins. If you throw n balls into n bins at random, the fullest bin holds about log n / log log n balls, not one. If you throw many more balls than bins, the ratio falls toward 1. That's why the shard counts real teams chose are so large. Pinterest created 4,096 shards out of a possible 65,536. Notion started with 480 logical shards on 32 machines. Redis Cluster fixes the number of slots at 16,384 and never changes it.

Notion's 480 has a second useful property: it divides evenly by many numbers. So Notion can go from 32 hosts to 40 to 48, and every host still gets a whole number of shards. Pick a number with many factors, not a round decimal one.

Keys moved when the fleet grows
The red bars are id % N. The green bars are a fixed logical shard count with a map, which moves only the shards that change machine, the minimum possible. Going from 32 machines to 33 moves 97 percent of keys under id % N and 3 percent with a map. Only doubling, from 32 to 64, costs the same both ways.The red bars are id % N. The green bars are a fixed logical shard count with a map, which moves only the shards that change machine, the minimum possible. Going from 32 machines to 33 moves 97 percent of keys under id % N and 3 percent with a map. Only doubling, from 32 to 64, costs the same both ways.
With id % N, adding one machine moves almost every key. The red bars are id % N. The green bars are a fixed logical shard count with a map, which moves only the shards that change machine, the minimum possible. Going from 32 machines to 33 moves 97 percent of keys under id % N and 3 percent with a map. Only doubling, from 32 to 64, costs the same both ways.

Consistent hashing, and what it is actually for

Consistent hashing comes from a 1997 paper at STOC, the Symposium on Theory of Computing, by Karger, Lehman, Leighton, Levine, Lewin and Panigrahy. It was built for web caching, where there are many clients, the set of cache nodes changes without warning, and there's no way to get everyone to agree on a mapping. Nodes and keys are hashed onto the same circle, called the ring, and each key belongs to the next node along the ring. So adding or removing a node moves only the keys that node is responsible for, roughly 1/N of the total, instead of reshuffling everything.

That property matters. But it isn't the property most sharded databases need.

The ring also needs virtual nodes, for the same reason as the worksheet above, and it needs them more. Virtual nodes are extra points on the ring for each machine. With one ring point per node, a 100-node simulation puts 5.17 times the average on the fullest node. That's worse than the balls-into-bins case, because a node's share is the gap between two random points on the ring, and those gaps vary more than the counts in the bins do. Dynamo-style systems give each node many ring points, called tokens, for this reason. If a design has one ring position per machine, it carries a 5x hardware multiplier that nobody measured.

The ceilings you are actually splitting against

Real systems publish limits per partition. Learn two or three of them by heart, because quoting a real limit turns a vague claim into an argument.

storeper partition ceilingwhat happens at the limit
Cassandra100 MB and 100,000 rows recommended, 2 billion cells hardcompaction and GC pressure long before the hard limit
DynamoDB10 GB, and 3,000 RCU or 1,000 WCU per secondsplits automatically on size, throttles on throughput
Elasticsearch10 to 50 GB per shard, under 200 million docs, 1,000 shards per nodeslow queries and slow single shard recovery
Postgres, per Notion's operating limits500 GB per table, 10 TB per machinevacuum and replication stop keeping up
Kafkano size ceiling, but one partition is the unit of both ordering and consumer parallelismconsumers past the partition count sit idle

Kafka's limit is about structure rather than size. A partition is the unit of ordering, so events that must be processed in order have to share one. A partition is also the unit of consumer parallelism. Within a consumer group, each partition is read by exactly one consumer, so the group can never have more busy members than there are partitions. These two facts pull in opposite directions, and the partition key is where you settle them. If you choose user_id, each user's events stay in order, and you can add consumers up to the partition count. If you choose a random key, the load is perfectly balanced and nothing is in order.

Partitions in a consumer group
Events are keyed by user_id, so all of user 7's events land in partition 1, in the order they were written. Each partition is read by one consumer in the group. Four partitions keep four consumers busy, and consumers 5 and 6, in grey, sit idle.Events are keyed by user_id, so all of user 7's events land in partition 1, in the order they were written. Each partition is read by one consumer in the group. Four partitions keep four consumers busy, and consumers 5 and 6, in grey, sit idle.
The partition count caps the useful consumers. Events are keyed by user_id, so all of user 7's events land in partition 1, in the order they were written. Each partition is read by one consumer in the group. Four partitions keep four consumers busy, and consumers 5 and 6, in grey, sit idle.

The method

This is where you announce a shard key in the interview. It should take 5 minutes, and it should end with you naming the queries you just broke.

Choosing a shard key in six steps
Each box is a step, with what it produced in the B2B example below. Steps 3 and 4, with red dashed outlines, are the ones candidates skip, and they are where the 1.6 TB workspace shows up. Steps 5 and 6 list the queries the key breaks and give each one an outcome.Each box is a step, with what it produced in the B2B example below. Steps 3 and 4, with red dashed outlines, are the ones candidates skip, and they are where the 1.6 TB workspace shows up. Steps 5 and 6 list the queries the key breaks and give each one an outcome.
Check the biggest key, not the average. Each box is a step, with what it produced in the B2B example below. Steps 3 and 4, with red dashed outlines, are the ones candidates skip, and they are where the 1.6 TB workspace shows up. Steps 5 and 6 list the queries the key breaks and give each one an outcome.

1. Write down the queries and their rates, before you look at the schema. List queries, not tables: ten to fifteen lines of the form "given X, fetch Y, N times per second." This list is the input to the decision, and everything after it is arithmetic. If you start from the schema instead, you end up picking a key by cardinality, the number of distinct values in a column.

2. Name the entity that owns the access pattern. In most systems, nearly every request already carries one noun: the workspace, the user, the channel, the org or the device. That noun is your candidate key. The reason isn't balance. The reason is that requests already know it. Figma is a good example. Instead of forcing one key on everything, they picked three: UserID, FileID and OrgID. Almost every table at Figma could be sharded by one of those three, so the application needed very little rewriting.

3. Check the ceilings against the largest single key, not the average. Take the per-partition limits from the table above and compare your biggest key with them. The average doesn't matter here. If the average partition is 40 MB and the largest is 4 GB, the scheme is broken, and the average will tell you it's fine.

4. Look at the top 0.1 percent of keys. Sort your candidate keys by row count and by request rate, separately, and look at the top of both lists. It takes one query against production, and no other step on this list tells you as much. You're looking for two different problems, a key that is too big and a key that is too busy, and they have different fixes.

5. Sort every query from step 1 into single shard or every shard. Make two columns. A query in the second column goes to the whole fleet, every shard machine you run. For each one, multiply its rate by the shard count to get its real load, then apply the tail latency arithmetic from mistake 4 below. Most designs fail in this column without the author noticing, because in staging, with three shards, the query still returns correct results.

6. Decide what happens to the losing queries, then commit. Each query in the every-shard column gets one of four outcomes. First, it may run rarely enough that scatter-gather is fine, where the router sends it to every shard and merges the answers. Second, it can get a second copy of the data, keyed differently. Third, it can move to a data store built for that access pattern. Fourth, it can be deleted from the product. Pick one for each query, out loud. This step is what turns an answer into a good answer.

Worked examples, start to finish

Here are four systems. In each one, the obvious key turns out to be the right key, and in each one it fails for a different reason.

A B2B app, where the key is right and the distribution is not

Take a collaborative product with 100,000 workspaces and 20 TB of data. Every request carries a workspace ID, because that's how the product works. Step 2 takes four seconds.

Now size it three ways.

Back of envelopeShard count from three directions, and which one binds
Inputs
  100,000 workspaces, 20 TB total
  400,000 queries/s at peak
  hot set ~5 percent of data, read on any given day

Storage, against a 500 GB per table ceiling
  20 TB / 500 GB              = 40 logical shards minimum

Throughput, at ~15,000 simple queries/s per primary
  400,000 / 15,000            ≈ 27 machines

Working set, at 256 GB RAM per machine
  20 TB × 0.05               = 1 TB hot
  1 TB / 256 GB               ≈ 4 machines

Pick for the largest: 32 machines
  × 15 logical shards each    = 480 logical shards
  → 20 TB / 480              ≈ 42 GB per logical shard,
                                12x headroom to the ceiling

Throughput binds today. Storage is what will bind you into
a second migration, because query rate plateaus with your
user count and data only grows.

These are Notion's published numbers, 480 logical shards across 32 physical databases, and inputs like these lead to them. The ceiling you provision for today is not the one that will force your next migration.

Now do step 4, the step everybody skips, and sort the workspaces by size. The largest one, often called the whale, is the problem.

Workspace size by rank
Both axes are logarithmic, so a size that falls as 1 / rank draws as a straight line. The largest workspace holds 1.6 TB, and the top three, in red, are each over the 500 GB per-table ceiling on their own. More shards cannot fix this, because each of those workspaces is one key.Both axes are logarithmic, so a size that falls as 1 / rank draws as a straight line. The largest workspace holds 1.6 TB, and the top three, in red, are each over the 500 GB per-table ceiling on their own. More shards cannot fix this, because each of those workspaces is one key.
One workspace is 8,000 times the mean. Both axes are logarithmic, so a size that falls as 1 / rank draws as a straight line. The largest workspace holds 1.6 TB, and the top three, in red, are each over the 500 GB per-table ceiling on their own. More shards cannot fix this, because each of those workspaces is one key.
Back of envelopeThe whale, and why adding shards cannot touch it
100,000 workspaces, 20 TB, heavy tailed by rank

  mean workspace               20 TB / 100,000    = 200 MB
  largest workspace                               ≈ 1.6 TB
  ratio                        1.6 TB / 200 MB    = 8,000x
  top 10 workspaces combined                      ≈ 4.7 TB
  → 23 percent of all data in 10 keys out of 100,000

Against the 500 GB per table ceiling
  1.6 TB / 500 GB                                 = 3.2x over

Try to fix it with more shards
  480 shards   → whale still on 1 shard, still 1.6 TB
  4,096 shards → whale still on 1 shard, still 1.6 TB
  65,536 shards → whale still on 1 shard, still 1.6 TB

Adding shards divides the key space. It does not divide a key.

Here, hashing is useless. Any hash function maps acme-corp to exactly one value, so the whole workspace lands on exactly one shard. If you rehash, the problem moves to a different machine and stays the same size.

Naive

Move the big tenant to a bigger machine

The reasoning makes sense: one key is too big for one shard, so give that shard a bigger machine. And it works, once. Then you run out of instance sizes, and you've built a fleet where one machine is special and nobody remembers why. The real cost is that this is a one-time move, not a strategy. It only delays the problem until the tenant is 4 TB and the migration is much harder.

Senior

A shard map with per key overrides, from day one

Route by workspace ID through a lookup table rather than a hash function, and make the table support overrides for single keys before you need one. The top ten tenants are pinned to dedicated shards, and the other 99,990 go wherever the default mapping puts them. Moving a tenant becomes a row edit plus a data copy, not a redesign. This is what a directory-based scheme gives you, and it's the main practical reason to prefer it over a hash ring.

The cost is that every query now reads the shard map, so the map has to be cached everywhere, versioned and correct. If two clients disagree about where a workspace lives, that isn't a routing bug. It's a data corruption bug.

Staff

Stop requiring that one tenant is one shard

Question the assumption that a workspace can't be split. It can. It just has no second key yet. Add one, usually the next level down in the product, such as the project. Shard the largest tenants on (workspace_id, project_id), and leave everyone else on workspace_id alone. You're now running two routing schemes at once. That sounds bad, and it's much cheaper than 1.6 TB on one primary.

Size it. Split across 8 sub-shards, the whale goes from 3.2 times over the ceiling to 200 GB per sub-shard, 2.5 times under it. Your largest customer can now grow 2.5 times before it needs more sub-shards.

What you give up: transactions and joins across the whole whale workspace, which every other tenant still has. So this only works if you can name the queries that need the whole workspace, and confirm they're admin tasks rather than things users wait on. There's also a commercial answer, not a technical one. A tenant at 8,000 times the mean may belong on its own single-tenant deployment, at a price that reflects it. Interviewers respond well to a candidate who notices that.

Three answers to a 1.6 TB tenant
A bigger machine and a dedicated shard both leave 1.6 TB in one table on one primary, in red, 3.2 times over the dashed 500 GB ceiling. Splitting the tenant by project spreads it over 8 sub-shards of 200 GB each, in green, 2.5 times under the ceiling.A bigger machine and a dedicated shard both leave 1.6 TB in one table on one primary, in red, 3.2 times over the dashed 500 GB ceiling. Splitting the tenant by project spreads it over 8 sub-shards of 200 GB each, in green, 2.5 times under the ceiling.
Only splitting the tenant gets it under the ceiling. A bigger machine and a dedicated shard both leave 1.6 TB in one table on one primary, in red, 3.2 times over the dashed 500 GB ceiling. Splitting the tenant by project spreads it over 8 sub-shards of 200 GB each, in green, 2.5 times under the ceiling.

Chat messages, where the key is right and time is the problem

Discord published how they solved this one, so we can check our work against a real answer.

Here the data is messages, keyed by channel. Step 2 gives you channel_id straight away. Every read is "the recent messages in this channel," every write is "a message in this channel," and every request already carries the key. Step 3 is where it breaks. The problem isn't that one channel is much bigger than the others, as with the whale. The problem is that every busy channel keeps growing, with no limit, forever.

Back of envelopeHow long a busy channel survives a single partition
Assume a busy channel, and a stored row of ~500 bytes
  20,000 messages/day × 500 B         = 10 MB/day

Against Cassandra's recommended 100 MB partition
  100 MB / 10 MB per day               = 10 days

Against Cassandra's advertised 2 GB hard ceiling
  2 GB / 10 MB per day                 = 200 days

After three years
  1,095 days × 10 MB                   ≈ 11 GB
  → 110x the recommendation, 5x the hard ceiling

Discord's published bucket width is 10 days. The arithmetic
above lands on their number, which is a good sign that the
ceiling is what actually drove the decision.

Discord's write-up matches. When they started importing existing messages into Cassandra, they saw warnings about partitions over 100 MB. They concluded that although Cassandra advertises 2 GB partitions, large partitions cause heavy garbage collection (GC) pressure during compaction and when the cluster grows. Compaction is Cassandra merging its data files in the background. Their fix was to bucket messages by time. About 10 days of messages per bucket kept even their largest channels comfortably under 100 MB, and the partition key became (channel_id, bucket).

Partition size as a channel ages
At 10 MB a day, a partition keyed by channel_id alone grows in a straight line, in red. It passes the 100 MB recommendation on day 10, Cassandra's advertised 2 GB on day 200, and reaches 11 GB after three years. With 10-day buckets, each partition stops at 100 MB, the green line along the bottom.At 10 MB a day, a partition keyed by channel_id alone grows in a straight line, in red. It passes the 100 MB recommendation on day 10, Cassandra's advertised 2 GB on day 200, and reaches 11 GB after three years. With 10-day buckets, each partition stops at 100 MB, the green line along the bottom.
Without a time bucket, the partition grows forever. At 10 MB a day, a partition keyed by channel_id alone grows in a straight line, in red. It passes the 100 MB recommendation on day 10, Cassandra's advertised 2 GB on day 200, and reaches 11 GB after three years. With 10-day buckets, each partition stops at 100 MB, the green line along the bottom.
Naive

Partition by message ID, because it is perfectly uniform

This is what you get if you pick the key by cardinality, and the distribution is perfectly even. But the only query the system has, "the last 50 messages in this channel," now touches every shard in the fleet, because no shard holds a channel's messages together. You've optimised a number nobody asked about and broken the one query the product is made of. Call it out as a wrong answer, because it's what "pick the highest-cardinality column" recommends.

Senior

Partition by channel ID

This is correct, and it's the standard answer. Reads and writes for a channel land on one machine. The recent-messages query is one seek and one scan in reverse ID order. There are enough channels to spread evenly across the machines. Most people build this, and it works fine for a couple of years.

The cost is that partition size now has no limit over time. Every day, every active channel's partition gets bigger, and nothing ever makes it smaller.

Staff

Partition by channel and time bucket

Question the assumption that a partition key must be a single existing column. Make it (channel_id, bucket), where bucket is calculated from the timestamp inside the message ID, so it needs no lookup and no extra storage. Now the bucket width caps the partition size, not the age of the channel. You choose the width from the ceiling: at 10 MB a day and a 100 MB target, that's 10 days.

Size the tradeoff. Partition size goes from no limit, 11 GB at three years, to a hard cap of 100 MB forever.

What you give up: "all messages in this channel" is no longer one read. It's one read per bucket, which is about 180 reads for a five-year-old channel. That's fine, because the product has no such query, and this is the part to defend out loud. The product has "the most recent messages," which reads the current bucket and sometimes the one before it. It also has search, and the message store was never going to serve search anyway. You gave up a query nobody runs, and in return every partition stays under a ceiling that would otherwise have taken the cluster down.

One channel, many buckets
The bucket number comes from each message's timestamp, so five years of channel 42 sit in about 180 partitions of at most 100 MB each. Reading the last 50 messages reads the current bucket, and sometimes the one before it, in green. Reading every message in the channel reads every bucket, in red.The bucket number comes from each message's timestamp, so five years of channel 42 sit in about 180 partitions of at most 100 MB each. Reading the last 50 messages reads the current bucket, and sometimes the one before it, in green. Reading every message in the channel reads every bucket, in red.
Recent messages need one bucket, and the full history needs all of them. The bucket number comes from each message's timestamp, so five years of channel 42 sit in about 180 partitions of at most 100 MB each. Reading the last 50 messages reads the current bucket, and sometimes the one before it, in green. Reading every message in the channel reads every bucket, in red.

A social feed, where the key is right and the query you care about loses

Take 10 million daily users, each following about 200 accounts. Posts are keyed by author, which is obvious and correct. Writing a post touches one shard, and so does reading an author's profile.

Then you build the timeline, the list of recent posts from everyone a user follows. The timeline is the product.

Back of envelopeRead fanout against write fanout, priced
Reading a timeline by gathering from 200 authors, across 100 shards
  distinct shards touched  100 × (1 − (1 − 1/100)^200)
                           = 100 × (1 − 0.99^200)
                           = 100 × 0.866            ≈ 87 shards

  at 50,000 timeline reads/s
  50,000 × 87                                = 4,350,000 shard queries/s

Writing into 200 follower timelines instead
  2M posts/day × 200 followers               = 400M rows/day
  400M / 86,400                              ≈ 4,600 writes/s average
  × 3 for peak                               ≈ 14,000 writes/s
  400M × 50 B per timeline row               = 20 GB/day
  × 30 days retained                         = 600 GB

  ────────────────────────────────────────────────────────────
  read fanout    4,350,000 shard queries/s
  write fanout      14,000 writes/s + 600 GB
                                              = 310x cheaper

Gathering from 200 keys over 100 shards is not a scatter-gather.
It is a full fleet scan wearing a disguise.

Remember that 87. Once you're gathering a couple of times more keys than you have shards, you're touching nearly every shard. Adding shards then makes it worse, not better, because each read touches more of them. At that point scatter-gather is a broadcast to the whole fleet.

Shards touched by one timeline read
A timeline read gathers posts from every followed account, and each account sits on a random shard. With 100 shards, in orange, 200 followed accounts touch 87 shards. With 200 shards, in red, the same read touches 127, so adding shards made each read more expensive.A timeline read gathers posts from every followed account, and each account sits on a random shard. With 100 shards, in orange, 200 followed accounts touch 87 shards. With 200 shards, in red, the same read touches 127, so adding shards made each read more expensive.
Past a few hundred keys, a read touches nearly every shard. A timeline read gathers posts from every followed account, and each account sits on a random shard. With 100 shards, in orange, 200 followed accounts touch 87 shards. With 200 shards, in red, the same read touches 127, so adding shards made each read more expensive.

So the decision is to keep two copies of the data, partitioned two ways. Posts are partitioned by author. Timeline entries are partitioned by reader, and they're written when the post is made. Writing each post into every follower's timeline like this is called write-time fanout. It isn't a hack, and it isn't denormalisation for speed. It follows directly from the thesis. You had a query that didn't carry the shard key, so you built a copy of the data whose shard key it does carry.

Posts and timelines, keyed two ways
An author's post is written once to the posts table, keyed by author (1). A fanout worker then writes one row into each follower's timeline, about 200 rows spread across the timeline shards, which are keyed by reader (2). Reading a timeline is one read on one shard, in green (3).An author's post is written once to the posts table, keyed by author (1). A fanout worker then writes one row into each follower's timeline, about 200 rows spread across the timeline shards, which are keyed by reader (2). Reading a timeline is one read on one shard, in green (3).
A second copy keyed by reader makes the timeline one read. An author's post is written once to the posts table, keyed by author (1). A fanout worker then writes one row into each follower's timeline, about 200 rows spread across the timeline shards, which are keyed by reader (2). Reading a timeline is one read on one shard, in green (3).

The whale problem from the first example is back in a different form. An account with 50 million followers can't use write-time fanout, because one post would become 50 million writes. The standard answer is a hybrid. Normal accounts fan out at write time. For the few thousand accounts above some follower threshold, the feed fetches their posts at read time and merges them in. So your feed service now contains two algorithms and a threshold, and you should be able to defend the threshold's value.

Order history, where the natural key guarantees a hot shard

Take an orders table with 20,000 writes per second at peak. Every query covers a time range: this month's orders for a merchant, yesterday's reconciliation, the last 90 days for a customer. Range partitioning by created_at looks perfect, because every range query becomes one partition.

Then look at where the writes go. Every new order has created_at equal to now, so 100 percent of writes land on the newest partition, always. This is the failure the Bigtable docs warn about, and they name two fixes. Field promotion puts a high-cardinality field, such as the merchant ID, in front of the timestamp. Salting puts a small bucket number, calculated from a hash, in front of it instead. This example uses salting.

Where the order writes land
With range partitioning on created_at, all 20,000 writes a second go to May, the newest partition, in red. That is four times the 5,000 per-partition limit. With 8 salt buckets in front of the timestamp, each bucket takes 2,500 a second, in green, under the limit.With range partitioning on created_at, all 20,000 writes a second go to May, the newest partition, in red. That is four times the 5,000 per-partition limit. With 8 salt buckets in front of the timestamp, each bucket takes 2,500 a second, in green, under the limit.
A time-ordered key puts every write on the newest partition. With range partitioning on created_at, all 20,000 writes a second go to May, the newest partition, in red. That is four times the 5,000 per-partition limit. With 8 salt buckets in front of the timestamp, each bucket takes 2,500 a second, in green, under the limit.

The question is how many buckets to use, and the answer is the opposite of the rule from the virtual shards section.

Back of envelopeHow many salt buckets a time ordered key can afford
Writes must clear the per shard ceiling
  20,000 writes/s / 5,000 per shard      = 4 buckets minimum
  × 2 for headroom                        = 8 buckets

Every time range query now fans out to all buckets
  8 buckets    → 8 partition scans per range query
  64 buckets   → 64 scans
  4,096 buckets → the range query is a full fleet scan,
                  and the table exists for range queries

Pick 8. The rule for a salted time key is the smallest count
that clears the write ceiling. For a hash partitioned key it
was the largest count you can administer. Same mechanism,
opposite direction, because here the suffix is the query.

So the key is (hash(order_id) % 8, created_at, order_id). In the prefix and suffix terms from the toolkit, the 8-way prefix spreads the writes, and the time suffix keeps the scans sequential inside each bucket. A range query reads 8 sorted ranges and merges them. That's 8 sequential reads instead of 1, which is a small price for writes that no longer pile onto one partition.

If the reconciliation job is the only reason the range query exists, the better answer may be that this table shouldn't serve it at all. That leads to the general question: what do you do with a query that doesn't carry the key?

Naive

Scatter-gather from the application, for every query that lacks the key

Send the query to all shards and merge the results in the application. It's simple, it works in staging, and every ORM makes it easy. But the query's real cost is now its rate times your shard count. Its latency is the slowest of N shard responses, not the typical one. Its availability is the product of N availabilities, because it fails if any one shard is down. All three get worse every time you add a machine, which is the opposite of why you sharded.

Senior

A second index table, partitioned by the other key

For each query that lacks the shard key, keep a narrow table keyed by what the query does have, which maps it to the primary key and the shard. For example, map merchant_id to order_id, partitioned by merchant. Now a lookup by merchant reads one index shard, then only the shards that hold that merchant's orders, instead of broadcasting to all N. This is what a global secondary index is, and if your store offers one, use it instead of building your own.

The cost is that every write now touches two partitions, so you have a consistency problem you didn't have before. The index can be stale. It can be wrong if the second write fails, and fixing it needs a reconciliation job that compares the index with the table. That cost is real, and it's much smaller than the broadcast.

Staff

Take the query out of this data store entirely

Question the assumption that one data store should answer all of these queries. It shouldn't. The shard key for transactions (OLTP, online transaction processing) and the access pattern for analytics never match. Transactions want "everything about one entity." Analytics wants "one column across all entities." A second index gives you point lookups on a different key. It does nothing for "revenue by region by week," and no shard key ever will.

So transactional orders stay sharded by their natural key. A change stream, a feed of every change made to the table, then feeds three other systems. A columnar store such as ClickHouse takes anything aggregate. A search index such as Elasticsearch takes anything full-text. A cache takes anything small that is read far more often than it's written. Each of these is partitioned the way its own access pattern wants. They lag the orders table by seconds, and that's fine, because nobody reconciles the quarter in real time.

Size the tradeoff. The broadcast to the whole fleet is gone, and in return you operate one more system and accept a lag of seconds on every derived view.

What you give up: read-your-writes on the derived views, so a user may not see their own change there straight away. You also lose the ability to join transactional and analytical data in one query. If someone needs both, and needs them consistent, you're back on the transactional store paying for the broadcast. So ask whether they really do.

Three answers to a query without the key
A broadcast sends every merchant query to all eight shards, in red. An index keyed by merchant answers the same query with one index read (1), then reads only the shards that hold that merchant's orders (2). A change stream consumer copies every change into ClickHouse, Elasticsearch and a cache, each a few seconds behind, so the orders store never sees those queries.A broadcast sends every merchant query to all eight shards, in red. An index keyed by merchant answers the same query with one index read (1), then reads only the shards that hold that merchant's orders (2). A change stream consumer copies every change into ClickHouse, Elasticsearch and a cache, each a few seconds behind, so the orders store never sees those queries.
Broadcast it, index it, or move it to another store. A broadcast sends every merchant query to all eight shards, in red. An index keyed by merchant answers the same query with one index read (1), then reads only the shards that hold that merchant's orders (2). A change stream consumer copies every change into ClickHouse, Elasticsearch and a cache, each a few seconds behind, so the orders store never sees those queries.

Where it goes wrong

These are ordered roughly by how often they show up. The first two cause most of the failures.

1. Choosing the key for cardinality instead of for the queries

Choosing the key for cardinality is the most common failure by a wide margin, and it's the one the thesis exists to prevent. Somebody looks for the column with the most distinct values, finds a UUID, and picks it. The distribution is perfect, and every query in the product now touches every shard.

You can spot it in a candidate who can state their shard key but can't say which queries it breaks. Ask "what does the admin dashboard do now?" and see what happens. The fix is step 1 of the method: the query list always comes before the schema.

2. Reaching for hashing to fix skew

Skew means some keys carry far more data or traffic than others. Hashing spreads the key space evenly. It doesn't spread the traffic. Those are different things, and outages happen in the gap between them.

If you hash 100 million user IDs onto 100 shards, every shard gets 1 percent of the users. The most-followed account in the world still hashes to one value and lives on one shard, and that shard still takes all of that account's traffic. You've balanced something that was never unbalanced.

This is where DynamoDB's per-partition limit causes an incident. The partition holding the celebrity key reaches 3,000 read units per second and starts throttling, while the table as a whole sits nearly idle. The table-level metric your alerts watch shows nothing wrong. There are real fixes, and none of them is "hash it." You can split the hot key with a small salt on writes and read every salted key. You can cache the hot key in front of the data store. Or you can give the hot key its own partition and its own capacity.

Even users, uneven reads
Every shard holds 1 million users, so the left chart is flat. On the right, shard 4 also holds the celebrity account, and its reads go past the 3,000 per second partition limit. The red part is throttled, while the other nine shards serve about 500 reads a second. The traffic numbers are assumed.Every shard holds 1 million users, so the left chart is flat. On the right, shard 4 also holds the celebrity account, and its reads go past the 3,000 per second partition limit. The red part is throttled, while the other nine shards serve about 500 reads a second. The traffic numbers are assumed.
Hashing evened out the users, not the traffic. Every shard holds 1 million users, so the left chart is flat. On the right, shard 4 also holds the celebrity account, and its reads go past the 3,000 per second partition limit. The red part is throttled, while the other nine shards serve about 500 reads a second. The traffic numbers are assumed.

3. Too few shards, sized to today's machine count

Sizing the shard count to today's machine count is invisible in testing and can't be fixed afterwards, which is why it's on this list as well as in the simulation above. It has three symptoms. Your fullest machine holds several times the average, and nobody knows why. Adding a machine means moving a large fraction of your data. And your shard count and machine count are the same number, so nobody can tell which one a piece of code depends on.

Pick a large logical shard count with many factors. Freeze it. Map it to machines with a table. If you take only one thing from this article into your next design, take this one, because it costs nothing today and can't be added later.

4. Not pricing scatter-gather

A query that touches N shards waits for the slowest of them, and few people calculate what that does to its latency. The yardstick is p99, the latency that 99 percent of requests beat.

A fanout request waits for its slowest shard
Each dot is one shard's response time, drawn from the same assumed distribution: about 5 ms typically and 50 ms at the p99. The large dot in each row is the slowest shard, and the request finishes when it does. With 1 or 10 shards, the slowest is usually quick. With 100, 63 percent of requests have at least one shard past its p99, like the red one here.Each dot is one shard's response time, drawn from the same assumed distribution: about 5 ms typically and 50 ms at the p99. The large dot in each row is the slowest shard, and the request finishes when it does. With 1 or 10 shards, the slowest is usually quick. With 100, 63 percent of requests have at least one shard past its p99, like the red one here.
The more shards a request touches, the more likely one is slow. Each dot is one shard's response time, drawn from the same assumed distribution: about 5 ms typically and 50 ms at the p99. The large dot in each row is the slowest shard, and the request finishes when it does. With 1 or 10 shards, the slowest is usually quick. With 100, 63 percent of requests have at least one shard past its p99, like the red one here.
Back of envelopeThe probability that a fanout request hits a slow shard
Each shard independently exceeds its own p99 with probability 0.01
P(request sees at least one slow shard) = 1 − 0.99^N

    N shards      P(slow)     what it means
  ─────────────────────────────────────────────────────────────
           1        1.0%      the shard's p99 is the request p99
          10        9.6%
          32       27.5%
          64       47.4%
         100       63.4%      the shard's p99 is the request p37
         200       86.6%
         256       92.4%      almost every request is a tail request

Inverting it: for a 100 shard fanout to have a p99, each shard
needs P(slow) of 1 − 0.99^(1/100) ≈ 0.0001

You must budget against each shard's p99.99, not its p99.
Adding shards makes fanout slower. It is the only operation in
your system that gets worse the more you scale it.

At 100 shards, the latency you were calling your p99 is closer to your median. This is the tail-at-scale problem that every fanout system has, and partitioning is where teams create it by accident. It's also why three defences become necessary once your shard count passes about 20. The first is hedged requests, which send a backup copy of a slow request to another replica. The second is partial results with a deadline. The third is a timeout on each shard.

5. The things you silently gave up

Sharding takes features away without any error. The code still compiles, and in development, with one shard, the queries still return. The list is longer than people expect.

what you losewhywhat you do instead
AUTO_INCREMENTtwo shards will both hand out 1,000a snowflake style ID, or per shard ranges, or embed the shard in the ID like Pinterest does
unique constraints across shardsthe index is per shard, so two shards can each hold one alice@example.coma separate uniqueness table on the constrained column, keyed by that column
COUNT(*) and SUMevery shard has a piecea counter you maintain, or an approximate count, or an analytical store
ORDER BY x LIMIT 10the global top 10 needs the top 10 from every shard firstfetch N from each shard and merge, which costs N times the rows
joinsthe two rows are on different machinesco-locate under one key, or denormalise, or join in the application
foreign keysthe database cannot see the other shardapplication level checks and a reconciliation job
multi row transactionstwo shards, two commitsco-locate the transaction under one key, or two phase commit, or a saga

The right-hand column has a pattern. Almost every fix is either "co-locate it under one key" or "keep a second copy, keyed differently." Figma's version of the first is the colo, short for colocation. Tables that share a shard key and a physical layout are grouped into a colo. Joins and transactions are allowed inside a colo when they stay on one shard key, and nowhere else. That restriction keeps the system manageable, and it tells developers exactly what sharding still allows.

Pinterest's answer to the ID problem is worth copying as it is. They pack the location into the ID: 16 bits of shard, 10 bits of type and 36 bits of local ID. That supports 65,536 shards and 68 billion objects per shard. Given any ID, you know which shard holds it without a lookup, and the trick costs nothing.

Pinterest's ID layout
Each 64-bit ID holds a 16-bit shard ID, a 10-bit type and a 36-bit local ID, with the top 2 bits unused. Shifting the ID right by 46 bits gives the shard, so no lookup table is needed to find it.Each 64-bit ID holds a 16-bit shard ID, a 10-bit type and a 36-bit local ID, with the top 2 bits unused. Shifting the ID right by 46 bits gives the shard, so no lookup table is needed to find it.
The ID carries its own shard number. Each 64-bit ID holds a 16-bit shard ID, a 10-bit type and a 36-bit local ID, with the top 2 bits unused. Shifting the ID right by 46 bits gives the shard, so no lookup table is needed to find it.

6. Assuming you can change the shard key later

Adding shards and changing the shard key sound like similar jobs, and they're very different in size.

Adding shards is mechanical. Changing the shard key is a rewrite. Teams fear the wrong one. With a fixed logical shard count and a shard map, resharding, which moves shards between machines, is a data copy plus a map edit. It's well understood, there are tools for it, and users notice it for seconds at most. Changing the key changes every query, every write path, every transaction boundary and every uniqueness assumption in the application. No tool can do that for you, because the tool would have to be your application.

The published migrations show how big the difference is. Slack spent three years moving 99 percent of its MySQL query load onto Vitess, and it serves about 2.3 million queries per second at peak. Figma took nine months from first design to its first horizontally sharded table. Part of how they got there was an extra step in the middle, called logical sharding. Queries were routed as if the database were already sharded, while the data still sat in one place behind Postgres views. That let them test the application changes separately from the data movement, and the views added under 10 percent overhead in the worst case. When they cut over the first table in September 2023, the primaries were partly unavailable for ten seconds, and the replicas were not affected.

Figma's step between one database and many
Before, the application talks to one Postgres table. In logical sharding, DBProxy routes each query by shard key to a view, and every view still reads the same table, so a routing mistake can be undone without moving data. In physical sharding, the views become separate databases, and the routing stays the same.Before, the application talks to one Postgres table. In logical sharding, DBProxy routes each query by shard key to a view, and every view still reads the same table, so a routing mistake can be undone without moving data. In physical sharding, the views become separate databases, and the routing stays the same.
Change the routing first, and move the data later. Before, the application talks to one Postgres table. In logical sharding, DBProxy routes each query by shard key to a view, and every view still reads the same table, so a routing mistake can be undone without moving data. In physical sharding, the views become separate databases, and the routing stays the same.

So changing which key an application's queries carry, done well, takes months or years, a purpose-built proxy and a deliberately invented in-between state. Plan for that, and pick the key as if you'll never change it.

7. Treating rebalancing as a maintenance window

The first idea is usually to stop writes, copy the data, and start writes again. Nobody gets that maintenance window, so the migration never happens, and the shard stays overloaded for another six months.

What works is a double write with a verification phase. Notion used this to move onto its sharded databases.

Moving a shard in five phases
The source serves reads and takes every write until phase 5. The destination takes every new write first (1), so nothing changes behind the backfill, which then copies the history (2). It's compared with the source (3) before reads move over gradually (4). Phases 1 to 4 can be rolled back with a config change, in green. Only retiring the source (5), in red, has no free rollback.The source serves reads and takes every write until phase 5. The destination takes every new write first (1), so nothing changes behind the backfill, which then copies the history (2). It's compared with the source (3) before reads move over gradually (4). Phases 1 to 4 can be rolled back with a config change, in green. Only retiring the source (5), in red, has no free rollback.
The source stays correct until the last phase, so rollback is free until then. The source serves reads and takes every write until phase 5. The destination takes every new write first (1), so nothing changes behind the backfill, which then copies the history (2). It's compared with the source (3) before reads move over gradually (4). Phases 1 to 4 can be rolled back with a config change, in green. Only retiring the source (5), in red, has no free rollback.

Two details make it work. First, the source stays authoritative, meaning its copy is the one that counts, and it stays correct until phase 5. So every phase before the last can be reversed instantly. Second, the verification phase is not optional, because double writing is where the two copies drift apart without any error. A second write fails. The backfill races a live update. A type mismatch shows up on only 0.01 percent of rows. If you move reads over before a verification job has passed for days, you're trusting your data to code nobody has checked.

Back of envelopeWhat resharding actually moves
480 logical shards, growing from 32 machines to 48

  before   480 / 32                    = 15 shards per machine
  after    480 / 48                    = 10 shards per machine
  moved    5 shards × 32 machines      = 160 shards
           160 / 480                   = 33 percent of the data

Which is the theoretical minimum: 1 − 32/48 = 33 percent.

The same growth under id % N
  32 → 48 buckets                       = 67 percent moves
                                          (2x the minimum)
  32 → 33 buckets                       = 96.97 percent moves
                                          (32x the minimum, to add one machine)

A fixed logical shard count with a lookup table moves the
minimum possible amount of data, every time, by construction.

8. Forgetting that the router is now the system

Sharding adds a router, a component that sits in front of every query and knows where everything lives. It has three consequences, and teams usually learn all three from incidents.

First, the shard map decides whether your data is correct, so it can't be treated like a config file. If two application instances hold different versions of it, they write the same key to two different shards. That isn't a routing bug. It's two copies of a row that disagree, with no error anywhere. The map needs a version number, and clients must refuse to run on a version they know is stale.

Two versions of the shard map
Workspace 42 moved to shard 19 in map version 13. Instance B fetched v13 and writes to shard 19, while instance A is still on v12 and writes to shard 7. Each shard now holds a different copy of workspace 42, and nothing raises an error. The fix is in green: a version on the map, and clients that refuse a stale one.Workspace 42 moved to shard 19 in map version 13. Instance B fetched v13 and writes to shard 19, while instance A is still on v12 and writes to shard 7. Each shard now holds a different copy of workspace 42, and nothing raises an error. The fix is in green: a version on the map, and clients that refuse a stale one.
Two map versions put one workspace on two shards. Workspace 42 moved to shard 19 in map version 13. Instance B fetched v13 and writes to shard 19, while instance A is still on v12 and writes to shard 7. Each shard now holds a different copy of workspace 42, and nothing raises an error. The fix is in green: a version on the map, and clients that refuse a stale one.

Second, schema migrations get harder. One ALTER TABLE is now 480 ALTER TABLEs that must all succeed. While they run, the fleet is on two different schema versions, so the application has to work with both. Figma listed schema changes as unsolved work even after its migration shipped, which shows how hard this is.

Third, the router is a new tier. It can be overloaded, it needs its own capacity planning, and its own tail latency adds to every query. Ask whether it should be a library inside the application rather than a network hop. The answer depends on how many programming languages your services are written in. Figma built DBProxy as a separate service. Plenty of teams put the routing logic in a shared client library and skip the hop.

If you memorise nothing else

factwhy it matters
Sharding splits your queries, not your datathe whole design follows from which queries carry the key
Adding shards divides the key space, not a keyone oversized tenant is immune to shard count, forever
Hashing balances the key space, not the traffica celebrity key defeats any hash function
One shard per machine costs 4x the hardwarerandom assignment is uneven; use many shards per machine
Consistent hashing with one ring point per node is 5x unevenvirtual nodes are not optional on a ring
id % N moves 97 percent of keys going 32 to 33use a fixed logical shard count and a lookup table
A 100 shard fanout needs each shard's p99.99 to have a p99fanout is the only operation that worsens as you scale
Gathering 200 keys over 100 shards touches 87 of thempast a point, scatter-gather is a fleet-wide broadcast
Resharding is mechanical, re-keying is a rewritespend your design time on the key, not the count
Prefix picks the machine, suffix picks the ordera single column shard key gives up ordered access for free
Never put a timestamp first in the key100 percent of writes land on one shard, by construction
Salted time keys want the fewest buckets, not the mostopposite of a hash key, because here the suffix is the query
Cassandra: 100 MB and 100k rows per partitionthe ceiling that forced Discord's (channel_id, bucket)
DynamoDB: 3,000 RCU and 1,000 WCU per partitiontable capacity cannot rescue a hot key
Notion: 500 GB per table, 10 TB per machine, 480 shards on 32 hostsa real operating envelope for sharded Postgres
Replication is not partitioningit buys availability and read throughput, and no write capacity

What is expected at each level

Mid-level

Know that sharding means splitting rows across machines by a key, and that it differs from replication. Be able to name hash and range partitioning and say what each is good at. Given a system, propose a plausible key and explain why requests already carry it.

You aren't expected to raise hot keys, virtual shard counts or the tail effect of fanout without prompting. You are expected to answer well when asked. Say the interviewer asks what happens when one customer is much bigger than the rest. "That shard is overloaded, and hashing won't help, because it's one key" is a good mid-level answer, and it's more than many candidates give.

The mistake to avoid is sharding by reflex. Calculate the data size and the write rate first, out loud, even if the answer is that you do need to shard.

Senior

You lead this part of the discussion, and three things must appear without anyone asking.

The query list before the key. List the access patterns with their rates. Then pick a key that serves the highest-rate ones, and say which queries you just broke and what happens to each. If you name a key without naming the queries it breaks, the interviewer can't tell your answer apart from a guess.

Skew, unprompted. Real distributions are heavy-tailed: a few keys are far bigger or busier than the rest. Say so before you're asked. Name which of the three kinds you have: a key that's too big, a key that's too busy, or a key with too many edges. They have different fixes, and mixing them up is a senior-level miss.

A fixed logical shard count, mapped to machines. Say the number, say it's frozen, and say why the mapping is a table. If you propose sharding directly onto machines, or id % N, that counts against you, because it's a mistake that can't be fixed later.

Disqualifying: proposing hashing as the answer to skew, and being unable to say what a cross-shard query costs.

Staff+

The question moves from producing a scheme to deciding how much of this you should do at all.

Name the ceiling, and the cheaper option you're skipping. The ceiling is storage, throughput, working set or maintenance time. Then say which of an index, a replica, a cache, a vertical split or single-machine partitioning you considered first, and why it doesn't close the gap. Sharding when you didn't have to is a more expensive mistake than sharding slightly late.

Separate the reversible decisions from the irreversible ones. The shard map is cheap to change. The logical shard count and the key are not. The count is easy to get right, because you just pick a large number with many factors. So spend your design attention on the key, and say so explicitly.

Price the fanout, in numbers. Give the shards touched, the requests per second multiplied out, and the tail arithmetic. If a query touches more than about a third of the fleet, propose a second copy keyed differently instead of a broadcast. Then say what that copy costs in extra writes and in staleness.

Question the idea that one data store answers everything. The transactional shard key and the analytical access pattern will never match. Send aggregates to a columnar store such as ClickHouse and full-text search to a search index such as Elasticsearch, and say how much staleness you're accepting on each. This move, more than any other, turns a struggling design into a clean one.

Design the migration, not just the target. Backfill, double write, verify, shift reads, retire. Say which phases can be reversed and why the verification phase can't be skipped. Anyone can draw the end state. The grade depends on how you get there while still serving traffic.

And be able to say what you would not build. Each of these can cost a team three months.

One is a general-purpose query router that supports any cross-shard join, when the answer was to keep joins on one key. Another is automated online resharding tools, built before anyone has resharded once by hand. A third is a consistent hash ring where a 480-row table would have been simpler to control.

Then there's a two-phase commit coordinator for a workflow that could have been co-located under one key. There's a global secondary index kept up to date synchronously, when seconds of staleness were fine and nobody asked for more. And there's the whole sharding project, when the real answer was one covering index and 18 more months on a single machine.

Sources

Every real-world figure in this article comes from a published engineering post, vendor documentation, or a paper, not from anecdote. Where a number is an assumption in a worked example, the article says so on the spot.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.