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 postsAppsaves new postsOne database, every post, FULLOne databaseevery postFULL
  • App — saves new posts — healthy
  • One database — every post — healthy — FULL
  1. One busy database. Every new post goes to one database, and it cannot keep up.
  2. Split into four. We split the data across four smaller databases, called shards, numbered 0 to 3.
  3. Hash the key. The router runs a hash function on the key u42 and gets 103,748,325.
  4. Keep the remainder. 103,748,325 divided by 4 leaves a remainder of 1, so u42 is stored on shard 1.
  5. Same key, same shard. Reading u42 later gives the same remainder, so the read goes straight to shard 1.
  6. Users spread out. Across 400 users, each shard ends up with between 89 and 112 of them.
  7. One hot user. If user 7 posts far more than anyone else, shard 1 gets the most writes and slows down.
  8. 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

  1. Each shard stores only some keys, so each one handles only part of the reads and writes.
  2. A hash function turns the key into a number, and the remainder after dividing by 4 picks the shard.
  3. Adding a fifth shard changes most remainders, so most data must move; consistent hashing moves far less.
  4. A very busy key still lands on one shard; salting spreads its writes, but reads must then check several.

Go deeper in the Sharding lab →

In plain words

Say one database takes every read and write for an app, and it cannot keep up. keeps full copies of the data on other servers, called replicas, and sends reads to them. splits the data instead: four servers, called shards, each store a quarter of the users. Each 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 , 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

Live simulationOpen the full lab →

Lab · Data

Replication

One primary database takes every write and copies it to two replicas. Replicas spread the read load and survive failures — but copying takes time. Explore stale reads, the latency cost of waiting for replicas, and what failover can lose.

Try it

Lab time 3.0 s
App (you), 1 writes/s · 2 reads/sApp (you)1 writes/s · 2 reads/sconfirmed likes: 5N1 · Primary, takes every write, PRIMARYN1 · Primarytakes every writelikes = 5PRIMARYN2 · Replica, lag 600 msN2 · Replicalag 600 mslikes = 3 · 2 behindN3 · Replica, lag 1.8 sN3 · Replicalag 1.8 slikes = 2 · 3 behind
About each part:
  • App (you) — 1 writes/s · 2 reads/s — healthy — confirmed likes: 5
  • N1 · Primary — takes every write — healthy — PRIMARY — likes = 5
  • N2 · Replica — lag 600 ms — healthy — likes = 3 · 2 behind
  • N3 · Replica — lag 1.8 s — healthy — likes = 2 · 3 behind
  • Request/response
  • Replication link
  • Write
  • Read
  • Copied change
  • Acknowledgement
  • Response
  • Stale data
  • Error / rejected
Confirmed writes
5
Write latency,
310 ms
Waiting for replicas
0
Stale reads
1
Problem: 33% of 3 reads
Went back in time
0
older than a version this reader already saw
Lost writes
0
after failover
Failed writes
0

Numbers add up:every replica's log is a prefix of the primary's (primary at offset 5); confirmed ≤ writtenThe lab checks this sum as it runs, so a counting mistake would show here.

Controls

Writes
Replication mode

The primary confirms the write at once. Replicas catch up in the background.

1/s
Reads
Read routing

Spreads reads, but a lagging replica returns old data.

2/s
Network & failures
600 ms
1.8 s

Click a database node to crash or recover it.

Each node's copy

  • N1 (primary)5
  • N23
  • N32

Bars show the number of writes applied. A shorter bar means that node would return an older value.

What just happened

  1. 1.1sWarning: Stale read from N3: returned 0 likes, but 2 were already confirmed.
  2. 0.0sInfo: N1 is the primary. N2 and N3 replicate from it.
