- Part 20 of 21 in System Design Roadmap: From Beginner to Intermediate Architecture Beginner
Database Replication Explained: From Single-Leader to Distributed Consensus
Master the principles of database replication, evaluate consistency models, and build resilient single-leader and multi-replica architectures.
MonksBit Desk
November 25, 2026 · 7 min read · 69 views
Read
Database replication is the technique of copying and maintaining database objects or data across multiple computing nodes connected via a network. It ensures high availability, fault tolerance, and horizontal read scalability by allowing standby nodes to serve queries or take over if a primary node fails.
You will need. Basic knowledge of relational or key-value databases · Familiarity with client-server networking · Understanding of basic concurrency concepts
The full lesson
Level 1 · Beginner: Core concepts of leader-based data replication
At its simplest, replication relies on a single leader node and one or more follower nodes. The leader receives all write requests from clients and records changes locally into an append-only log. Followers continuously ingest this log and apply changes to their local state in the identical sequence.
Consider a single bank balance starting at 100 on leader node L and follower node F. A client issues a write setting the balance to 150 on node L. Node L records this assignment to its write-ahead log, applies it to local storage, and transmits the log record across the network to node F. Node F reads the log record, applies the mutation, and now both nodes hold the value 150.
Reads can be distributed across both nodes to scale query throughput. However, if node F has not yet processed the latest update from node L, a client reading from node F will observe a stale value. This behavior is called replication lag.
Basic simulation of single-leader synchronous replication
class FollowerNode: def __init__(self, node_id: str): self.node_id = node_id self.store = {} def apply_write(self, key: str, value: str) -> bool: self.store[key] = value return Trueclass LeaderNode: def __init__(self): self.store = {} self.followers = [] def add_follower(self, follower: FollowerNode): self.followers.append(follower) def write(self, key: str, value: str) -> bool: self.store[key] = value for follower in self.followers: follower.apply_write(key, value) return True def read(self, key: str) -> str: return self.store.get(key, "")leader = LeaderNode()replica = FollowerNode("follower_1")leader.add_follower(replica)leader.write("user_101", "Alice")assert replica.store["user_101"] == "Alice"
Key takeaways
- A leader processes all writes to enforce total ordering of mutations.
- Followers replicate the leader log to provide read scalability and redundancy.
- Replication lag occurs when network or processing delays cause followers to fall behind.
Level 2 · Intermediate: Synchronous versus asynchronous replication and failover handling
Replication can be synchronous, asynchronous, or semi-synchronous. In synchronous replication, the leader waits for follower acknowledgments before committing a transaction to the client, guaranteeing zero data loss at the expense of higher write latency. In asynchronous replication, the leader acknowledges the client immediately after writing locally, prioritizing throughput over strict durability.
Failover is the process of promoting a follower to become the new leader when the existing leader stops responding. A failover mechanism requires heartbeat monitoring to detect node failure, consensus among nodes to choose the most up-to-date follower, and reconfiguring clients to route writes to the newly elected leader.
A critical challenge during failover is split-brain syndrome, where network partitions cause two nodes to believe they are the legitimate leader simultaneously. This condition causes conflicting writes that corrupt persistent state unless a quorum-based fencing mechanism prevents unauthorized writes.
Semi-synchronous replication with failure recovery and heartbeats
import timeclass ReplicatedStore: def __init__(self, node_id: str): self.node_id = node_id self.state = {} self.log = [] self.is_alive = True def append_log(self, term: int, key: str, value: str) -> bool: if not self.is_alive: return False entry = (term, key, value) self.log.append(entry) self.state[key] = value return Trueclass LeaderCluster: def __init__(self): self.term = 1 self.leader = ReplicatedStore("leader") self.followers = [ReplicatedStore("f1"), ReplicatedStore("f2")] def write(self, key: str, value: str) -> bool: self.leader.append_log(self.term, key, value) acks = 1 for f in self.followers: if f.append_log(self.term, key, value): acks += 1 majority = (len(self.followers) + 1) // 2 + 1 return acks >= majoritycluster = LeaderCluster()assert cluster.write("config_timeout", "30s") is Truecluster.followers[0].is_alive = Falseassert cluster.write("config_timeout", "60s") is True
Key takeaways
- Synchronous replication prevents data loss but blocks if followers become unreachable.
- Asynchronous replication delivers low latency but risks data loss during ungraceful leader failover.
- Quorum checks prevent split-brain states by ensuring only a true majority can commit updates.
Level 3 · Advanced: Multi-leader replication, conflict resolution, and consensus logs
In multi-datacenter environments, single-leader replication introduces unacceptable latency for geographically distant writes. Multi-leader replication permits write operations on multiple designated leader nodes across regions. Each leader processes writes locally and asynchronously transmits data modifications to peer leaders.
Allowing concurrent writes to different nodes creates conflicting changes on identical records. Systems resolve conflicts using deterministic strategies such as Last-Write-Wins (LWW) via timestamps, Conflict-free Replicated Data Types (CRDTs), or application-level merge procedures.
Modern distributed databases replace ad-hoc leader management with formal consensus algorithms such as Raft or Paxos. These algorithms guarantee linearizable state transitions by establishing durable quorums and monotonic term numbers, ensuring state convergence across all unpartitioned replicas.
Conflict-free state convergence using Observed-Remove Sets (ORSet)
import uuidclass LWWRegister: def __init__(self, initial_value=None, initial_timestamp=0.0): self.value = initial_value self.timestamp = initial_timestamp def set(self, value, timestamp: float): if timestamp > self.timestamp: self.value = value self.timestamp = timestamp def merge(self, other: "LWWRegister"): if other.timestamp > self.timestamp: self.value = other.value self.timestamp = other.timestampnode_a = LWWRegister("active", 100.0)node_b = LWWRegister("inactive", 105.0)node_a.merge(node_b)assert node_a.value == "inactive"assert node_a.timestamp == 105.0
Key takeaways
- Multi-leader setups reduce cross-region write latencies but require deterministic conflict resolution.
- Last-Write-Wins can silently drop valid data due to clock drift across unsynchronized servers.
- Distributed consensus engines like Raft ensure atomic log replication across dynamic quorums.
Complexity
- Time: O(1) local write, O(N) network replication broadcast to N followers
- Space: O(N * M) total storage across N nodes storing M log entries
Applying a write to local memory or append-only log takes constant time O(1). Replicating updates across N nodes requires O(N) message transmissions. Storing replicated logs across N nodes requires memory proportional to the cluster size multiplied by log size.
Common mistakes
- Using wall-clock timestamps for Last-Write-Wins conflict resolution without acknowledging NTP clock drift.
- Promoting an arbitrary follower during failover without verifying it holds all committed log indices.
- Failing to implement write-fencing tokens, leading to split-brain data corruption when dead nodes recover.
- Routing strictly consistent reads to asynchronous followers without checking read-your-writes guarantees.
Practice problems
- Read-your-writes routing policy (easy). Hint: Track the client last commit timestamp and route reads to the leader until followers reach that index.
- Heartbeat and split-brain detection (medium). Hint: Count responses to ensure a node can only remain leader if it maintains contact with a majority quorum.
- Distributed log reconciliation engine (hard). Hint: Compare term numbers and log indices backwards from the uncommitted end to truncate divergent histories.
Summary
Database replication provides horizontal read scaling, geographic locality, and disaster recovery. Single-leader architectures simplify ordering at the expense of write throughput bottlenecks, while multi-leader and consensus systems eliminate single points of failure through explicit quorum checks and deterministic conflict convergence.
Finish the Prove step above to complete this lesson.
System Design Roadmap: From Beginner to Intermediate Architecture · 20 of 21
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!