Replication, Failover & Sharding

System Design · Distributed Systems · Advanced · 24 min

Compare leader-follower, multi-leader and leaderless replication, explain failover and leader election (Raft intuition), and shard data by range or hash without painful rebalancing.

A choir with one conductor. Everyone follows the conductor's beat. If the conductor faints, the singers who know the song best agree on a new conductor, and anyone who fell behind catches up from them.

The idea in everyday words

Replication is photocopying a notebook so losing one copy is not a disaster. Failover is deciding who holds the master copy when its owner gets sick, and the rule is: only someone with the most complete notes may take over. Sharding is splitting a huge encyclopedia into volumes A-F, G-M and so on, so no single shelf has to hold everything.

Three ways to replicate

Replication = keeping copies of the same data on several machines, for durability (survive a disk dying), availability (survive a server dying) and read scale (more machines to read from).

Shape How writes flow Good Bad Examples
Leader-follower (single leader) all writes go to one leader, followers copy its log simple, no write conflicts leader is a bottleneck and a failover point RDS, Aurora, PostgreSQL, MySQL
Multi-leader several leaders (often one per Region) accept writes and sync low write latency everywhere, survives a Region conflicts: two leaders change the same row DynamoDB global tables (multi-active), multi-Region setups
Leaderless client writes to W replicas and reads from R no failover needed, tunable needs quorums, read repair, conflict handling Cassandra, Dynamo-style stores

Synchronous replication: the leader waits for the follower's ack before saying "done". Safe, slower. Asynchronous: the leader answers first and copies later. Fast, but recent writes can be lost if the leader dies, and followers lag.

Replication lag symptoms: you post a comment and it vanishes on refresh (read went to a lagging follower), or a refreshed page shows older data than before. Fix the important paths by reading from the leader right after a write.

Failover and leader election (Raft intuition)

When a leader dies, someone must notice and a new leader must be chosen without ever having two leaders (that is split brain, where two nodes both accept writes and data diverges).

Raft, the most teachable consensus algorithm, does it like this:

  1. The leader sends heartbeats. Each follower has a randomized election timeout (e.g. 150-300 ms). Random, so they rarely time out together.
  2. A follower whose timer fires becomes a candidate: it increments the term (an election counter) and votes for itself.
  3. Others grant at most one vote per term, and only if the candidate's log is at least as up to date as theirs (compare last entry's term, then index).
  4. A strict majority (3 of 5) wins. Two majorities always overlap, so two leaders in the same term are impossible.
  5. The new leader sends missing entries to lagging followers. An old leader that comes back sees a higher term and steps down.

Why odd cluster sizes? 3 nodes tolerate 1 failure, 5 tolerate 2. A 4th node adds cost but still only tolerates 1 (majority of 4 is 3). Spread nodes across 3 Availability Zones so losing one AZ never removes a majority.

Fencing: the term number also acts as a fencing token. Storage rejects writes stamped with an old term, so a "zombie" old leader cannot corrupt data.

Sharding: range vs hash, and rebalancing

Sharding (partitioning) = splitting data across machines so each holds only part of it. Replication copies data; sharding divides it. Big systems do both: each shard is itself replicated.

Range sharding Hash sharding
Rule keys A-F → shard 0, G-M → shard 1 … shard = hash(key) % shards (or a hash ring)
Range queries great: "all orders in March" hits one shard bad: neighbours land everywhere
Hot spots sequential keys (timestamps) all hit the last shard spreads load evenly
Used by HBase, Bigtable, Spanner, MongoDB ranged DynamoDB, Cassandra, ElastiCache cluster mode

Rebalancing = moving data when you add or remove shards. The naive hash % N is a trap: going from 3 to 4 shards moves about 3 out of 4 keys. Better:

  • Consistent hashing: only about 1/N of keys move (see the consistent hashing lesson).
  • Many fixed partitions: create far more partitions than machines (e.g. 256) and move whole partitions between machines. Redis Cluster uses 16384 hash slots this way.
  • Split hot ranges: DynamoDB splits partitions automatically as they grow or get hot.

Go deeper (senior / staff)

Start every failover answer with RPO and RTO. RPO = how much recent data you may lose. RTO = how long you may be down. Async replication means RPO is "whatever the lag was"; sync replication buys RPO near zero with write latency.

Failure modes interviewers probe.

  • Promoting an async replica loses writes that had not arrived yet. Say so, and say how you reconcile (replay from an outbox or queue, or accept it for this data).
  • Failover is a client problem too. Endpoints move by DNS, and clients that cache DNS or hold dead connections keep failing. RDS Proxy keeps a connection pool and cuts reconnect storms; set low DNS TTLs and retry with backoff.
  • Flapping: an automated failover that triggers on a short network blip can bounce the writer back and forth. Require sustained health-check failure.
  • Gray failure: the leader still sends heartbeats but is too slow to serve. Monitor latency, not just liveness.

