Database replication in system design
Database replication keeps copies of the same data on several machines so the system survives a machine failure, serves more reads and can sit closer to users. Most designs use one leader that takes writes and streams a change log to followers. The decisions that matter in an interview are whether replication is synchronous or asynchronous (durability versus write latency), how the application copes with replica lag, and how failover picks a new leader without losing data or ending up with two leaders.
By Evin JohnPublished 7 min read
1. What replication is
Replication means every change made on one node is copied to others. It is separate from sharding: sharding splits data so each node holds a part, replication copies the same part to several nodes, and large systems do both. The copies serve four goals that pull in different directions. Durability wants each write on several machines before it is acknowledged. Read scaling wants many followers, even if they lag. Availability wants a fast, automatic failover. Locality wants copies in other regions, which makes synchronous replication slow.
2. Why interviewers ask about it
Any design that stores data meets the question "what happens when that database machine dies?" Replication is the answer, and the follow-ups test whether you know its costs: lost writes after an asynchronous failover, users not seeing the comment they just posted, or two nodes both believing they are the leader. The consistency side, models like linearizable and eventual and quorum math, is covered in our consistency and CAP guide; this page is about the plumbing.
3. Synchronous, asynchronous, semi-synchronous
| Mode | Leader acknowledges after | Write latency | If the leader dies right after acking |
|---|---|---|---|
| Synchronous (all followers) | Every follower has the change | Slowest follower sets it; one stuck follower blocks writes | No acknowledged write is lost |
| Semi-synchronous | At least one follower (or a quorum) has it | One round trip to the nearest follower | No loss if that follower becomes leader |
| Asynchronous | Only the leader has it | Lowest | Writes not yet copied are lost, often a fraction of a second's worth, more under load |
Put a number on it in the interview: within one region a synchronous copy to another zone typically costs about a millisecond or two, which most products accept. Across continents it can cost tens to over a hundred milliseconds per write, which is why cross-region copies are usually asynchronous, while consensus systems such as Raft-based stores wait for a majority, not for every node.
4. How changes are shipped
| Method | What is sent | Pros | Cons |
|---|---|---|---|
| Statement-based | The SQL statements themselves | Compact | Non-deterministic functions (NOW(), RAND()), triggers and ordering can make replicas differ |
| Physical log shipping | The storage engine's write-ahead log, byte-level page changes | Exact copy; simple | Leader and follower must run compatible versions; cannot filter tables |
| Logical (row-based) | Row changes: inserted row, old and new values of updated rows, deleted keys | Version-independent; can filter; readable by other systems | Larger for bulk updates |
| Change data capture (CDC) | A stream of logical changes published to a log or queue | Feeds caches, search indexes and analytics from one source of truth | Another system to run; consumers must handle ordering and replays |
CDC is worth mentioning whenever a design has derived data: a search index, a cache, a data warehouse. Reading the database's own log avoids the dual-write problem where the app writes to the database and the index separately and one of them fails. It also connects naturally to event-driven architecture.
5. Replica lag and the anomalies it causes
| Anomaly | What the user sees | Fix |
|---|---|---|
| Missing your own write | You post a comment, refresh, and it is gone | Read-your-writes: read from the leader for a short window after a write, or from a follower that has reached your write's log position |
| Time going backwards | A refresh hits a more stale follower and a message disappears | Monotonic reads: pin each user's session to one follower, or track the highest position they have seen |
| Effect before cause | A reply appears before the question it answers | Consistent prefix: keep related writes in the same partition so they replicate in order |
class Router:
def __init__(self, leader, replicas):
self.leader, self.replicas = leader, replicas
def write(self, session: dict, sql: str) -> None:
lsn = self.leader.execute(sql) # leader returns its log position
session["min_lsn"] = max(session.get("min_lsn", 0), lsn)
def read(self, session: dict, sql: str):
need = session.get("min_lsn", 0)
for r in self.replicas: # any caught-up replica will do
if r.applied_lsn() >= need:
return r.query(sql)
return self.leader.query(sql) # none caught up: use the leader
# leader at 100, replica-1 at 99, replica-2 at 100:
# read before any write -> replica-1
# write (leader now at 101) -> next read goes to the leader
# replica-2 reaches 101 -> next read goes to replica-2Lag is usually small, but it grows under heavy write load, during long-running queries on a follower, or after a network blip, and it can reach minutes. Monitor it, alert on it, and have followers that fall too far behind removed from the read pool automatically.
6. Failover, split brain and fencing
- Detect the failureUsually a missed heartbeat timeout. Too short and a slow garbage-collection pause triggers a needless failover; too long and writes are down for longer.
- Choose a new leaderThe follower with the most recent data, ideally one that was synchronous. With asynchronous followers, whatever the old leader had not shipped is lost or must be reconciled later.
- Redirect writesUpdate the service discovery entry, virtual IP or proxy config so clients write to the new leader.
- Fence the old leaderIf the old leader comes back believing it still leads, two nodes accept writes: split brain. Prevent it with a lease from a consensus store, an epoch number that storage rejects when stale, or by cutting the old node off (often called STONITH).
- Rejoin as a followerThe old leader discards any writes the new leader never saw, or they are reconciled by hand, then catches up.
Consensus-based replication (Raft, Paxos and close relatives, as used by etcd, ZooKeeper and many distributed SQL databases) builds election and fencing into the protocol: a leader needs a majority, and a minority side cannot elect one. That is why such clusters use an odd number of nodes, typically three or five. The same fencing idea appears in distributed locks.
7. Adding a new follower
You cannot just copy files from a running leader, because they change during the copy. The standard method: take a consistent snapshot, note the exact log position it corresponds to, restore the snapshot on the new node, then replay the log from that position until it has caught up. Snapshots are also how you rebuild a follower that fell too far behind. In capacity terms, budget network and disk for the initial copy; restoring several terabytes takes hours, which matters for how fast you can recover redundancy after a failure.
8. How it shows up in common prompts
| Prompt | Replication choice | Why |
|---|---|---|
| Payment system | Synchronous or consensus replication for the ledger | An acknowledged payment must never be lost on failover |
| Twitter timelines | Asynchronous followers for reads, read-your-writes for the author | Read-heavy; a second of lag is fine for others |
| URL shortener | Leader plus read replicas and caches | Redirect reads dominate; new links can read from the leader briefly |
| Search autocomplete | CDC from the source of truth into the suggestion index | Derived data should follow the database's log |
| Multi-region products | Async cross-region followers or multi-leader | Synchronous writes across oceans are too slow for most requests |
9. Mistakes to avoid
- "We replicate, so we won't lose data." Not with asynchronous replication and automatic failover.
- Reading from followers everywhere. Some reads must see the latest write: after a user's own update, or before a money decision.
- Automatic failover without fencing. Two leaders corrupt data faster than downtime ever would.
- Replicas as backups. A bad DELETE replicates in milliseconds. Keep point-in-time backups too.
- Ignoring catch-up time. A dead node's replacement needs hours to copy data, and the cluster runs with less redundancy meanwhile.
10. How to talk about it in the interview
- State the replication factor and where copies live (zones, regions).
- Say sync or async per hop, and what could be lost on failover.
- Name which reads must go to the leader or a caught-up follower.
- Describe failover in three steps and how the old leader is fenced.
Fictional example
- Interviewer
- How do you make the orders database survive a failure?
- Candidate
- One leader and two followers in other zones of the same region. One follower is semi-synchronous, so every acknowledged order exists on two machines. The second is asynchronous and serves reporting reads.
- Interviewer
- The leader dies. Walk me through it.
- Candidate
- The cluster manager misses heartbeats for about ten seconds, promotes the semi-synchronous follower because it has every acknowledged write, bumps the epoch, and updates the endpoint clients use. Storage rejects writes with the old epoch, so the old leader can't accept anything if it wakes up.
- Interviewer
- What do users see?
- Candidate
- Ten to twenty seconds of failed writes that the client retries with idempotency keys, and no lost orders. A cross-region async copy covers a full regional outage, where we'd accept losing the last seconds of writes.
Practicing with Natively
Replication questions go three follow-ups deep: what is lost, what users see, and who fences whom. If you rehearse with Natively running, it transcribes the session and can suggest points for each follow-up as it comes, and the saved transcript shows afterwards whether you ever said sync or async out loud. You can also capture a screenshot of a replication diagram and have it explained.
Questions people ask
What is the difference between synchronous and asynchronous replication?
With synchronous replication the leader confirms a write only after followers have it, so no acknowledged write is lost on failover, but writes wait for the slowest required follower. With asynchronous replication the leader confirms immediately, which is faster, but writes not yet copied are lost if the leader dies.
What is replication lag and how do you handle it?
The delay before a change on the leader appears on a follower. Handle it by sending reads that must be fresh, such as a user's view of their own update, to the leader or to a follower that has reached the write's log position, and by pinning sessions to one follower to avoid going back in time.
What is split brain in database replication?
A failure where two nodes both act as leader and accept writes, usually after a failover when the old leader comes back. Prevent it with fencing: leases from a consensus store, epoch numbers that storage checks, or cutting off the old node.
Is a replica the same as a backup?
No. A replica copies every change, including accidental deletes and corruption, within moments. You still need point-in-time backups to recover from mistakes.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
