Data Storage & Scaling· 20 min

Database Replication

Primary-replica for fault tolerance and read scaling

Data StorageIntermediate20 min read

Copy data across multiple machines for fault tolerance, read scaling, and geographic locality.

Database Replication — diagram
🖱️ Drag nodes · Scroll to zoom · Drag background to pan
alwayssyncasyncasyncround-robinround-robinround-robinWrite RequestPrimaryAccepts ALL writesReplica 1ReadsReplica 2ReadsReplica 3ReadsRead Request

High-level design

Writes → Primary → [Replica 1, Replica 2]. Reads → any replica. Single primary (master-slave) or multi-primary (multi-master). Sync vs async replication determines consistency/latency.

Low-level design

Single-primary: one node accepts writes, replicates to others. Multi-primary: any node accepts writes, conflicts resolved via LWW/vector clocks/CRDTs. Modes: synchronous (slow but safe), asynchronous (fast but may lose data), semi-synchronous.

Trade-offs

  • →Sync replication = no data loss but high write latency
  • →Multi-master = write availability but conflict resolution complexity
  • →More replicas = better read scale but more storage and sync cost

Used in production by

PostgreSQL streaming replication, MySQL master-slave, Cassandra multi-master

Questions to ask your interviewer

  • →What's the acceptable data loss window on failover?
  • →Read-heavy or write-heavy workload?
  • →Is cross-region replication needed?

System design deep dive

Database Replication: deep dive

Replication keeps copies of the same data on several machines so the system survives hardware failures, serves more reads, and puts data closer to users. The hard parts are replication lag, safe failover, and resolving conflicting writes.

How leader-follower replication works, step by step

  1. A client sends UPDATE users SET email = ... WHERE id = 42 to the primary.
  2. The primary applies the change and appends it to its replication log (the WAL in Postgres, the binlog in MySQL), each entry tagged with an increasing position.
  3. Followers keep a connection open and stream log entries from their last known position, applying them in the same order.
  4. In asynchronous mode the primary acknowledges the client right after its own commit. In synchronous mode it waits until at least one follower confirms it has the entry durably.
  5. Read traffic is routed to followers, which may be a few milliseconds to several seconds behind depending on load and network.
  6. If the primary fails, a monitor detects missed heartbeats, the most up-to-date follower is promoted, the others re-point to it, and clients are redirected through DNS, a proxy, or a virtual IP.

Replication topologies compared

TopologyWrites accepted atStrengthMain challenge
Single leaderOne primarySimple, no write conflictsPrimary limits write throughput; failover needed
Multi-leaderOne leader per region or data centerLow-latency local writes, survives region lossConflicting concurrent writes must be merged
Leaderless (Dynamo style)Any replica, with quorumsNo failover step, highly availableRead repair, sloppy quorums, conflict handling
Consensus-based (Raft, Paxos)Elected leader, majority ackStrong consistency with automatic failoverWrite latency of a majority round trip

Living with replication lag

Asynchronous followers create user-visible anomalies. A user updates their profile and immediately reloads, but the read hits a lagging follower and shows the old value. Fixes include read-your-writes (route a user's reads to the primary for a few seconds after they write, or wait until a follower has reached the write's log position), monotonic reads (pin each user to one follower so time never appears to go backwards), and consistent prefix reads (keep causally related writes in the same partition so a reply never appears before the question).

When to replicate (and what replication will not do)

Every production database should have at least one replica for high availability, ideally in a different availability zone. Add read replicas when reads dominate and the primary's CPU is the bottleneck; a read-heavy app at a 10:1 read-write ratio can often scale reads 4 or 5x this way. Cross-region replicas cut read latency for distant users and provide disaster recovery. Replication does not increase write capacity in a single-leader setup (that needs sharding), and it is not a backup: an accidental DELETE replicates to every copy within milliseconds, so you still need point-in-time backups.

Common mistakes in interviews

  • Adding read replicas without mentioning lag or read-your-writes consistency.
  • Treating failover as instant and free. Promoting an async follower can lose the last few seconds of writes.
  • Ignoring split brain, where two nodes both believe they are primary. Use fencing tokens, a consensus-based coordinator, or STONITH-style isolation of the old primary.
  • Proposing multi-leader replication without a conflict resolution strategy.
  • Calling replicas backups.

Interview questions

›What is semi-synchronous replication?

The primary waits for at least one follower to acknowledge receiving each transaction before confirming the commit, while other followers stay asynchronous. It guarantees that every acknowledged write exists on two machines, with less latency than waiting for all followers. MySQL and Postgres both support variants of it.

›How does leaderless replication handle a replica that was down?

With hinted handoff, another node temporarily stores writes meant for the down replica and forwards them when it returns. Read repair fixes stale values when a quorum read notices a mismatch, and periodic anti-entropy uses Merkle trees to find and sync any remaining differences.

›How do multi-leader systems resolve conflicts?

Common options are last-write-wins using timestamps (simple but silently drops data), version vectors that detect concurrency and keep both versions for the application to merge, and CRDTs, data types like counters and sets designed to merge automatically. Avoiding conflicts by routing each record's writes to one home region is often the most practical choice.

›How do you avoid split brain during failover?

Use a consensus system such as etcd or ZooKeeper, or a built-in Raft group, to elect exactly one leader with a majority vote. Each new leader gets a higher epoch or fencing token, and storage or downstream systems reject writes carrying an older token, so a resurrected old primary cannot corrupt data.

›What do RPO and RTO mean for replication design?

RPO (recovery point objective) is how much data you can afford to lose, which drives sync vs async replication. RTO (recovery time objective) is how long recovery may take, which drives automated failover and warm standbys. A bank may need RPO near zero and RTO under a minute; an analytics system might accept an hour for both.

More System Design Concepts

Compare this lesson with the other 13 concepts in the course. Expand any card for its design, trade-offs and diagram.

Category:
Difficulty:
Showing 13 of 13