Stage 3 · Distributed data · Medium · 24 min
Replication and sharding
Replicas are copies of a database that share the reads. Shards split the data so writes are shared too. Learn what each one fixes and the new problems it brings.
What each interview level is expected to know
Learn first: Choosing a database and modelling data
After this lesson you can:
- Explain what replicas fix and what shards fix.
- Predict when a user reads an old value because of replication lag.
- Spot a hot shard and a split brain, and say how writes can be lost on failover.
Start here
See it in 60 seconds
How a shard is chosen
Sharding splits one busy database into smaller ones, called shards, and a rule on each key picks the one shard that stores it.
Scene 1 of 7 · One busy database
Every new post goes to one database, and it cannot keep up.
- App — saves new posts — healthy
- One database — every post — healthy — FULL
- One busy database. Every new post goes to one database, and it cannot keep up.
- Split into four. We split the data across four smaller databases, called shards, numbered 0 to 3.
- Hash the key. The router runs a hash function on the key u42 and gets 103,748,325.
- Keep the remainder. 103,748,325 divided by 4 leaves a remainder of 1, so u42 is stored on shard 1.
- Same key, same shard. Reading u42 later gives the same remainder, so the read goes straight to shard 1.
- Users spread out. Across 400 users, each shard ends up with between 89 and 112 of them.
- One hot user. If user 7 posts far more than anyone else, shard 1 gets the most writes and slows down.
- Now you try. Pick a user ID from 1 to 400 and see which shard stores it. For example: User 42 has the key u42, so it is stored on shard 1. hash(u42) = 103,748,325, and dividing that by 4 leaves 1. The Sharding lab uses this same rule.
Scene 1 of 7: One busy database. Every new post goes to one database, and it cannot keep up.
Key points
- Each shard stores only some keys, so each one handles only part of the reads and writes.
- A hash function turns the key into a number, and the remainder after dividing by 4 picks the shard.
- Adding a fifth shard changes most remainders, so most data must move; consistent hashing moves far less.
- A very busy key still lands on one shard; salting spreads its writes, but reads must then check several.
In plain words
Say one database takes every read and write for an app, and it cannot keep up. (Continuously copying every write from a primary database to one or more replicas, so each one ends up with the same data.) keeps full copies of the data on other servers, called replicas, and sends reads to them. (Splitting one database's data into parts and keeping each part on a different machine. Each part is called a shard.) splits the data instead: four servers, called shards, each store a quarter of the users. Each (One slice of a database. Each shard holds part of the data on its own machine.) then handles only its own share of the load.
Each fix has its own catch. Replicas copy the writes a fraction of a second late, and later under heavy load. That gap, called (How far behind a replica is: the time between a write on the primary and that same write showing up on the replica.), means a user might not see their own last change. Shards need a key that decides where each row lives. A poor key, such as the current time, sends almost every new write to the same shard.
The problem it solves
A single database server runs out in three ways. Reads pile up until queries wait. Writes arrive faster than one disk can save them. Or the data grows past what one machine can hold. A bigger machine delays each limit, but does not remove it.
Why it matters
One database server has a limit on reads, on writes and on disk. Replication raises the read limit and keeps a spare copy ready. Sharding raises the write and storage limits. Most large systems use both, so a design must say where each applies.
A worked example
A single primary database serves 3,000 reads a second. Adding 2 read replicas, each able to serve 3,000 reads a second, adds 2 × 3,000 = 6,000 more reads a second. Total read capacity then reaches 3,000 + 6,000 = 9,000 reads a second. Sharding instead helps writes: it splits a 20 TB dataset across 5 shards. Each shard then holds about 20 ÷ 5 = 4 TB, small enough to fit on one machine's disk.
Think of it like…
Think of a library. Replication buys extra copies of the same books, so more people can read at once. Sharding splits the collection: A to M in one branch, N to Z in another.
Where this analogy stops working
More copies for readers, and a split for size, is the useful part. But a printed book never changes. A database row does, and each change takes time to reach every copy. A reader can get the old value from a copy that is behind. A question that spans both branches must ask both.
Try it
See it working
Also try: Sharding · Consistent hashing · IDs: from auto-increment to UUIDs and Snowflake
Mechanics
How it works
One database server has limits: how many reads it can answer, how many writes it can take, and how much it can store. Replication copies the data to more servers, which helps with reads and with failures. Sharding splits the data across servers, which helps with writes and storage. The pictures below show each one and the problem it brings.
Primary and replicas
One database server, the primary, takes every write. It sends each change to copies called replicas, which serve reads. With three replicas, reads spread across four servers. If the primary fails, a (A copy of a database kept on another machine.) can take over.
Copy now or copy later
Pick a case to follow belowWith this case: The write took about 2 ms, but a confirmed order was lost when the primary crashed before copying it.
App, reads and writes App reads and writes Primary, takes every write, NOW Primary takes every write has order 81 NOW Replica, a copy for reads Replica a copy for reads - App — reads and writes — healthy
- Primary — takes every write — healthy — NOW — has order 81
- Replica — a copy for reads — healthy
- Write
- Confirmed
Step 1 of 4Step 1 of 4 · Primary
Done: The app writes order 81 to the primary
- What happens
- A customer pays, and the app saves order 81. Every write goes to the primary.
- Why
- One server takes all the writes, so there is one place that decides the order of changes.
- What changes
- The primary has order 81. The replica does not, yet.
- Next
- The primary confirms the write
Primary hasorder 81takes every writeReplica hasno order 81Watch: behind the primaryThe write waited2msround example timesStep 1 of 4: Primary. The app writes order 81 to the primary. A customer pays, and the app saves order 81. Every write goes to the primary.
(A widely used open-source SQL database.) and MySQL copy changes asynchronously by default: the primary confirms a write first and sends it to the replicas after. In the picture, a customer places order 81, and then the primary crashes. Switch between the two ways of copying.
With (Replying right away, without waiting for another step to finish. That step is done later, by itself.) copying, the write waits only for the primary, about 2 ms here. But the primary crashes before it sends the copy. The replica takes over without order 81, although the customer was told the order was placed.
With (Waiting for another step to finish before confirming, instead of moving on right away.) copying, the primary waits until the replica confirms it has the change. The write takes about 5 ms instead of 2 ms, but the crash loses nothing: the new primary already has order 81.
Many systems take a middle path. The primary waits for one replica and copies to the others later. Each write pays for one extra trip, and a confirmed write survives the loss of the primary, as long as that replica survives too.
Replication lag
Pick a case to follow belowWith this case: The user saw "Sam" 200 ms after renaming, because the replica was 1,500 ms behind. Nothing was lost; the read was too early.
App, reads and writes App reads and writes Primary, takes every write, NOW Primary takes every write Sam Lee NOW Replica, a copy for reads Replica a copy for reads Sam - App — reads and writes — healthy
- Primary — takes every write — healthy — NOW — Sam Lee
- Replica — a copy for reads — healthy — Sam
- Write
- Old value
- Copied change
Step 1 of 3Step 1 of 3 · Primary
Done: A user changes their name to Sam Lee
- What happens
- The app writes the new name to the primary, which confirms it.
- Why
- Writes always go to the primary.
- What changes
- The primary has "Sam Lee". The copy to the replica is on its way, 1,500 ms in this example.
- Next
- 200 ms later, the user reloads and sees the old name
Clock0msfrom the renamePrimary hasSam LeeReplica hasSamWatch: 1,500 ms behindStep 1 of 3: Primary. A user changes their name to Sam Lee. The app writes the new name to the primary, which confirms it.
A copy takes time to reach a replica, often milliseconds but sometimes seconds. In the picture, the replica is 1,500 ms behind. A user renames their profile, then reloads the page 200 ms later.
If the reload reads from the replica, the user sees their old name. Nothing is lost: the change reaches the replica at 1,500 ms. But to the user, it looks as if their change failed.
The second case shows a common fix, called read-your-own-writes. For 5 seconds after a user writes, that user's reads go to the primary. They see their change at once, and everyone else keeps reading from the replicas.
The rule only needs to last about as long as the lag usually does. Send too many reads to the primary, and you lose the reason for having replicas.
Sharding
Pick a case to follow belowWith this case: Each lookup touched one shard of 4: user 42 on shard 2, user 7 on shard 3.
App, shard = user_id % 4 App shard = user_id % 4 Shard 0, ids 0, 4… Shard 0 ids 0, 4… Shard 1, ids 1, 5… Shard 1 ids 1, 5… Shard 2, ids 2, 6…, NOW Shard 2 ids 2, 6… user 42 NOW Shard 3, ids 3, 7… Shard 3 ids 3, 7… - App — shard = user_id % 4 — healthy
- Shard 0 — ids 0, 4… — healthy
- Shard 1 — ids 1, 5… — healthy
- Shard 2 — ids 2, 6… — healthy — NOW — user 42
- Shard 3 — ids 3, 7… — healthy
- Read
Step 1 of 2Step 1 of 2 · Shard 2
Done: The app finds user 42 on shard 2
- What happens
- 42 % 4 = 2, so user 42 lives on shard 2. The app asks that shard only.
- Why
- The shard key, user_id, decides where each user's rows live. Anyone can do the sum.
- What changes
- One shard of 4 did the work.
- Next
- The app finds user 7 on shard 3
Shards asked1of 4the others do nothingStep 1 of 2: Shard 2. The app finds user 42 on shard 2. 42 % 4 = 2, so user 42 lives on shard 2. The app asks that shard only.
What these pictures simplify. These pictures use one replica, four shards and round example times. Real lag depends on load and distance. In the shard picture, the hash of an id is the id itself, so the sums stay easy to check. A real system hashes the id first, so neighbouring ids spread out.
When writes or data outgrow one server, split the data across several, called shards. A shard key decides where each row lives. In the picture, shard = user_id % 4, so each user lives on one of 4 shards.
To find user 42, the app does the sum: 42 % 4 = 2. It asks shard 2 only, and the other three do no work. Each user lands on one shard, so the load spreads across all four.
Now pick the second case. The app needs the user with a given email, but the shard key is the user id. It cannot tell which shard holds that email, so it asks all four. One query has become four.
So choose the shard key from your most common queries. For the email lookup, a second table keyed by email can store each user's id. The lookup then reads that table, then one shard.
Hot shards and resharding
One very popular user can send far more traffic to a shard than the others get. That is a hot shard. One fix is to give such users their own shard. Also, with hash(user_id) % 4, changing 4 to 5 moves most rows. (A way to spread keys across servers so that when one server joins or leaves, only a small share of keys move.), the next concept, moves far fewer.
You can check the second claim with small numbers. Take user ids 1 to 20. Only ids 1, 2, 3 and 20 give the same answer for % 4 and % 5. So 16 of the 20 users move to a new shard.
| Question | Replication | Sharding |
|---|---|---|
| What it does | Copies all the data to more servers | Splits the data, so each server holds a part |
| What it helps | Reads, and surviving a failed server | Writes and storage |
| New problem | Replicas can lag behind the primary | Queries without the shard key ask every shard |
| Hard choice | Fast writes or no lost writes | The shard key, and moving data when shards are added |
Use it when
- Replicas: reads are more than one server can answer, or you need a copy ready to take over if the primary fails.
- Shards: writes or data have outgrown the largest server you can sensibly run. Try a bigger machine, caching and replicas first, because sharding is hard to undo.
Skip it when
- Data and traffic that one well-sized database server handles: sharding adds routing, cross-shard queries and harder schema changes for no gain.
- Replicas for data that must be current on every read, such as an account balance: a replica can be behind. Read those from the primary.
Check yourself
Also
More in 60 seconds
Finding the hot key
A count-min sketch counts a stream of keys in a few small counters, so you can find the hot key without exact counts.
Scene 1 of 6 · Too many keys
A busy app sees huge numbers of different user keys, and an exact count for each takes memory per key.
- Events counted
- 0
- Estimated count
- not shown yet
- Too many keys. A busy app sees huge numbers of different user keys, and an exact count for each takes memory per key.
- A small grid instead. A count-min sketch keeps 3 rows of 6 counters, 18 numbers in all, however many keys arrive.
- One counter per row. For each event, 3 hash functions pick one counter per row for its key, and each goes up by 1.
- Read the smallest. To estimate u7's count, read its 3 counters, shown in brackets, and take the smallest.
- The hot key stands out. After 65 events, u7 reads 40, far above every other key, so it is the one to split.
- Never too low. Sharing counters can make a count too high: u4 reads 8, truly 3; other keys only ever add.
- Now you try. Pick a key, and compare the sketch's estimate with its true count. For example: u4: the sketch says 8, but the true count is 3, 5 too high. Every one of its counters also counts another key, so even the smallest is too high.
Scene 1 of 6: Too many keys. A busy app sees huge numbers of different user keys, and an exact count for each takes memory per key.
Key points
- The grid keeps no key names, so real systems also keep a short top-K list of the biggest keys.
- A count-min sketch keeps a small grid, here 3 rows of 6 counters, however many keys arrive.
- Each key bumps one counter per row; its estimate is the smallest of its counters.
- An estimate can be too high when keys share counters, but never too low.
Unique IDs without a shared counter
A Snowflake ID packs time, a machine number and a counter into one 64-bit number, so 1,024 machines each make unique IDs alone.
Scene 1 of 6 · Every order needs an ID
Each new order needs a unique ID: one number, 64 bits or 8 bytes long, that no other order has.
- Order service — healthy
- ID maker, machine 7 — healthy
- ID maker, machine 8 — healthy
- Orders table — healthy
- IDs made this millisecond
- not shown yet
- Waiting for a later millisecond
- not shown yet
- Every order needs an ID. Each new order needs a unique ID: one number, 64 bits or 8 bytes long, that no other order has.
- Time comes first. After the sign bit, 41 bits count milliseconds since a chosen start date, so IDs sort roughly by time.
- Then the machine. The next 10 bits hold the machine number, so up to 1,024 machines never make the same ID.
- Then a counter. The last 12 bits count IDs within one millisecond on one machine: 0, 1, 2, up to 4,095.
- No talking needed. Each machine makes its IDs alone, with no shared counter that every order must wait for.
- Watch the clock. If a machine's clock jumps back, it could repeat an ID, so it waits until time catches up.
- Now you try. How many IDs does machine 7 get asked for in the same millisecond? For example: 4,096 get an ID now. The other 904 wait: 904 in the next millisecond. The counter has 12 bits, so it stops at 4,095 and starts again at 0 in the next millisecond.
Scene 1 of 6: Every order needs an ID. Each new order needs a unique ID: one number, 64 bits or 8 bytes long, that no other order has.
Key points
- 41 bits of milliseconds put IDs roughly in time order, for about 69 years.
- 10 bits of machine number keep two machines from making the same ID.
- A 12-bit counter allows 4,096 IDs per millisecond on each machine.
- A clock that jumps back could repeat an ID, so the machine must wait.
Judgement
Trade-offs and how it fails
What you give up
- Throughput
- Each replica adds read capacity, but every write still goes through one primary. Each shard adds write and storage capacity, as long as the load spreads evenly across the shards.
- Complexity
- A join across shards is slow, and some systems do not allow it. A schema change must be run on every shard, which needs tooling.
Failure modes
- (Two servers or regions each believe they are the leader, and both accept writes at once. It usually happens during a network partition.): during a (Switching to a backup, such as promoting a replica to primary, after the original one fails.), the old primary and the new one both accept writes for a while. Their data then disagrees, and some writes may be lost.
- A hot shard: a poor shard key, or one very busy user, sends most of the traffic to one shard. That shard slows down while the others sit idle.
- Writes lost on failover: with asynchronous replication, the primary can fail before a replica has its latest writes. Those writes are gone when the replica takes over.
In the real world
- YouTube built Vitess, a layer that shards MySQL and routes each query to the right shard. It is now open source.
- Instagram's engineering blog (2011) describes 64-bit ids, made inside PostgreSQL, that carry a shard number.
Trade-offs to be ready to discuss: Sharding vs partitioning · Sync vs async replication
Check yourself
Interview
What interviewers look for
- Name the shard key and the reason: "I shard by user id, so each user's data sits on one shard."
- Say why a timestamp is a poor shard key: every new write carries the current time, so they all land on the newest shard.
- Bring up replication lag before you are asked. "After a user writes, I read from the primary for a few seconds, so they see their own change."
Say it out loud: What happens if you shard by ranges of a timestamp, for example one shard per month?
Expected depth by interview level
Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.
- JuniorUseful
- Replicas for reads and backups; sharding at a high level.
- MidCore
- Read replicas, replication lag, choosing a shard key.
- SeniorCore
- Hot shards, resharding, failover and read-your-writes.
- StaffCore
- Partitioning strategy for a whole data platform.
Practice
Apply it
Three harder questions
The first two use the idea on a new case. The last asks you to judge a design.
Apply it
Apply it
Judge a design
Go deeper
Sources and further reading
First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsHigh Availability, Load Balancing, and ReplicationPostgreSQL documentationSynchronous and asynchronous replicas, failover, and what each costs.
- Official docsShardingMongoDB documentationShard keys, ranged and hashed sharding, and why a bad key makes a hot shard.
- BookDesigning Data-Intensive ApplicationsMartin Kleppmann (O’Reilly)Chapters 5 and 6: replication lag and its effects, then partitioning and rebalancing.