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:
- Who accepts writes? One server, several, or any of them?
- When is a write “done”? When one copy has it, or when several do?
- What happens when copies fall behind?
- What happens when the server taking writes dies?
Sync vs async: when is a write “done”?
This choice shapes everything else.
| 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.
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:
- 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.
- Pick the most up-to-date follower and promote it. With async replication, any writes it never received are lost.
- 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.
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:
- 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
- Replication keeps copies on several machines for availability, latency, read capacity and durability. It is not a backup.
- Async is fast but can lose recent writes if the leader dies. Semi-sync waits for one replica and closes that gap.
- Leader-follower is the default: no conflicts, but you must handle replica lag and failover (with fencing).
- Multi-leader gives fast writes in every region and creates write conflicts. Avoid them with a home region per record.
- Leaderless uses quorums: when W + R > N, reads overlap with the latest write.
- 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