Sharding, partitioning and consistent hashing

Replication copies the same data to many machines. It adds read capacity, but every write still goes to one leader. When one machine cannot hold the data or take the writes, you must split the data so that each machine owns a part. That split is called sharding. This lesson covers how to split, how to choose the key, how consistent hashing avoids moving everything when you add a machine, and what breaks once data lives in many places.

1. When You Need It

Sharding is the most expensive step on the scaling ladder, so do it last (the relational databases lesson lists the cheaper steps first). Reasons to shard are limits you can name with a number:

  • Writes: one relational primary takes about 5,000 to 20,000 writes per second.
  • Data size: a few TB on one node makes backups, restores and new replicas take hours.
  • Memory: the hot data no longer fits in the RAM of the largest affordable machine.
  • Throughput or connections: one machine's network or connection limit is reached.

Two words are often mixed up. Partitioning means splitting a table into smaller pieces. Sharding means placing those pieces on different machines. Partitions inside one database (for example, a PostgreSQL table split by month) help with maintenance and old data. Shards add capacity. Vertical splitting (different tables or services on different databases) is a third option, and it is cheap, but it stops helping once one table is too big.

2. How to Split

Strategy How it works Good Bad
Range Each shard owns a key range: A to F, G to M, and so on, or a date range Range queries touch few shards. Easy to understand Hot spots. With dates, all new writes hit the newest shard
Hash Shard = hash(key) mod number of shards Even spread of data and load Range queries touch every shard. Adding shards moves most keys (section 4)
Directory (lookup) A table stores which shard owns each key or tenant Full control. Move one tenant without moving others The lookup is another service to keep fast and available

HBase, Spanner and CockroachDB split a range automatically when it grows too big or too busy. So the real range problem is sequential keys, not fixed boundaries.

Geographic sharding (EU users on EU shards) is a directory or range rule based on location. It also helps with data residency laws.

3. Choosing the Shard Key

The shard key decides everything and is very hard to change later. Judge a key by four tests:

  • High cardinality: many different values. Country has 200 and will never spread across 500 shards.
  • Even load: no value gets far more traffic than the rest.
  • Matches your queries: the common query includes the key, so it goes to one shard and not to all.
  • Stable: the value never changes. If it does, the row must move shards.

Take an invoicing product for companies (multi-tenant). Compare three keys:

  • invoice_id (hashed): perfect spread. But "all invoices of company X" now touches every shard.
  • created_at (range): all new invoices go to one shard, a permanent hot spot.
  • tenant_id: the usual query is "this company's invoices", so it hits one shard, and a company's data and transactions stay together. The risk is one huge tenant.

The best answer is tenant_id, with a plan for large tenants: give a huge tenant its own shard (directory strategy), or use a compound key such as (tenant_id, invoice_id) for it so its data spreads over several shards.

3.1 Hot Shards and Hot Keys

Even with a good key, one value can be far busier than the rest, such as an account with 50 million followers or a product in a flash sale. The shard that owns it overloads while the others are idle. Fixes:

  • Cache the hot reads.
  • Split the hot key by adding a suffix: write counts for a hot item to item42#0 to item42#9 (10 keys on different shards) and add them up when reading. Writes spread out. Reads cost 10 lookups.
  • Isolate the hot tenant or key on its own shard.

4. The Problem with Hash Mod N

The simplest hash rule is shard = hash(key) % N. It works until N changes. Going from 4 shards to 5, a key stays on the same shard only when h % 4 == h % 5, which is true for just 20% of keys. 80% of the data must move. In general, going from N to N+1 shards moves N/(N+1) of the keys. During the move, the cache is cold and the databases are busy copying. Adding capacity should not cause an outage.

5. Consistent Hashing

Consistent hashing moves only a small part of the keys when a node joins or leaves.

  1. Imagine a circle of hash values, say 0 to 99 (real systems use 0 to 264).
  2. Place each node on the circle at the hash of its name.
  3. Hash each key onto the same circle, then walk clockwise to the first node. That node owns the key.
