Database replication explained: leader-follower, multi-leader and leaderless quorums

Keep copies of your data on several machines and you survive crashes, serve users nearby and spread reads. But copies drift apart. Learn the three replication models, sync vs async, failover, write conflicts and quorums, and what each one costs.

A main library building in the centre sends copies of the same red book along dotted paths to three branch libraries labelled US, Europe and Asia. One branch's copy is still on its way, with a small clock beside it. A sign above says 'Same data, many places.'
Fig. 1 — Replication keeps the same data on several machines. The hard part is that copies don't all change at the same moment.

You have one database server. Then three things happen, one after another:

  • The server crashes, and every user sees an error page.
  • You get users in Asia, but the server is in the US, so every request crosses the planet.
  • A sale starts, 10,000 users read at once, and the server can’t keep up.

The fix for all three is the same: keep copies of the data on more than one machine. That’s replication. Think of a library that opens branches in other cities, each with the same books. If one branch closes, the others stay open. Readers go to the nearest one. And no single branch is swamped.

This article opens the Consistency & CAP theorem thread, because replication is where consistency problems are born. The moment there are two copies, they can disagree.

What replication buys you, and what it doesn’t

  • High availability: one server fails, another carries on.
  • Lower latency: users read from a copy near them.
  • More read capacity: spread reads across many copies.
  • Durability: the data survives losing a whole machine.

One thing it is not: a backup. If someone runs DELETE FROM orders by mistake, every copy deletes it too, within milliseconds. You still need backups you can restore to a point in time.

Every replication design answers four questions:

  1. Who accepts writes? One server, several, or any of them?
  2. When is a write “done”? When one copy has it, or when several do?
  3. What happens when copies fall behind?
  4. What happens when the server taking writes dies?

Sync vs async: when is a write “done”?

This choice shapes everything else.

Three timelines of a write. Synchronous: the leader writes, sends the change to the follower, waits for the follower to confirm, then tells the user it is saved; slow but no data loss if the leader dies. Asynchronous: the leader writes and immediately tells the user it is saved, then sends the change to the follower in the background; fast, but if the leader dies before sending, the write is lost. Semi-synchronous: the leader waits for one of several followers to confirm, then replies; a middle ground used by most production setups.
Synchronous waits for copies before saying 'saved'. Asynchronous says 'saved' first and copies later. Semi-sync waits for just one.
Synchronous Asynchronous Semi-synchronous
Write is “done” when Every replica has it The leader has it The leader and one replica have it
Write speed Slowest (waits for all) Fastest Slightly slower
Leader dies right after Nothing lost Recent writes can be lost Nothing lost (one copy has it)
One slow replica Blocks every write No effect Little effect

Fully synchronous is rare, because one slow or dead replica freezes all writes. Most systems run async or semi-sync, and accept that replicas trail slightly behind.

Model 1: leader-follower

The most common model by far. One server, the leader (or primary), accepts all writes. It streams every change to the followers (replicas), which apply them in the same order. Reads can go to any of them.

Three panels. Leader-follower: all writes go to one leader, which streams changes to three followers; reads are spread across all of them. Multi-leader: three leaders in the US, Europe and Asia each accept local writes and sync with each other in both directions; a warning marks that two leaders can change the same row at once. Leaderless: a client writes directly to three of five equal nodes and reads from three, with no leader at all; overlapping nodes guarantee at least one has the latest write.
One writer, several writers, or no special writer at all. Each step to the right makes writes more available and conflicts more likely.

It’s simple to reason about: there’s one source of truth, so writes never conflict. PostgreSQL, MySQL, MongoDB replica sets and Amazon RDS all work this way. The two costs are replica lag and failover.

Replica lag

With async replication, a follower might be milliseconds behind, or seconds when it’s busy. That leads to a classic bug:

A user changes their profile picture. The write goes to the leader. They refresh, the read goes to a follower that hasn’t caught up, and the old picture appears. “It didn’t save!” They upload it again.

The fix is read-your-writes: right after a user writes something, read their data from the leader for a short while.

