Skip to content

Lesson 7 of 38Building blocks

Replication and Sharding

Copy data for availability and read scale, split it across machines for write scale, avoid hot shards, and reshard without downtime.

25 min read0/8 questions

Eventually one database server is not enough. Either it cannot survive a crash without downtime, it cannot keep up with reads, or the data and writes outgrow any single machine. Replication (copies of the same data) solves the first two. Sharding (splitting the data into pieces) solves the third. Every large system uses both, and interviewers expect you to know the costs that come with each.

Leader-follower replication

The most common setup has one leader (also called the primary) and several followers (replicas, secondaries). All writes go to the leader. The leader streams its change log to the followers, and they apply the same changes in the same order. Reads can go to any copy.

Leader-follower replication
App serversApp serversLeader: writesLeaderwritesFollower 1: readsFollower 1readsFollower 2: readsFollower 2readsINSERTWAL streamWAL streamSELECTSELECT

A write (INSERT INTO posts ...) always goes to the leader, which commits it and replies.

1/5

Replication buys you:

  • Availability: if the leader dies, promote a follower in seconds (managed databases like Amazon RDS Multi-AZ or Aurora do this automatically).
  • Read scaling: add followers to serve more reads.
  • Locality: a follower in Europe serves European reads with low latency.

It does not help write throughput: every follower still applies every write.

Replication lag and how to live with it

With asynchronous replication, followers are slightly behind. Usually that is milliseconds, but a heavy batch job can push it to seconds or minutes. The common symptom is a user saving their profile, refreshing, and seeing the old version. Fixes:

  • Read your own writes from the leader: for a few seconds after a user writes, route that user's reads to the leader.
  • Read from the leader for anything the user just changed (their own profile), and from followers for everyone else's data.
  • Track the replication position: after a write, remember its log position, and only read from a follower that has caught up to it.
Quick check
Users edit their bio, get redirected to their profile page, and sometimes see the old bio. Profile reads go to read replicas. What is the most targeted fix?
Need a nudge? A hint rules out a wrong answer.

Synchronous, asynchronous, and semi-synchronous

The diagram above used asynchronous replication: the leader commits, replies to the client, and ships the change afterwards. The alternative modes decide when the leader is allowed to say "committed".

ModeLeader replies afterWrite latencyIf the leader diesAvailability risk
AsynchronousIts own local commitLowestRecent writes not yet shipped are lostNone from followers
SynchronousEvery synchronous follower confirmsHighest; the slowest follower sets the paceNo acknowledged write is lostOne slow or dead follower stalls all writes
Semi-synchronousAt least one follower has received the changeMediumAcknowledged writes exist on two machinesFalls back to async on timeout, quietly

Fully synchronous replication to every follower is rare, because one sick follower stops all writes. What teams run is a middle ground:

  • Postgres lets you list standbys in synchronous_standby_names, including quorum forms like ANY 1 (s1, s2): the commit waits for any one of the two. Combined with synchronous_commit you choose how far that standby must get (received, flushed, or applied).
  • MySQL semi-sync makes the source wait until at least one replica has written the change to its relay log. If no replica answers within a timeout (rpl_semi_sync_source_timeout, 10 seconds by default), it falls back to async and keeps going. That keeps writes available, but during exactly the window when replicas are struggling, you have lost the durability you thought you had. Monitor for it.
  • Amazon Aurora moves the problem into storage: every write goes to six copies across three availability zones and is durable once four confirm, so the database instances do not replicate data pages to each other.

The framing to use at work is RPO (recovery point objective: how much recent data you can afford to lose) and RTO (recovery time objective: how long you can be down). Async gives you an RPO of "whatever lag was at the moment of failure". Synchronous replication to at least one standby in another zone gives an RPO of zero for a single failure, and costs a cross-zone round trip on every commit.