Nodes: A at 20, B at 50, C at 80
Key at 35 -> clockwise -> B.   Key at 90 -> wraps around -> A.

Add node D at 65:
Only keys between 50 and 65 move, from C to D.
Every other key stays where it was.
flowchart LR
    A["Node A at 20"] --> K1(["key at 35"]) --> B["Node B at 50"] --> K3(["key at 58"]) --> D["New node D at 65"] --> C["Node C at 80"] --> K2(["key at 90"]) -- "wraps past 99 to 0" --> A
    classDef key fill:#f1f3f5,stroke:#868e96
    classDef newnode fill:#fde2e2,stroke:#c53030
    class K1,K2,K3 key
    class D newnode

Read the line from left to right as the circle, and follow the arrows clockwise. Each key belongs to the first node it reaches. Key 35 goes to B, and key 90 wraps around to A. Before D joined, key 58 belonged to C. Now D owns it. No other key changed owner.

When a node is added, it takes keys only from its clockwise neighbor. When a node dies, its keys go to the next node. When you add one node to N nodes, about 1/(N+1) of the keys move, not N/(N+1) of them.

5.1 Virtual Nodes

With one point per node, the arcs are uneven and one node may get twice the load of another. The fix is virtual nodes: each physical node appears at many points on the circle (from about 16 to 256 in practice). Load then evens out to within roughly 10%. A new node takes a little from every existing node, which spreads the copying load. A bigger machine can get more virtual nodes than a smaller one.

flowchart LR
    A1["A1"] --> B1["B1"] --> D1["D1 new"] --> C1["C1"] --> A2["A2"] --> C2["C2"] --> D2["D2 new"] --> B2["B2"] --> A3["A3"] --> D3["D3 new"] --> B3["B3"] --> C3["C3"] --> A1
    classDef a fill:#cfe2ff,stroke:#2b6cb0
    classDef b fill:#d4edda,stroke:#2f855a
    classDef c fill:#ffe5b4,stroke:#c05621
    classDef d fill:#fde2e2,stroke:#c53030
    class A1,A2,A3 a
    class B1,B2,B3 b
    class C1,C2,C3 c
    class D1,D2,D3 d

In the diagram, each server has three points (A1 to A3, B1 to B3, C1 to C3), mixed around the circle. When server D joins with its own three points, each point takes a small slice from whichever node comes next: D1 from C1, D2 from B2, D3 from B3. So D receives a little data from several servers at once. The copying is spread out, and no single server carries the whole move. With one point per server, D would take everything from just one neighbor. The same mixing keeps the load even as nodes come and go.

For replication, the key is also stored on the next few distinct nodes clockwise, which is how Dynamo-style stores such as Cassandra place copies.

5.2 Fixed Partitions: The Common Alternative

Many systems skip the ring and use a simpler idea: create many more small partitions than nodes, and assign whole partitions to nodes. The key goes to a partition with hash(key) % number of partitions, and that number never changes. Adding a node means moving some whole partitions to it.

  • Redis Cluster has 16,384 hash slots, assigned to nodes.
  • Elasticsearch fixes the number of primary shards when you create the index. In Kafka, keys map to partitions, so changing the partition count later remaps keys.
  • A common plan for your own system: 1,024 logical partitions over 8 servers, 128 each. To grow to 16 servers, move 512 partitions. No key is ever re-hashed.

6. Finding the Right Shard