What this model simplifies
  • The stored value is a simple counter so staleness is easy to see. Real replication ships row changes (or WAL records), but the timing behaves the same way.
  • Lag is a fixed delay per replica. Real lag varies with load, long transactions and network hiccups — it can spike from milliseconds to minutes.
  • Failover promotes the most up-to-date live replica after a fixed 2.5 s detection time. Real systems use health checks, consensus (e.g. Raft) or an operator to decide, and must fence the old primary so it cannot keep accepting writes.
  • Semi-synchronous mode here never falls back to async. MySQL, for example, falls back after a timeout — trading safety for availability.

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.

  1. 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 can take over.

  2. Copy now or copy later

    Pick a case to follow below

    With this case: The write took about 2 ms, but a confirmed order was lost when the primary crashed before copying it.

    App, reads and writesAppreads and writesPrimary, takes every write, NOWPrimarytakes every writehas order 81NOWReplica, a copy for readsReplicaa 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 4

    Step 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 has
    order 81
    takes every write
    Replica has
    no order 81
    Watch: behind the primary
    The write waited
    2ms
    round example times

    Step 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.

    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 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 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.

  3. Replication lag

    Pick a case to follow below

    With 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 writesAppreads and writesPrimary, takes every write, NOWPrimarytakes every writeSam LeeNOWReplica, a copy for readsReplicaa copy for readsSam
    • 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 3

    Step 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
    Clock
    0ms
    from the rename
    Primary has
    Sam Lee
    Replica has
    Sam
    Watch: 1,500 ms behind

    Step 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.

  4. Sharding

    Pick a case to follow below

    With this case: Each lookup touched one shard of 4: user 42 on shard 2, user 7 on shard 3.

    App, shard = user_id % 4Appshard = user_id % 4Shard 0, ids 0, 4…Shard 0ids 0, 4…Shard 1, ids 1, 5…Shard 1ids 1, 5…Shard 2, ids 2, 6…, NOWShard 2ids 2, 6…user 42NOWShard 3, ids 3, 7…Shard 3ids 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 2

    Step 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 asked
    1of 4
    the others do nothing

    Step 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.

  5. 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. , 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.

Replication and sharding side by side
QuestionReplicationSharding
What it doesCopies all the data to more serversSplits the data, so each server holds a part
What it helpsReads, and surviving a failed serverWrites and storage
New problemReplicas can lag behind the primaryQueries without the shard key ask every shard
Hard choiceFast writes or no lost writesThe 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

With asynchronous replication, the primary crashes right after confirming a write. What can happen?

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
  1. Too many keys. A busy app sees huge numbers of different user keys, and an exact count for each takes memory per key.
  2. A small grid instead. A count-min sketch keeps 3 rows of 6 counters, 18 numbers in all, however many keys arrive.
  3. One counter per row. For each event, 3 hash functions pick one counter per row for its key, and each goes up by 1.
  4. Read the smallest. To estimate u7's count, read its 3 counters, shown in brackets, and take the smallest.
  5. The hot key stands out. After 65 events, u7 reads 40, far above every other key, so it is the one to split.
  6. Never too low. Sharing counters can make a count too high: u4 reads 8, truly 3; other keys only ever add.
  7. 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

  1. The grid keeps no key names, so real systems also keep a short top-K list of the biggest keys.
  2. A count-min sketch keeps a small grid, here 3 rows of 6 counters, however many keys arrive.
  3. Each key bumps one counter per row; its estimate is the smallest of its counters.
  4. An estimate can be too high when keys share counters, but never too low.

Go deeper in the Sharding lab →

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 serviceOrder serviceID maker, machine 7ID maker, machine 7ID maker, machine 8ID maker, machine 8Orders tableOrders table
  • 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
  1. 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.
  2. Time comes first. After the sign bit, 41 bits count milliseconds since a chosen start date, so IDs sort roughly by time.
  3. Then the machine. The next 10 bits hold the machine number, so up to 1,024 machines never make the same ID.
  4. Then a counter. The last 12 bits count IDs within one millisecond on one machine: 0, 1, 2, up to 4,095.
  5. No talking needed. Each machine makes its IDs alone, with no shared counter that every order must wait for.
  6. Watch the clock. If a machine's clock jumps back, it could repeat an ID, so it waits until time catches up.
  7. 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

  1. 41 bits of milliseconds put IDs roughly in time order, for about 69 years.
  2. 10 bits of machine number keep two machines from making the same ID.
  3. A 12-bit counter allows 4,096 IDs per millisecond on each machine.
  4. 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

  • : during a , 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

Why is user_id often a better shard key than country?

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?

A user saves a new profile photo, reloads, and sees the old one. Reads go to replicas that copy the primary with a delay. What fixes this for that user?

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

Writes reach 8,000 a second, and the primary can take only 5,000. The team plans to add 3 more replicas. Will that help?

Apply it

Rows are placed with user_id % 4. You add a fifth shard and switch to user_id % 5. About what share of rows must move?

Judge a design

If replicas lose contact with the primary for 5 seconds, one of them promotes itself. Once, the old primary had only lost its network link, and it kept taking writes. What is wrong?

Next: consistent hashing, a way to add or remove a server while moving only a small share of the keys.

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.