Multi-region on AWS.

  • Aurora Global Database: storage-level replication to secondary Regions with lag typically under a second. A planned switchover loses nothing but needs both Regions healthy; an unplanned failover during a Regional outage can lose the last moments of writes.
  • DynamoDB global tables: multi-active, last writer wins, so design for conflicts or give each item a home Region.
  • Decide who pulls the trigger: a human runbook or automation such as Route 53 Application Recovery Controller.

Cost reasoning. Every replica is a full copy you pay for, and cross-Region replication adds data transfer and replicated write charges. Active-active roughly doubles the bill and adds conflict handling; warm standby or pilot light cost less but give a longer RTO. Match the tier to what one hour of downtime actually costs the business.

Step by step

  1. Steady state:

    5 nodes, N1 leads term 1. Logs: N1 6, N2 6, N3 6, N4 4, N5 5. Entry 6 is on 3 of 5 nodes, so it is committed.

  2. Leader dies:

    N1 crashes. Heartbeats stop. Each follower's random timer starts counting (say N2 150 ms, N3 210 ms, N4 260 ms).

  3. Candidate:

    N2 times out first, sets term = 2, votes for itself (1 vote) and asks N3, N4, N5 for votes.

  4. Log check:

    N3: candidate (t1, 6) vs mine (t1, 6) → grant. N4: (t1, 6) vs (t1, 4) → grant. N5: (t1, 6) vs (t1, 5) → grant. 4 votes ≥ 3 → N2 leads term 2.

  5. If N4 had gone first:

    N4 (t1, 4) asks N2, N3, N5: all have newer logs and refuse. N4 gets 1 vote and loses. Committed entry 6 is safe.

  6. Catch up:

    N2 sends entries 5-6 to N4 and entry 6 to N5. All alive nodes now have log 6.

  7. Old leader returns:

    N1 restarts with term 1, sees term 2 heartbeats, steps down to follower. No split brain.

Code example

import bisect

# Range sharding: sorted split points. Shard i holds keys < bounds[i].
bounds = ["g", "n", "t"]           # shards: [..g) [g..n) [n..t) [t..]
def range_shard(key):
    return bisect.bisect_right(bounds, key)

for k in ["apple", "grape", "mango", "zebra"]:
    print(f"{k:6} -> range shard {range_shard(k)}")

# Hash sharding: how many keys move when we go from 3 to 4 shards?
def h(key):
    return sum(ord(c) * 31 ** i for i, c in enumerate(key)) % 1000003

keys = [f"user{i}" for i in range(1000)]
moved = sum(1 for k in keys if h(k) % 3 != h(k) % 4)
print(f"hash % N, 3 -> 4 shards: {moved / len(keys):.0%} of keys move")

# Fixed partitions: 12 partitions, only whole partitions move to the new node.
owner_before = {p: p % 3 for p in range(12)}
owner_after = dict(owner_before)
for p in [0, 4, 8]:                # hand 3 partitions to new node 3
    owner_after[p] = 3
changed = sum(1 for p in range(12) if owner_before[p] != owner_after[p])
print(f"fixed partitions: {changed}/12 partitions move ({changed / 12:.0%})")

Complexity

  • Time: O(n log n) to sort the alive nodes (O(n) with a single max pass)
  • Space: O(n) for the list of alive nodes

Interview tips

  • State the replication choice and its trade-off: 'single leader, async replicas for reads; read-after-write goes to the leader'.

  • Explain failover in 4 beats: detect (heartbeats), elect (majority + up-to-date log), redirect (DNS / endpoint), repair (catch up followers).

  • Mention split brain and how majorities plus terms (fencing tokens) prevent it.

  • For sharding, say the key and why: 'hash on user_id for even load; a celebrity user is a hot key, so we add a suffix or cache it'.

  • AWS mapping: RDS Multi-AZ standby, Aurora replicas + cluster endpoint, Aurora Global Database, DynamoDB global tables, ElastiCache cluster mode.

Challenge: Simplified Leader Election

Write elect_leader(nodes). Each node is {"id": str, "alive": bool, "last_term": int, "last_index": int}.

Rules (a simplified Raft):

  1. Let n = total number of nodes (alive or not). A leader is only possible if more than half of all nodes are alive (alive * 2 > n). Otherwise return None / null.
  2. Among alive nodes, the winner has the most up-to-date log: higher last_term wins; if equal, higher last_index wins.
  3. If still tied, the smaller id (string comparison) wins.

Return the winner's id.

Example: A(1, 6), B(1, 6), C(1, 4), all alive → "A".

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Distributed Systems

Previous: CAP, PACELC & Consistency · Next: Monolith vs Microservices