// Java · read your own recent writes from the leader
public Profile getProfile(long userId, Session session) {
    boolean wroteRecently = session.lastWriteAt()
            .map(t -> t.isAfter(Instant.now().minusSeconds(10)))
            .orElse(false);
    DataSource db = wroteRecently ? leader : replicas.pick();   // others can tolerate a little lag
    return new JdbcTemplate(db).queryForObject(PROFILE_SQL, mapper, userId);
}

Also monitor lag on every follower and alert when it grows (say, past 5 seconds). Lag is the first thing to check when users report “my change disappeared”.

Failover

When the leader dies, writes stop until a follower is promoted. Doing that safely takes three steps:

  1. Detect it properly. One failed health check isn’t enough: it might be a network blip. Require several failures in a row, ideally seen from more than one place.
  2. Pick the most up-to-date follower and promote it. With async replication, any writes it never received are lost.
  3. Fence the old leader. If the old leader was only cut off, not dead, and comes back still thinking it’s in charge, you have two leaders taking writes: split brain. Cut off its access to storage or the network before the new one takes over.

Managed databases (RDS, Cloud SQL) and tools like Patroni for PostgreSQL handle this for you. Use them rather than writing your own failover.

Model 2: multi-leader

With one leader in the US, a user in Europe waits for a round trip across the Atlantic on every write: around 150 ms each way. Multi-leader replication puts a leader in each region. Users write to the nearest one, and leaders sync with each other in the background.

  • Good: fast local writes everywhere, and each region keeps working if the link between regions breaks.
  • Bad: two leaders can change the same data at the same time.
A product starts at a price of 100 dollars in both the US and EU leaders. At the same moment, a US admin sets it to 90 and an EU admin sets it to 95. Each leader accepts its own write. When they sync, the leaders disagree: 90 or 95? Below, four ways to resolve it: last write wins keeps the later timestamp and silently throws the other away; a business rule, such as keep the lower price; merge both, such as combining two shopping carts; or avoid the conflict by giving each record a home region that alone accepts its writes.
Two leaders, one row, two different answers. Every multi-leader system needs a rule for who wins.

Ways to resolve conflicts, from bluntest to best:

  • Last write wins (LWW). Keep the version with the later timestamp. Simple, but it silently throws away the other write, and server clocks are never perfectly in sync, so “later” can be wrong.
  • A business rule. “Keep the lower price.” “Keep the higher stock count.” Only works where such a rule makes sense.
  • Merge. Two edits to a shopping cart? Keep the items from both. Collaborative editors and CRDTs (data types designed to merge automatically) work this way.
  • Avoid conflicts. Give each user or record a home region, and send all its writes there. Conflicts can’t happen if only one leader ever writes a given row.

Use multi-leader only when you truly need fast writes in several regions, and keep critical data like account balances away from it.

Model 3: leaderless

No server is special. The client (or a coordinator node) sends each write to several nodes at once, and reads from several too. Cassandra, ScyllaDB and DynamoDB’s design ancestors work this way.

The trick that keeps it correct is the quorum:

Three nodes, N equals 3. A write of x equals 5 succeeds once two nodes, A and B, confirm it, so W equals 2. Node C is down and still has the old value x equals 0. A later read asks two nodes, B and C, so R equals 2. Because W plus R, 4, is greater than N, 3, the read and write sets must overlap, here at node B, so the read sees x equals 5. The client takes the newest version and writes it back to C, which is called read repair.
If the nodes you write to and the nodes you read from always overlap (W + R > N), every read reaches at least one node with the latest write.
  • N = how many copies of each piece of data (say 3).
  • W = how many must confirm a write (say 2).
  • R = how many are asked on a read (say 2).

If W + R > N, the nodes you read from always overlap with the nodes you wrote to, so at least one returns the latest value. The client picks the newest version and quietly writes it back to stale nodes (read repair).

// Java · Cassandra driver: quorum writes and reads (N = 3, so 2 of 3 each time)
session.execute(SimpleStatement.newInstance(
        "UPDATE users SET email = ? WHERE id = ?", email, userId)
    .setConsistencyLevel(DefaultConsistencyLevel.QUORUM));

