Database Replication

Keep several copies of a database in sync, so no single database is a point of failure.

What is it?

A single database server is a risk: if it goes down, the app loses its data. Replication continuously copies data from one database (the primary) to one or more others (replicas), so there's always more than one copy.

Replicas help even when nothing fails. Reads usually far outnumber writes, so spreading reads across several replicas handles much more traffic than one database could.

Explain like I'm 10

It's like a company keeping copies of an important ledger in several offices, updated as changes come in. If the main office burns down, another office already has an up-to-date copy. Meanwhile, staff in every office read their local copy instead of all calling the main office.

Examples

Reads from a replica, writes to the primary

// Simplified pattern
async function getUser(id) {
  return replicaDb.query("SELECT * FROM users WHERE id = ?", [id]);
}

async function createUser(data) {
  return primaryDb.query("INSERT INTO users ...", [data]);
  // this change then gets replicated to replicaDb automatically
}

How it works

The primary records every change (often in a log) and streams that log to each replica, which applies the same changes in the same order.

Streaming takes a little time, so a replica is usually slightly behind the primary. This delay is called replication lag.

Why does it exist?

Replication protects you from losing your only database (a replica can be promoted to take over). It also lets read-heavy apps scale far beyond one server by spreading reads across many replicas.

When to use it

Add replication once a single database is a reliability risk you can't accept, or a read bottleneck. Most production databases run at least one replica for these reasons.

When not to use it

For a small, early-stage app with low traffic, where brief downtime is acceptable, one database is simpler to run and reason about. Replication adds real complexity (replication lag, failover logic) that isn't worth it until the risk or read load justifies it.

Common mistakes

  • Reading from a replica right after writing and being surprised the new data isn't there yet. That's replication lag.

  • Forgetting that replicas are (usually) read-only and sending writes to one.

  • Treating replication as a backup. A mistaken delete on the primary reaches every replica just as fast as a real change.

Practice exercises

  1. Easy:

    Explain why spreading reads across replicas helps an app handle more traffic.

  2. Medium:

    Describe what 'replication lag' is and a real case where it could cause a confusing bug.

  3. Hard:

    Explain why replication is not a substitute for backups, even though both keep copies of your data.

Interview questions

What is database replication?

Continuously copying data from a primary database to one or more replicas, so there's more than one up-to-date copy.

Why do replicas help with read scalability?

Reads can be spread across many replicas instead of all hitting one database, while writes still go to the primary.

What is replication lag?

The short delay between a change on the primary and that change appearing on a replica, since replication isn't instant.

What's the difference between synchronous and asynchronous replication?

In synchronous replication, the primary waits for at least one replica to confirm the write before telling the client it succeeded, so confirmed data exists in more than one place. In asynchronous replication, the primary confirms immediately and streams to replicas afterward. That's faster, but a just-confirmed write may briefly exist only on the primary.

What's the tradeoff of synchronous replication — why doesn't every system just always use it, since it avoids lag?

Every write waits for a round trip to at least one replica, adding latency. If that replica is slow or unreachable, writes can stall or fail. You trade write speed and availability for the guarantee that a confirmed write already has a second copy.

What is "semi-synchronous" replication, and what problem does it try to solve?

The primary waits for at least one replica (not all) to acknowledge before confirming, then replicates to the rest asynchronously. A confirmed write survives the primary failing alone, without the latency and availability cost of waiting on every replica.

Scenario: a primary crashes with writes that had been confirmed to the client but hadn't yet reached any replica. What happens to that data?

With asynchronous replication, it's lost. The client was told the write succeeded, but no replica has it, so nothing can be promoted with it. This is exactly the failure synchronous or semi-synchronous replication prevents.

What is failover, and what's the difference between automatic and manual failover?

Failover is promoting a replica to be the new primary after the primary fails. Manual failover needs a human to spot the failure and trigger it: slower but deliberate. Automatic failover detects and promotes on its own: faster, but risky if detection is wrong (e.g. a network blip mistaken for an outage).

What is "split-brain" in a replicated system, and how does it happen?

Two nodes both believe they're the primary. Often a network partition makes the old primary unreachable, a replica is promoted, then the old primary comes back still thinking it's in charge. Both accept writes independently, and those writes can conflict or be lost when the partition heals.

How do quorum-based writes help prevent split-brain or ambiguous leadership?

A write (or leadership claim) is valid only once a strict majority of nodes acknowledge it. Two separate groups can't both have a majority, so at most one side of a partition can have a legitimate primary.

What is the "read-after-write" (read-your-writes) consistency problem in replicated systems, and how might a system solve it?

A user writes data and immediately reads it back, but the read hits a replica that hasn't caught up, so their change seems missing. Common fixes: send that user's reads to the primary for a short time after their write, or always route their reads to the replica they wrote through.

Scenario: a user updates their profile picture, then immediately reloads the page and sees the old one. What's likely happening, and how would you fix it?

The reload almost certainly read from a replica that hasn't received the update yet: classic replication lag. Give that user a read-your-writes guarantee, e.g. read from the primary briefly after their own write, instead of sending every read to any available replica.

What's the difference between single-leader, multi-leader, and leaderless replication topologies?

Single-leader: one primary takes all writes and replicas are read-only. Simple, with no write conflicts, but the primary is a write bottleneck and single point of failure. Multi-leader: several nodes accept writes and replicate to each other. Better write availability across regions, but concurrent writes to the same data on different leaders can conflict. Leaderless: any node accepts writes and read/write quorums keep things consistent enough. No leader bottleneck, but conflict resolution and consistency become the client's or system's job.

