0% completed
Replication: Lag, Failover, and Split-Brain
On This Page
Part 1: Two Ways to Copy a Database
Part 2: How Far a Commit Travels
Part 3: Three Kinds of Lag
Part 4: Reading Your Own Writes
Part 5: What Happens During Failover
Part 6: Split-Brain and Fencing
Part 7: A Replica Is Not a Backup
Part 8: Using This in an Interview
Common Mistakes
Key Takeaways
A database replica is a copy of the database that another machine keeps up to date. A common belief about replicas has two parts. A replica always matches the main database, and for that reason it can also serve as a backup. Both parts are wrong in ways that matter.
A replica matches the main database as it was a moment ago. In a food delivery app, that moment is enough for a customer to place an order, tap "My orders," and see nothing. And a replica copies every change quickly, including a mistake such as a dropped table.
The lesson first covers how far replicas lag behind, and how to design around that delay. It then covers what happens when the main database fails, or only seems to fail.
Part 1: Two Ways to Copy a Database
Replication keeps copies of a database on more than one machine. Three roles describe the machines:
- The primary is usually the one machine that accepts all writes.
- The replicas apply the primary's changes and can serve reads.
- A standby is a replica kept ready to take over from the primary.
The running example is the delivery app's orders database on Postgres. The primary is in one zone, and there is a standby in each of two other zones. An availability zone, or zone, is one or more separate data centers inside one cloud region, with their own power and network. All numbers in this lesson are made-up examples.
Every change on the primary is first recorded in the write-ahead log, or WAL, so the database can be repaired from it after a crash. Replication sends this log, or rows decoded from it, to each replica. The table below compares the two ways to do it.
| Physical replication | Logical replication | |
|---|---|---|
| What is sent | The log's bytes, which describe changes to disk pages | Row changes, decoded from the log |
| What the replica is | An exact copy of the whole database server | A separate database that applies the rows it receives |
| Which tables | All of them | Only the tables you choose |
| Postgres versions | Must be the same major version | Can differ |
The last row needs one more term. A major version is a release that may change how data is stored on disk. Logical replication sends rows, not disk bytes, so a newer major version can apply them. That makes it the usual way to upgrade with very little downtime. Physical replication is simpler, so standbys usually use it.
Part 2: How Far a Commit Travels
Part 1 showed what the primary sends. This Part covers when the primary tells the client that a write is done. A commit is the moment a transaction's changes become permanent, and the client is told so. The design choice is how far a change travels before that moment. There are two options:
- In asynchronous replication, the primary answers once the change is on its own disk.
- In synchronous replication, the primary also waits for a standby to confirm.
Once the primary has a synchronous standby, the Postgres setting synchronous_commit says how far to wait. The diagram below shows where each value lets the commit return.
Step 1: local. The change is on the primary's disk. This is asynchronous.
Step 2: remote_write. The standby has received the change, but it is not yet on disk.
Step 3: on. The change is on the standby's disk, so it survives losing the primary, even if the standby also crashes.
Step 4: remote_apply. The standby has applied the change, so queries there can read it.
Notice that a reader on the standby can see the change only at step 4. Each step also adds a wait to every commit that uses it: about a millisecond for a standby in another zone, and tens of milliseconds in another region.
A synchronous standby that stops answering can stall all writes, because every commit waits for it. For this reason, teams often name two standbys and wait for either one. The setting can be changed for each transaction, and remote_apply is usually set only where it is needed.
Part 3: Three Kinds of Lag
The commit can return at step 1, while the standbys are still catching up. Replication lag is how far a replica is behind the primary, in time or in bytes of log. Postgres reports three lag figures for each standby, one for each later point in the diagram:
- Write lag is the time until the standby has received the change.
- Flush lag is the time until the change is on the standby's disk.
- Replay lag is the time until the standby has applied the change.
A change that has arrived, or has even reached disk, stays invisible to the standby's readers until it is applied. For this reason, replay lag decides whether a read is stale, and it is the lag to alert on. Write and flush lag show something else: how much recent data a failover could lose.
Part 4: Reading Your Own Writes
Replay lag is what the customer from the opening ran into. Read-your-writes is a guarantee that a user always sees the changes they made, even if other users see them later.
The order history page reads from the standbys, where replay lag is usually well under a second. That delay is fine for restaurant ratings. It is not fine for the customer who just ordered and taps "My orders." Three fixes are common.
Fix 1: Read from the primary briefly after a write. For a few seconds, that user's reads go to the primary. It is simple, but a standby that lags past the window still returns stale data.
Fix 2: Wait until the standby reaches the write. The app saves the log position of the order's commit. A standby serves the read only once its replay has reached that position. Otherwise, the app waits or reads from the primary.
Fix 3: Make the commit wait. With remote_apply on the order's transaction, the commit returns only after a synchronous standby has applied it. Reads from that standby then see the order, at the cost of a slower commit.
Not every page needs one of these fixes. The question "How stale can this be?" from The First Ten Minutes sorts the reads that need a fix from those that do not.
Part 5: What Happens During Failover
Parts 2 to 4 assumed the primary is running. Now it fails. Failover makes a standby the new primary when the old one fails. The diagram below shows a safe order of steps for the orders database.
Step 1: Detect. Health checks stop getting answers. The system waits for several missed checks, perhaps ten to thirty seconds, so that a short network delay does not start a failover.
Step 2: Agree. A small group of machines votes, and a majority must agree that the primary is gone.
Step 3: Fence the old primary. Fencing means making sure the old primary can no longer accept writes.
Step 4: Promote. The standby with the most changes becomes the primary. In Postgres, promotion starts a new timeline, which is a numbered branch of the log's history. The timeline keeps the two histories from being mixed.
Step 5: Move traffic. Clients reconnect, often through a switch of the connection pooler or a DNS name.
Step 6: Rebuild. The old primary later returns as a replica of the new one, after any changes that only it had are removed.
Notice the line at the bottom of the diagram: nothing is promoted until step 3 is confirmed. Part 6 explains why that order matters.
Step 4 has a cost with asynchronous replication. It can lose orders that the old primary confirmed but never sent to a standby. Waiting for a standby's disk at commit, the on setting from Part 2, removes that loss, at the cost of a slower commit.
Part 6: Split-Brain and Fencing
Step 3 of the failover exists to prevent one failure. Split-brain is the state in which two machines both act as primary and both accept writes, so their data diverges.
It happens when the primary is cut off, not dead. Suppose the network cuts zone A off from the other two zones. Zones B and C promote the standby in zone B. Meanwhile, app servers in zone A keep sending orders to the old primary. The diagram below shows what follows.
Notice order 1001 on both sides. The old primary gives it to Ana, and the new primary gives it to Ben. Both primaries can give the same order number to two different orders. When the network returns, someone must compare the two histories by hand.
An unreachable primary is not a dead primary. For this reason, fencing must finish before promotion starts. Three ways to fence are common.
- Stop the machine through the cloud provider's API.
- Remove its network access.
- Make it step down. In tools such as Patroni, a primary that cannot reach the majority within a set time stops accepting writes.
If the system cannot prove that the old primary has stopped writing, waiting is safer than promoting. A longer outage is better than two primaries.
Part 7: A Replica Is Not a Backup
The opening named a second belief: that a replica can serve as a backup. Replication copies every change quickly and exactly, including mistakes. If an engineer drops the orders table, every standby applies the drop within moments. A synchronous standby helps least, because it is the most current.
A delayed replica applies changes a fixed time late, such as one hour. In Postgres, recovery_min_apply_delay sets this delay. After the mistake, an operator stops its replay before the drop. The operator then copies the table back or promotes the replica. That avoids a full restore, which can take hours.
The delayed replica serves no useful reads, since its only job is to undo human error. Backups are still required, because a mistake noticed after an hour reaches the delayed replica too.
Part 8: Using This in an Interview
Replication usually enters the high-level design, the first sketch of the whole system. Here is a short answer for the delivery app.
"Each commit waits until one of two standbys has the change on disk, so a failover loses no confirmed orders. History reads go to the standbys, but a customer's own reads wait until the standby has replayed their order. The old primary is fenced before anything is promoted."
Expect two follow-up questions. "What if the network cuts the primary off from the standbys?" Explain the majority vote and the fence. "Why not make every standby synchronous?" Every commit would wait for the slowest one, and one failure would stop all writes.
Common Mistakes
Mistake 1: Sending reads to replicas without a plan for lag. Decide which pages need read-your-writes, and give those reads a fix.
Mistake 2: Treating an unreachable primary as dead. Promoting without a confirmed fence can cause split-brain, because the old primary may still accept writes.
Mistake 3: Calling replicas a backup. They copy a mistake within moments, so only a delayed replica or a backup undoes it.
Key Takeaways
- Physical replication copies changes to disk pages, and logical replication copies rows. Only logical replication can cross a major version.
- Synchronous replication chooses how far each commit travels. Each point adds a wait, and
remote_applywaits until the change is readable on the standby. - Replay lag decides whether a read is stale. Give read-your-writes only to the pages that need it.
- Fence before you promote. An unreachable primary may still be accepting writes.
- In a system design interview, state the replication mode, what a failover can lose, and how the old primary is fenced.
The next lesson, Connection Pooling and the Database Thundering Herd, explains why databases often fail at peak because of too many connections.
Reading Progress
0%
On This Page
Part 1: Two Ways to Copy a Database
Part 2: How Far a Commit Travels
Part 3: Three Kinds of Lag
Part 4: Reading Your Own Writes
Part 5: What Happens During Failover
Part 6: Split-Brain and Fencing
Part 7: A Replica Is Not a Backup
Part 8: Using This in an Interview
Common Mistakes
Key Takeaways