Row row = session.execute(SimpleStatement.newInstance(
        "SELECT email FROM users WHERE id = ?", userId)
    .setConsistencyLevel(DefaultConsistencyLevel.QUORUM)).one();

You tune W and R per query. W=1 makes writes fast but risky; R=1 makes reads fast but possibly stale. The system stays up as long as enough nodes respond, with no failover step at all. The cost: concurrent writes to the same key still need a conflict rule (usually last-write-wins), and the overall guarantee is weaker than a single leader’s.

The three models side by side

Leader-follower Multi-leader Leaderless
Who takes writes One leader One per region Any node
Write conflicts None Yes, need a rule Yes, usually LWW
Leader dies Failover needed Other regions carry on Nothing special happens
Global write latency Slow far from the leader Fast everywhere Depends on the quorum
Simplicity Simplest Hard Medium
Typical use Most apps Multi-region apps, offline-first apps Huge always-on data (Cassandra, DynamoDB-style)

Start with leader-follower. It covers most systems. Move to the others only for a specific reason: writes in many regions, or availability that can’t wait for a failover.

What breaks, and how to fix it

What breaks What users see The fix
Replica lag Their own change seems to vanish Read-your-writes from the leader; alert on lag
Leader dies, no failover Every write fails; the app is read-only Automatic failover (managed DB or Patroni) with fencing
False failover Two leaders; data diverges Confirm failure from several checks; fence the old leader
Multi-leader conflicts Edits silently overwritten Home region per record, merge rules or CRDTs, not blind LWW
Quorum can’t be reached Writes fail when too many nodes are down Size N for failures you expect; spread nodes across zones

Puzzle 1: the disappearing write

With async replication, “saved” meant “saved on one machine”, and that machine died. The promoted follower never saw the write.

Use semi-synchronous replication for data you can’t lose: the leader only confirms once at least one follower has the change, so a promoted follower always has it. Writes get a little slower (one extra network round trip), which is why some systems apply it only to critical tables. How much loss is acceptable is a business decision with a name: the RPO (recovery point objective). For payments it’s zero; for view counts, a few seconds is fine.

Puzzle 2: split brain

There’s no right answer, and that’s the point. Last-write-wins picks whichever has the later timestamp and silently drops the other. Neither $100 nor $150 is likely to be the true balance.

Three ways out:

  • Don’t use multi-leader for balances. Give each account a home region, or keep money in a single-leader database.
  • Store operations, not results. Record “+50” and “−20” instead of “balance = 100”. Additions can be applied in any order and still give the same answer.
  • Detect true conflicts with version vectors and flag them for a business rule or a person to resolve, instead of guessing.

Puzzle 3: the thundering herd

10,000 connections arrive at once, at a server that was just promoted and has cold caches. It falls over, and the outage gets worse instead of better.

Make reconnection gentle:

  • Cap connection pools so the total can never exceed what the database handles.
  • Retry with exponential backoff and jitter so servers don’t all retry at the same instant.
  • Use a circuit breaker: after repeated failures, stop hammering the database and return a friendly “try again shortly” for a few seconds.
  • Put a connection pooler like PgBouncer in front, so thousands of app connections share a few hundred database ones.

Key takeaways

  1. Replication keeps copies on several machines for availability, latency, read capacity and durability. It is not a backup.
  2. Async is fast but can lose recent writes if the leader dies. Semi-sync waits for one replica and closes that gap.
  3. Leader-follower is the default: no conflicts, but you must handle replica lag and failover (with fencing).
  4. Multi-leader gives fast writes in every region and creates write conflicts. Avoid them with a home region per record.
  5. Leaderless uses quorums: when W + R > N, reads overlap with the latest write.
  6. Every copy can be behind. How far behind you can tolerate is the next question.

This opens the Consistency & CAP theorem thread. Replicas disagree for a while; next we’ll look at consistency models, the precise promises a system makes about what a read can return.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.