What kind of conflict can arise in multi-leader replication that doesn't happen in single-leader?

Two leaders can each accept a write to the same record at nearly the same time. When they replicate to each other, there are two conflicting versions and no obviously correct order between them.

How is a write conflict typically resolved in a multi-leader or leaderless system?

Common strategies: last-write-wins (keep the later timestamp and silently drop the other), merging the versions with app-specific logic, or surfacing the conflict for a human or the app to resolve. There's no universally right answer, only tradeoffs.

What is "cascading replication," and why might you use it?

Some replicas copy from other replicas instead of the primary, forming a chain or tree. This reduces the network and CPU load on the primary, at the cost of extra hops (and lag) for replicas further down.

What is log-based (WAL-shipping) replication versus statement-based replication, and what's the tradeoff?

Log-based replication ships the primary's low-level write-ahead log entries (the exact bytes changed), which replicas apply directly. It's exact and deterministic but tied to the storage engine and version. Statement-based replication ships the SQL statements for each replica to re-run. It's more portable and compact, but any non-deterministic statement can give different results on each replica.

What could go wrong with statement-based replication that log-shipping avoids?

A statement using something non-deterministic (like NOW(), RAND(), or an auto-increment value computed separately) can produce a different value on each replica. Replicas silently drift from the primary even though each "correctly" ran the same statement.

How would you monitor replication lag in production, and what would you do if it grows unbounded?

Track lag per replica as a key metric (seconds or bytes behind the primary) and alert past the threshold your app can tolerate. Lag that keeps growing usually means a replica can't keep up with writes. Find what's slowing that replica, route reads away from it for a while, or add capacity or replicas to spread the read load.

Scenario: replication lag balloons from 200ms to 30 seconds during a traffic spike. What's likely the cause, and what are your options?

Likely a write spike the replica can't apply fast enough, or the replica starved of CPU/IO by a surge of read queries. Options: cut read traffic to that replica for a while, scale it up, or check whether a batch job or write-heavy event caused an unusual burst.

What happens during promotion of a replica to primary, and what risk exists if the old primary comes back online afterward?

The chosen replica stops applying replication and starts accepting writes, and other replicas and the app are pointed at it. If the old primary returns without being told it was demoted, it may keep accepting writes: split-brain, with two diverging sets of writes to reconcile.

Why is automatic failover risky without careful design?

It must tell a real primary failure from a brief network blip; a false positive can cause an unneeded promotion and split-brain when the 'failed' primary returns. And a promoted replica may be missing writes the old primary confirmed, risking silent data loss during failover.

How does replication lag relate to the choice of consistency model?

Replication lag is the mechanical reason eventual consistency exists: an eventually consistent system accepts lag as normal. A strongly consistent system chooses to wait out or avoid that lag on the read path instead.

Scenario: an application always reads from a replica, but a user who just wrote data expects to see it immediately in the same session. What pattern fixes this without going fully synchronous everywhere?

Read-your-writes routing. Send just that user's reads to the primary (or a replica confirmed to be past their write) for a short time after their write, while everyone else keeps reading from any replica. You pay for the guarantee only where it's needed.

Why does adding more read replicas not help with write scalability?

Every replica must apply every write to stay in sync. More replicas means more places each write must land, not faster writes on the primary. Write throughput depends on the primary (or another strategy like sharding); replicas only spread reads.

Why can heavy read traffic against a replica itself worsen replication lag?

A replica's CPU, memory and IO are shared between serving reads and applying replicated writes. If reads use enough of that capacity, it falls behind on writes, so the read scaling replicas exist for can, under heavy load, make their data staler.

What's a realistic strategy for deciding how many replicas to run, and why isn't "more is always better"?

Size for the read throughput you need beyond what the primary (or cache) handles, plus headroom for one replica being down. Each extra replica adds replication work for the primary and another part to monitor and fail over, so unneeded replicas add complexity for capacity you won't use.

Why can it be risky to promote a replica that was itself lagging at the time the primary failed?

It's missing writes that hadn't reached it yet. Promoting it can lose not only writes no replica had, but also writes that more caught-up replicas already had, once it becomes the new source of truth.

What is chain replication, briefly, and what property does it optimize for?

Replicas form an ordered chain: writes enter at the head and pass down, and a write is complete only once it reaches the tail. It optimizes for strong consistency with clear rules (e.g. reads from the tail always see fully replicated data), at the cost of write latency growing with chain length.

Scenario: you need strong, immediate consistency for one critical page (an order confirmation) right after a write, but want general read scaling everywhere else. How would you architect this with replication?

Send reads for that page (or that user's data, briefly after their write) to the primary, and keep every other read on replicas. Apply the stronger guarantee only where staleness would cause a real problem.

Follow-up: what's the cost of routing reads to the primary for that one page?

It adds load to the primary, which replicas were meant to avoid, and that page's latency now depends on the primary's load. It's an acceptable tradeoff only because it's limited to the one page that needs it.

Why is monitoring replication lag considered a first-class operational metric rather than an afterthought?

Lag decides how stale every replica read is. Without it, a team can't tell whether eventual consistency is holding at milliseconds or has quietly slipped to minutes, which changes what the rest of the system can safely assume.