Quick check
Your MySQL primary uses semi-sync replication. During a network problem, replicas stop acknowledging for 30 seconds, then the primary crashes. What can be lost?
Need a nudge? A hint rules out a wrong answer.

Replication lag anomalies

Lag causes three distinct bugs, and naming them precisely helps you pick the fix. The Consistency and CAP lesson covers the guarantees in depth; here is how each shows up in a replicated database.

  1. Missing your own write (read-your-writes violated): covered above.
  2. Time going backwards (monotonic reads violated): your first read hits a replica that is 50 ms behind, your second hits one that is 900 ms behind. You saw a comment, now you do not. Fix it by pinning each user's reads to one replica.
  3. Effect before cause (consistent prefix violated): you see an answer before the question it replies to. This happens when related writes land on different shards or partitions that replicate independently. Fix it by keeping causally related writes in the same partition (all messages of one conversation on one shard), or by carrying ordering metadata.

Measure lag instead of guessing it. In Postgres, pg_stat_replication on the primary shows each standby's replay_lag. In MySQL, SHOW REPLICA STATUS reports Seconds_Behind_Source. Alert when it crosses what your read-your-writes window assumes.

Predict the outputPython

A comment is written at t = 100 ms. Replica A applies it after 50 ms of lag, replica B after 900 ms. A user refreshes three times. What prints?

COMMENT_WRITTEN = 100
lag = {"a": 50, "b": 900}
for now, replica in [(200, "a"), (400, "b"), (1200, "b")]:
  seen = now >= COMMENT_WRITTEN + lag[replica]
  print(replica, "yes" if seen else "no")
Need a nudge? Hints walk you through it.

Multi-leader and leaderless, briefly

Multi-leader replication lets several nodes (often one per region) accept writes and sync with each other. Writes are fast everywhere, but two regions can change the same row at once, and you need conflict resolution (last write wins, merging, or app logic). It suits collaborative apps and multi-region setups where conflicts are rare.

Leaderless replication (Cassandra, Riak, and the original Dynamo design) sends each write to several replicas directly and considers it done when enough of them acknowledge. There is no failover because there is no leader. The consistency lesson covers the quorum math that makes it work.

Multi-leader in more depth

