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 Published 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

When the leader tells the client a write succeeded
ModeLeader acknowledges afterWrite latencyIf the leader dies right after acking
Synchronous (all followers)Every follower has the changeSlowest follower sets it; one stuck follower blocks writesNo acknowledged write is lost
Semi-synchronousAt least one follower (or a quorum) has itOne round trip to the nearest followerNo loss if that follower becomes leader
AsynchronousOnly the leader has itLowestWrites not yet copied are lost, often a fraction of a second's worth, more under load
When the leader tells the client a write succeeded. Scroll sideways on a small screen.

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

What actually travels from leader to follower
MethodWhat is sentProsCons
Statement-basedThe SQL statements themselvesCompactNon-deterministic functions (NOW(), RAND()), triggers and ordering can make replicas differ
Physical log shippingThe storage engine's write-ahead log, byte-level page changesExact copy; simpleLeader and follower must run compatible versions; cannot filter tables
Logical (row-based)Row changes: inserted row, old and new values of updated rows, deleted keysVersion-independent; can filter; readable by other systemsLarger for bulk updates
Change data capture (CDC)A stream of logical changes published to a log or queueFeeds caches, search indexes and analytics from one source of truthAnother system to run; consumers must handle ordering and replays
What actually travels from leader to follower. Scroll sideways on a small screen.

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

Three things users notice when followers lag
AnomalyWhat the user seesFix
Missing your own writeYou post a comment, refresh, and it is goneRead-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 backwardsA refresh hits a more stale follower and a message disappearsMonotonic reads: pin each user's session to one follower, or track the highest position they have seen
Effect before causeA reply appears before the question it answersConsistent prefix: keep related writes in the same partition so they replicate in order
Three things users notice when followers lag. Scroll sideways on a small screen.
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-2
Read-your-writes routing by log position (run with python3 against fake nodes)

Lag 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

  1. 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.
  2. 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.
  3. Redirect writesUpdate the service discovery entry, virtual IP or proxy config so clients write to the new leader.
  4. 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).
  5. 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

Replication choices in well-known prompts
PromptReplication choiceWhy
Payment systemSynchronous or consensus replication for the ledgerAn acknowledged payment must never be lost on failover
Twitter timelinesAsynchronous followers for reads, read-your-writes for the authorRead-heavy; a second of lag is fine for others
URL shortenerLeader plus read replicas and cachesRedirect reads dominate; new links can read from the leader briefly
Search autocompleteCDC from the source of truth into the suggestion indexDerived data should follow the database's log
Multi-region productsAsync cross-region followers or multi-leaderSynchronous writes across oceans are too slow for most requests
Replication choices in well-known prompts. Scroll sideways on a small screen.

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

Replicating an order database
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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP