Sharding, replication and consistent hashing

Lesson 3.6 · 10 min read · by Vinay C

We'll cover the following

Visual summary

Infographic summarizing Sharding, replication and consistent hashing: Your app took off. The database now holds more data than one disk can store, and the write traffic is more than one…

Download imageFree to share, please link back to this lesson.

The problem: one database is not enough

Your app took off. The database now holds more data than one disk can store, and the write traffic is more than one machine can absorb. A bigger machine only delays the problem. At some point you must spread the data over several machines.

There are two different tools for this, and mixing them up is a common interview mistake.

ShardingReplication
WhatSplit different data across machines. Each machine (a shard) holds a slice.Keep the same data on several machines (copies, also called replicas).
ScalesStorage and writes.Reads, and survival when a machine dies.
WeaknessLose a shard and that slice is gone (unless it is replicated).Every copy still holds all the data, so it does not help with a full disk.

Real systems do both: the data is split into shards, and each shard has a primary plus replicas. Shards are sized by data volume and load (say 500 GB to 1 TB each), not by record count. One billion small records might need only a handful of shards.

Three ways to decide which shard holds a record

StrategyHow it worksGoodBad
RangeEach shard owns a range of keys, e.g. names A-H, I-P, Q-Z, or dates by month.Range queries are cheap (all of March is on one shard).Uneven load. Many names start with S, and "today" always lands on the newest shard.
HashCompute hash(key) and map the result to a shard.Keys spread evenly, no hot ranges.Neighbouring keys end up on different shards, so range queries must ask every shard.
Directory (lookup)A small table says "key X lives on shard 7".Fully flexible. You can move one key at will.The lookup service is one more thing to run, keep fast and keep available.

Most large systems pick hash, because even load matters more than range scans. The next question is how to turn a hash into a server.

Why plain hash(key) % N is bad

The obvious answer is server = hash(key) % N, where N is the number of servers. It works until N changes. To keep the numbers readable, pretend the hash of each key is just the key itself. Here are keys 1 to 10 with 4 servers, then with 5:

key      1  2  3  4  5  6  7  8  9  10
% 4      1  2  3  0  1  2  3  0  1  2
% 5      1  2  3  4  0  1  2  3  4  0
moved?   -  -  -  X  X  X  X  X  X  X

3 of 10 keys stay, 7 of 10 move.

The divisor changed, so almost every answer changed. Over a large number of keys, going from 4 to 5 servers keeps only about 20% of keys in place and moves about 80%. If these servers are caches, nearly every lookup misses at once and the database behind them is flooded. If they are data shards, you must physically copy most of your data.

Consistent hashing, step by step

The fix is to stop tying a key to N. Instead, place both servers and keys on the same circle.

  1. Picture all hash values laid out on a ring, going from 0 up to the maximum and then wrapping back to 0.
  2. Hash each server's name to get its point on the ring.
  3. Hash each key to get its point on the ring.
  4. A key belongs to the first server found going clockwise from its point.

A small example with a ring numbered 0 to 99 and four servers:

servers: A=10  B=40  C=70  D=90

key at  5 -> clockwise: A (10)
key at 25 -> clockwise: B (40)
key at 55 -> clockwise: C (70)
key at 80 -> clockwise: D (90)
key at 95 -> wraps past 99 to 0, then A (10)

Add server E at 60:
  only keys between B(40) and E(60) change owner: the key at 55 moves C -> E.
  every other key stays where it was.

Server D dies:
  only D's keys move, to the next server clockwise.
  the key at 80 was on D (90); now it continues past 90 and wraps to A (10).

Adding a server takes over only the slice between itself and the previous server. With 4 servers going to 5, about 80% of keys stay and about 20% move, roughly 1/N. That is the mirror image of hash % N. When a server dies, only its keys move, to the next server clockwise.

Virtual nodes and replicas

With only a few points on the ring, bad luck can give one server a huge slice. The fix is virtual nodes: each physical server is hashed to many points (100 or more) spread around the ring. Slices become small and numerous, so load evens out. A new server also takes a little from everyone instead of a lot from one neighbour, and a bigger machine can simply be given more points.

For durability, store each key on its owner and the next 2 nodes clockwise (replication factor 3). In the example above, the key at 25 lives on B, then C, then D. If B dies, the data is still on two other nodes. (With virtual nodes, skip points that belong to a machine already holding a copy, so the three copies sit on three different machines.)

  • It applies to nodes that own data or cache: DB shards, Redis or memcached nodes, sticky routing. It is not needed for stateless API servers, because any server can handle any request.
  • With a cache, a dead node only costs the entries it held, which refill from the database. About 1/N of the keys are affected instead of everything.
  • Used by DynamoDB, Cassandra, memcached clients and CDNs.

How to choose the shard key

The shard key is the field you hash (or range-split) on. It matters more than the algorithm, because it decides which requests land on which shard. A good key has many distinct values and spreads traffic evenly. It also matches how you query, so most requests touch one shard.

DataShard keyResult
Usersuser_idSmooth. Millions of users, each with similar traffic, and a profile lookup hits one shard.
Tweetsuser_id of the authorHurts. A celebrity with 50M followers makes one shard a hot spot (this is the celebrity problem) while others idle.
Log entriesDateHurts. All of today's writes go to one hot current-day shard, and old shards sit idle.
Ordersorder_id (hashed)Even load. The cost: "all orders of one customer" now asks every shard.

Fixes for hot keys: pick a more random key (a tweet id instead of the author), add a suffix such as user_id + random(0..9) to split one hot key over several shards (reads must then gather from all ten), or use a compound key like date plus a hash bucket so each day spreads over many shards.

What sharding costs you

  • Cross-shard queries. A query that does not include the shard key must ask every shard and merge the answers. It is slower and one slow shard slows the whole query.
  • No easy joins. Rows that were one JOIN away may now sit on different machines. You denormalise, join in application code, or keep related data on the same shard by using the same key.
  • Transactions get hard. An update across two shards needs a distributed protocol such as a saga or two-phase commit.
  • Resharding. Adding shards later means moving data while serving traffic. Consistent hashing keeps the moved share near 1/N, but it is still real work. Start with more logical shards than machines, so you can move whole shards instead of splitting them.
  • More to operate. Backups, schema changes and monitoring now happen per shard.

This is why the usual advice is to shard last: use indexes, caching, read replicas and a bigger machine first.

Check yourselfYou run 4 cache servers with hash(key) % 4 and add a fifth. What happens, and what would you change?

Only about 20% of keys keep the same server, so about 80% of lookups miss at once and the database is flooded. Switch to consistent hashing with virtual nodes: adding a node then moves only about 1/N of the keys (about 20% here), and the rest stay warm.

Check yourselfYou store a chat app's messages. Someone suggests sharding by timestamp. What is wrong with it, and what would you use instead?

All new writes hit the newest shard, a hot spot, while old shards idle. Shard by conversation_id (hashed) instead: load spreads evenly and one conversation's messages stay on one shard. Watch for a very busy group chat becoming hot.

Summary: say it in the interview

  • "I shard by a high-cardinality key that matches my queries, and use consistent hashing with virtual nodes, so adding or removing a node only moves about 1/N of the keys."