Someone must map a key to a shard. There are four common places:

  • In the client library (the app knows the ring or the slot map). Fast, but every app must be updated when the map changes.
  • In a proxy or router (Vitess, MongoDB's mongos). One place to change, one more hop.
  • Any node forwards. The client asks any node, and it redirects to the owner (Redis Cluster's MOVED, Cassandra's coordinator).
  • A config service such as ZooKeeper or etcd that stores the map and tells everyone when it changes.

7. What Gets Harder

  • Queries without the shard key go to all shards (scatter-gather). The answer takes as long as the slowest shard, and the tail latency adds up (see the tail latency example in the Numbers lesson).
  • Joins across shards are slow or unsupported. Design so that data that is joined shares a key, or copy small reference tables to every shard.
  • Transactions across shards need two-phase commit or sagas (see the distributed transactions lesson). Keep a transaction inside one shard when you can.
  • Secondary indexes. A local index covers one shard, so a lookup by that field asks every shard. A global index is split by the indexed value, so the lookup goes to one shard, but writes touch two shards.
  • Unique IDs and counters. A database sequence on each shard produces duplicates across shards. Use globally unique IDs (see the ID generation lesson).
  • Operations. Backups, schema changes and monitoring multiply by the number of shards.

7.1 Resharding Without Downtime

Sooner or later, you add shards. The safe way:

  1. Copy a snapshot. Copy the data for the moving range to the new shard. The old shard keeps serving users, and the copy can take hours.
  2. Catch up. Users keep writing to the old shard during the copy, so the snapshot is already out of date when it finishes. Read the old shard's change log (the same log replication uses) and apply every change made since the snapshot to the new shard. Repeat until the new shard is only a moment behind.
  3. Verify. Compare counts or checksums.
  4. Switch. Pause writes to that range for a few seconds so the last changes reach the new shard, switch the routing to the new shard, then delete the old copy.

Move a small range at a time, and be able to roll back. With fixed partitions, each move is one whole partition.

8. Worked Example: How Many Shards?

The invoicing product has 50,000 writes per second at peak and 6 TB of data. Peak is about 4 times the average, so the average is 12,500 writes per second, which is about 1.1 billion writes a day. Assume a primary should stay at 70% of 10,000 writes per second, and a shard should hold under 2 TB.

  • Writes: 70% of 10,000 = 7,000 per shard. 50,000 ÷ 7,000 = 7.1, so 8 shards.
  • Data: 6 TB ÷ 2 TB = 3 shards.
  • Result: writes decide, so at least 8. Leave room to grow and choose 16 shards, 2 times the minimum, with about 375 GB of data per shard today. Use the flip-point method from the estimation lesson to know when to add more.
  • Machines: each shard is a leader plus 2 replicas, so 16 × 3 = 48 database nodes.
  • Plan: shard by tenant_id, 1,024 fixed partitions assigned to 16 shards (64 each), and a directory entry for the biggest tenants.

9. Common Pitfalls

  • Sharding too early. Try indexes, caching, replicas and a bigger machine first.
  • A bad key: low cardinality, a growing timestamp, or one that your main query does not use.
  • Hash mod N with changing N. Use consistent hashing or fixed partitions.
  • No plan for hot keys or huge tenants.
  • Forgetting cross-shard work: joins, transactions, global unique constraints.
  • Resharding by hand, all at once. Move small ranges, with verification and rollback.
  • Too few partitions. If you fix the count at 16 and later need 64 servers, you must re-hash everything. Start with many more partitions than nodes.

10. Interview Questions This Lesson Prepares You For

  • When do you shard, and how does it differ from replication? Shard when writes, data size or memory exceed one machine. Replication copies the same data for reads and availability. Sharding splits different data across machines for capacity.
  • How do you choose a shard key? High cardinality, even load, matches the main query, and does not change. Then say what query goes to all shards and how you handle it.
  • What is wrong with hash(key) % N? Changing N moves almost all keys (80% when going from 4 to 5). That causes a cold cache and heavy copying.
  • Explain consistent hashing and virtual nodes. Nodes and keys sit on a ring, and a key belongs to the next node clockwise. Adding a node to N nodes moves only about 1/(N+1) of the keys. Virtual nodes (many points per server) even out the load.
  • How do you handle a hot key? Cache it, split it with a suffix and sum on read, or give it its own shard.
  • How many shards do you start with? Compute from writes (at 70% of one primary's limit) and from data size, and take the larger. Add room to grow and round to a power of two. Use many more fixed partitions than shards.
  • How do you add shards with no downtime? Copy a small range, stream catch-up writes, verify, switch routing, delete the old copy. Fixed partitions make each move one whole partition.