Replication
Copies of your data make reads fast and keep you running. They also make users see the past, unless you plan for it.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
Ravi changes his delivery city from Pune to Delhi in a shopping app. He taps Save and sees "Saved". The page reloads, and the city still says Pune.
He taps Save again. Same result. He writes to support: "Your app does not save my address." Five seconds later he refreshes once more, and now it says Delhi.
Nothing was lost. The write went to the leader, the one database that takes writes. The page read came from a copy that was 3 seconds behind. The team had added copies last month to handle more reads. Nobody had asked what users would see while a copy catches up.
This bug is common, hard to reproduce on a laptop, and easy to prevent once you know its name.
The idea in simple words
Replication means keeping the same data on several machines. You do it for three reasons. Reads can be spread across many machines. A copy can take over if one machine dies. And a copy near the user can answer faster.
The most common setup has one leader and some followers. All writes go to the leader. The leader sends each change to every follower, and the followers apply the changes in the same order. Reads can go to the leader or to any follower. 1
The key idea. A follower is a copy of the past. How far in the past is the replication lag. Every read from a follower must be fine with seeing that past.
Most of the time the lag is small. Postgres says it is typically under one second when the standby can keep up. 2 But that is not a promise. Our advice: plan for the lag to grow much larger under heavy load, a long query, or a network problem.
How it works
Step through Ravi's bug. Use Next and Back, or the ← and → keys.
- The app saves a new city, Delhi, for the user. The write goes to the leader. The leader saves it and says OK.
- The leader sends the change to the follower in the background. Today the follower is slow, so the change takes 3 seconds.
- The app reloads the profile page. To spread the load, reads go to a follower.
- The follower still has the old value, Pune. The user thinks the save failed and may try again or call support.
- 3 seconds later the change reaches the follower. Now it says Delhi. Nothing was lost; the user just read too early.
- One fix: for a short time after a user writes, read that user's own data from the leader. This gives read-your-writes.
Now try it yourself. Move the sliders to change the lag and the moment you read.
Try it: read from a follower that is behind
Sync or async
The big choice is when the leader says "done" to the client.
With synchronous replication, the leader waits until a follower confirms it has the change. By default, Postgres waits until the commit is written to disk on both servers. The cost is at least one network round trip on every commit. 2
With asynchronous replication, the leader says "done" at once and sends the change later. Writes are fast. But if the leader crashes, its newest commits may never have reached a follower. Postgres and MySQL both replicate asynchronously by default, and both docs warn about this data loss. 2 3
MySQL also has a middle option, semisynchronous replication: the leader waits until at least one replica has received and logged the change. If no replica answers before a timeout, it falls back to async. 3
Lag bugs, and their names
Two lag bugs come up again and again. 1
- Read-your-writes. After you save something, your own next read should show it. Ravi's bug breaks this. Other users may see the change a bit later, and that is usually fine. 5
- Monotonic reads. Your reads should never go back in time. Imagine you refresh twice. The first read hits a fresh follower and shows a new comment. The second hits a slow follower, and the comment is gone. 6
Common fixes: read a user's own recent data from the leader for a short time after they write. Send all of one user's reads to the same follower. Or make the client remember the last version it saw, and skip followers that are behind it.
Failover and split-brain
When the leader dies, a follower must become the new leader. This is failover. It sounds simple, but each step can go wrong. 1
First, you must decide the leader is dead. You usually use a timeout. Too short, and a slow leader gets replaced for no reason. Second, you pick the follower with the most data. With async replication, some recent writes may be missing. Third, every client must send writes to the new leader.
The worst case is split-brain: the old leader is still alive and still takes writes. Now two nodes think they are the leader. Their data goes in two directions.
This happened to GitHub in October 2018. A network cut lasted 43 seconds. In that time, their failover tool made database servers on the US West Coast the new leaders. Several seconds of writes on the East Coast never reached the West. Then the West took writes for nearly 40 minutes. Both sides now had writes the other did not have. 4
GitHub chose to keep user data correct over coming back fast. The site was degraded for 24 hours and 11 minutes while they put the data back together. 4
Two other shapes, briefly
Multi-leader. Each data centre has its own leader, and the leaders copy to each other. Writes are fast everywhere. But two people can change the same row in two places, and you must resolve the conflict. 1
Leaderless. The client writes to several copies and reads from several copies. Amazon's Dynamo made this popular, and Cassandra works this way. With n copies, you write to w of them and read from r. If w + r > n, at least one copy you read has the latest write. With 3 copies, w = 2 and r = 2 is a common quorum. 1
Trade-offs
| Setup | Lose writes on crash? | Cost | Use it when |
|---|---|---|---|
| Leader + async followers | Yes The newest commits may be lost on failover. | Fast writes. Stale reads from followers. | Most web apps. It is the default in Postgres and MySQL. |
| Leader + one sync follower | No , unless both crash at once. | Every commit waits for a round trip. If the sync follower is down, writes can stall. | Money, orders, anything you must not lose. |
| Multi-leader | Yes Conflicts can drop one side's change. | You must design conflict rules. | Several regions must accept writes, or apps must work offline. |
| Leaderless with quorums | Depends on w and r. | More copies per request. Edge cases with lag still exist. | Very high write volume, and you can live with some stale reads. |
Simple rule: start with one leader and async followers. Then decide, for each read, whether it may see stale data.
At work: how a senior uses this
- For every new read path, ask: "What does the user see if this read is 5 seconds old?" If the answer is "a bug report", read from the leader.
- Watch replication lag on a dashboard, and alert on it. A follower that is minutes behind is a quiet incident.
- After a write, send that user's reads to the leader for a short window. Make the window longer than your normal lag.
- Ask how failover works before you need it. Who decides the leader is dead? What stops the old leader from taking writes?
- Practise failover in a test environment. Measure how many writes you lose and how long clients take to find the new leader.
- Know your settings. "Async by default" means a crash can lose your last commits. 2
With AI
What to ask the agent
"We read profiles from a Postgres read replica. Change the code so that for 10 seconds after a user updates their profile, that user's reads go to the primary."
"Write an integration test with a primary and a replica where replication is paused. Assert that a user's own profile read after a save shows the new value."
"List every query in this service that reads from a replica. For each, tell me what goes wrong if the data is 30 seconds old."
What to check yourself
- The "read from leader" window really covers your worst normal lag, not just the average.
- A connection pool or ORM (a library that maps code objects to database rows) did not quietly send writes, or reads inside a transaction, to the replica.
- Reads that check a rule before a write, like "is the coupon still unused?", go to the leader.
- The test really pauses or slows replication. A test with zero lag proves nothing.
- Failover scripts stop the old leader from taking writes before they promote a new one.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 6 sources and related lessons
- Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly)
1st edition (2017): chapter 5, Replication (leaders and followers, replication lag, multi-leader, leaderless and quorums). - PostgreSQL documentation: High Availability, Load Balancing, and Replication (Log-Shipping Standby Servers) (opens in a new tab)
Sections on streaming replication and synchronous replication. Shows that replication is async by default and what sync costs. - MySQL 8.4 Reference Manual: Semisynchronous Replication (opens in a new tab)
Why async replication can lose committed writes on failover, and what waiting for one replica buys you. - GitHub, “October 21 post-incident analysis” (opens in a new tab)
A 43-second network cut, an automatic failover across the US, and writes on both coasts that could not be merged. - Jepsen, Consistency models: Read Your Writes (opens in a new tab)
A short, exact definition of the read-your-writes guarantee. - Jepsen, Consistency models: Monotonic Reads (opens in a new tab)
A short, exact definition of monotonic reads.
Real incident: GitHub, 21 Oct 2018: GitHub outage: a 43-second network cut caused a day of trouble
Case studies: Amazon: How Dynamo kept the shopping cart always writable
Related: Quorums and leaderless replication · CAP, PACELC and consistency models · Leader election and leases · Multi-region systems and data locality
Next: Transactions and isolation levels. It covers bugs inside one database, even with no copies at all. For how one database does this in practice, see PostgreSQL in depth.