Multi-leader setups are mostly about regions. Each region has a leader that accepts local writes with local latency, and leaders replicate to each other asynchronously. The pain is conflicts, and the best conflict is one that never happens. The standard trick is conflict avoidance: give every record a home region (a user's account is written only in the region they signed up in, or where they are now), so two leaders rarely touch the same row. When a conflict does happen, you need one of the resolution rules from the Consistency and CAP lesson: last write wins, keeping siblings, or a CRDT.

Watch the topology too. With an all-to-all topology, a change can arrive at one leader before an earlier change it depends on, so updates to a row can show up before the insert that created it. Circular and star topologies avoid that but stop replicating if one node in the chain fails.

Inside leaderless replication: repair, sloppy quorums, hinted handoff

Leaderless stores (Cassandra, ScyllaDB, Riak, and the design in Amazon's 2007 Dynamo paper) have no leader to bring a lagging replica up to date, so they repair themselves in three ways:

  • Read repair: when a quorum read sees replicas disagree, the coordinator writes the newest value back to the stale ones. Hot keys get repaired quickly; rarely read keys may stay stale.
  • Anti-entropy: a background process compares replicas and copies missing data. Cassandra's repair compares Merkle trees (trees of hashes over ranges of data), so two replicas can find the few ranges that differ without sending everything.
  • Hinted handoff: if a replica is down during a write, another node stores a hint ("this write belongs to node C") and delivers it when C returns.

A sloppy quorum goes one step further. If too few of a key's usual replicas are reachable, the write is accepted by other healthy nodes, which hold it with hints. Writes stay available during failures, but R + W > N no longer guarantees overlap, because the W nodes that took the write may not be the ones a later read asks. Dynamo used sloppy quorums for availability. Cassandra stores hints but does not count them toward the consistency level (except at level ANY), so its quorums stay strict.

Note that Amazon DynamoDB, the managed service, is not leaderless despite the name: each partition has a leader replica elected with Paxos, which is how it offers strongly consistent reads.

Sharding: splitting the data

When writes or data size outgrow one leader, you partition the data: each shard is a separate database holding a subset of the rows, and each shard has its own leader and followers. Ten shards give you roughly ten times the write capacity and storage.

The key decision is the shard key (partition key), the column that decides where a row lives.

StrategyHow it decidesGoodBad
RangeKey ranges: user ids 1 to 1M on shard 0, next million on shard 1Range scans are efficient ("all orders in March")Hot spots: new rows all land on the last shard
Hashhash(key) % N or a hash ringSpreads load evenlyRange queries hit every shard; changing N moves data
DirectoryA lookup table maps each key (or tenant) to a shardTotal flexibility, move one tenant at a timeThe directory is an extra hop and a critical dependency
Hash-sharded users
App serverApp serverShard router: hash(user_id)Shard routerhash(user_id)Shard 0Shard 0Shard 1Shard 1Shard 2Shard 2

GET /users/42/orders. The router hashes 42, gets shard 1, and sends the query only there.

1/4

Choosing a shard key is choosing which queries are cheap. Pick the key most queries filter by (user_id for a social app, tenant_id for B2B SaaS, conversation_id for chat), so most requests touch one shard.

Hot keys need special treatment: cache them aggressively, split them across shards with a suffix (post:123#0 to post:123#9, then sum the parts on read), or give them dedicated capacity.

Quick check
A multi-tenant SaaS app shards by created_at month. What goes wrong?
Need a nudge? A hint rules out a wrong answer.

Hot partitions and choosing a shard key

The hash diagram ended on a hot key. In practice it is the most common reason a sharded system falls over, so a shard key needs to pass four tests:

  1. High cardinality. Many distinct values. Sharding by country gives you at most a couple of hundred shards, and one of them holds half your users.
  2. Even frequency. No single value dominates. User ids are usually fine. Tenant ids often are not: in B2B SaaS, the biggest customer can be a large share of all traffic.
  3. Not monotonic. Timestamps and auto-increment ids send all new writes to one shard under range sharding (the earlier created_at quiz).
  4. Matches the main queries. The most frequent queries should hit one shard. A key that spreads load perfectly but turns every page into a scatter-gather is a bad key.

These pull against each other, and compound keys are how you resolve the tension. For a SaaS app, tenant_id keeps each tenant's queries local, but a giant tenant overloads its shard. (tenant_id, user_id) spreads the giant across shards and still lets per-user queries go to one place, at the cost of making "everything for this tenant" a multi-shard query. Run the comparison on a realistic, skewed set of tenants.

Pythonshard_key_skew.py
import hashlibimport randomfrom collections import Counter rng = random.Random(7)SHARDS = 8 def shard_for(key: str) -> int: return int(hashlib.md5(key.encode()).hexdigest(), 16) % SHARDS # 200 tenants whose sizes follow a power law: a few giants, a long tail of small ones.tenants = list(range(200))weights = [1 / (rank + 1) ** 1.2 for rank in tenants]events = [(t, rng.randrange(5_000)) for t in rng.choices(tenants, weights, k=100_000)] def report(name, key): load = Counter(shard_for(key(t, u)) for t, u in events) busiest = max(load.values()) fair = len(events) / SHARDS print(f"{name:<22} busiest shard {busiest:>6,} ({busiest / fair:.1f}x a fair share)") report("tenant_id", lambda t, u: f"{t}")report("(tenant_id, user_id)", lambda t, u: f"{t}:{u}")print("biggest tenant's share of all events:", f"{Counter(t for t, _ in events)[0] / len(events):.0%}")
Output
Press Run (⌘ Enter) to see what happens.

The biggest tenant alone is about a quarter of the traffic, so no hash function can save tenant_id: whichever shard holds that tenant gets at least a quarter of all load. A common production answer is a hybrid: hash most tenants by tenant_id, and use a directory to give the few giants their own dedicated shards.

Read-hot and write-hot keys need different fixes. A celebrity's profile is read-hot: cache it, serve it from replicas, and the shard barely notices. A viral post's like counter is write-hot: every like is a write to one row on one shard, and caching does not help writes. Split the key (post:123#0 to post:123#9, as above), have each write pick a random sub-key, and sum on read, or buffer increments in memory or a queue and write them in batches. Managed stores help a little (DynamoDB adapts capacity and splits busy partitions), but a single key still has a per-key ceiling, so design for it.

Quick check
A chat app shards messages by conversation_id. One company-wide channel with 40,000 members produces 30% of all writes. What is the best change?
Need a nudge? A hint rules out a wrong answer.

Consistent hashing

With hash(key) % N, adding one shard changes N, and almost every key maps somewhere new. Moving most of your data to add one machine is a disaster.

Predict the outputPython

Going from 4 shards to 5 with key % N, how many of the keys 0 to 19 change shard?

print(sum(k % 4 != k % 5 for k in range(20)))
Need a nudge? Hints walk you through it.

Consistent hashing fixes this. Picture a ring of hash values from 0 to 2^32. Each server is hashed to a point on the ring. Each key is hashed too and belongs to the first server clockwise from it. When you add a server, it takes over only the keys between it and its neighbour: about 1/N of the data moves, not most of it.

Servers also get many virtual nodes (say 100 points each) so the ring is evenly divided and a new server takes a little from every other server instead of a lot from one. Run the comparison.

Pythonconsistent_hashing.py
import hashlibfrom bisect import bisect_left def h(text: str) -> int: return int(hashlib.md5(text.encode()).hexdigest(), 16) % 2**32 class Ring: def __init__(self, nodes, vnodes=100): self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes)) self.hashes = [p for p, _ in self.points] def node_for(self, key: str) -> str: i = bisect_left(self.hashes, h(key)) % len(self.points) return self.points[i][1] keys = [f"user:{i}" for i in range(10_000)]old_nodes = ["db-a", "db-b", "db-c", "db-d"]new_nodes = old_nodes + ["db-e"] # Naive: shard = hash(key) % Nmoved = sum(h(k) % 4 != h(k) % 5 for k in keys)print(f"mod N: {moved / len(keys):.0%} of keys move") # Consistent hashing ring with 100 virtual nodes per serverold, new = Ring(old_nodes), Ring(new_nodes)moved = sum(old.node_for(k) != new.node_for(k) for k in keys)print(f"consistent hash: {moved / len(keys):.0%} of keys move") load = {n: 0 for n in new_nodes}for k in keys: load[new.node_for(k)] += 1print("keys per node: ", load)
Output
Press Run (⌘ Enter) to see what happens.

About 20% of keys move (the new server's fair share of one fifth), against 80% with modulo. Consistent hashing is used by Cassandra and DynamoDB to place data, by Memcached client libraries to pick a cache node, and by load balancers to keep a key on the same backend.

ChallengeMedium

Consistent hashing ring

A hash ring has positions 0 to 99. Each server sits at one position. A key belongs to the first server at or after the key's position, walking clockwise. If no server is at or after it, wrap around to the server with the smallest position.

Given nodes as [name, position] pairs (in any order) and a list of key positions, return the server name for each key, in the same order as keys.

nodes = [["A", 10], ["B", 40], ["C", 75]]
keys  = [5, 10, 11, 76]
→ ["A", "A", "B", "A"]   (76 wraps around to A)

There is at least one node, and no two nodes share a position. Aim for O(log n) per key after sorting.

def assign_keys(nodes: list[list], keys: list[int]) -> list[str]: # Sort the ring, then find the first node at or after each key. pass

Resharding is painful

Moving data between shards on a live system is one of the hardest operations in backend engineering. You must copy terabytes while writes keep arriving, keep both copies in sync, switch reads and writes over without downtime, and verify nothing was lost. Cross-shard transactions and joins, which were free on one database, now need application code or distributed transactions.

That is why the advice is: do not shard until you must, and when you do, pick a shard key you will not need to change and start with more logical shards than machines (for example 1,024 logical shards on 8 servers), so growing means moving whole logical shards rather than re-hashing every row. Tools like Vitess (MySQL) and Citus (Postgres) automate much of this.

Put it in order5 steps

A read-heavy Postgres app is growing. Put the usual scaling steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

An online resharding playbook

When you do have to move data on a live system (split a hot shard, go from 8 shards to 16, move a tenant), teams follow nearly the same playbook. Interviewers like it because each step exists to prevent a specific way of losing data.

Moving a shard without downtime
  1. Step 1

    Provision and plan

    Create the target shards and decide the new key-to-shard mapping. Nothing reads or writes the new shards yet.

  2. Step 2

    Start capturing changes

    Begin double writes from the app, or better, stream the source's change log (CDC from the binlog or WAL) into the target. Writes made during the copy must not be missed.

  3. Step 3

    Backfill

    Copy the existing rows in batches, throttled so the source shard keeps serving production traffic. Idempotent upserts make it safe to rerun a batch.

  4. Step 4

    Verify

    Compare row counts and per-range checksums, then shadow-read: serve from the source, also read from the target, and log every mismatch. Fix and repeat until mismatches are zero.

  5. Step 5

    Cut over reads, then writes

    Switch reads first; they are easy to roll back. Switching writes needs a brief write pause on the moving range so the target can catch up on the last changes, then the router points writes at the target.

  6. Step 6

    Keep a way back, then clean up

    Replicate target back to source for a while so you can roll back. Once you are confident, stop it, drop the old copies, and remove the dual-path code.

Some details that separate a smooth migration from a postmortem:

  • Double writes from the app are risky. If the write to the source succeeds and the write to the target fails, the copies diverge. Change data capture from the database log is more reliable, because the log is the single source of truth for what changed and in what order.
  • Backfill and live changes race. A backfill batch can copy an old version of a row after CDC has already applied a newer one. Use the row's version or log position so an older write never overwrites a newer one.
  • The write cut-over is the only moment of risk. Keep it short (seconds) by doing it per range, and practice it on a staging copy first.

You rarely build this from scratch. Vitess (for MySQL) runs it as a workflow: Reshard or MoveTables copies and streams changes, VDiff verifies, and SwitchTraffic cuts reads and writes over, with a reverse workflow kept for rollback. Citus (for Postgres) moves shards between nodes with logical replication through its shard rebalancer. Managed distributed databases like CockroachDB, Spanner, and DynamoDB split and move ranges automatically, which is a large part of why teams choose them.

Put it in order7 steps

Put the steps of an online resharding in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
leader-follower replication
All writes go to one leader, which streams changes to read-only followers.
replication lag
How far a follower is behind the leader. Causes users to miss their own recent writes.
shard
One partition of the data, held by its own database (with its own replicas).
shard key
The column that decides which shard a row lives on. It decides which queries are cheap.
hot key
One key with so much traffic that its shard is overloaded however evenly the rest is spread.
consistent hashing
Keys and servers on a hash ring; each key goes to the next server clockwise, so adding one moves only about 1/N of keys.
semi-synchronous replication
The leader waits for at least one follower to receive each change before confirming, and falls back to async on timeout.
hinted handoff
A node stores writes meant for a down replica and delivers them when it returns.
sloppy quorum
Accepting a write on whichever nodes are reachable, not the key's usual replicas. More available, but quorum overlap is lost.
backfill
Copying existing rows to a new location in batches while live changes are captured separately.