Replication
Read first: Choosing a database
A single leader orders writes and ships a log of what the replica must replay. Synchronous replication waits for a replica and stalls on the slow one, while asynchronous replication acks first and can lose the tail at failover. A fence, a lease or a generation, stops the old primary from writing after you promote someone else.
Replication exists so one dead disk is not a dead dataset, and so a read can land somewhere other than the machine that took the write. Someone has to order the writes. Either one leader does, or several accept writes and you reconcile them. The bytes that move are a log. Whether the client is allowed to hear “committed” before a second machine has that log is the whole argument.
Core concepts
A single copy has two failures that look the same to a user: the machine is down, so you cannot read, and the disk is gone, so you have nothing to read. A replica is a second process applying the same changes. Choosing a database picked the shape of the data. Replication does not change that shape. It decides how many machines hold it, and what an acknowledgement means.
Single leader
One primary accepts writes. Each backup applies the same sequence. Readers can use a backup if they accept that it may be behind. The order of writes is the order the primary put in its log, which is easy to explain and easy to operate. There is one place a lock, a constraint, and a transaction naturally live.
The cost is that one machine. Every write goes there. When it dies, writes stop until a backup is promoted. Read scale is real: backups can serve reads. Write scale is not. Write scale is partitioning, and once you partition, this primary-and-backups pattern usually repeats per shard. Do not confuse “we added replicas” with “we can take more writes.”
Multi-leader
More than one node accepts writes, often one per site. A user in each region writes locally, and the leaders exchange logs. The moment the same key changes in two places, you have a conflict. Something has to merge. A last-writer-wins rule needs a total order, usually a timestamp plus a replica id. Clocks alone are a poor order: skew makes “later” a guess. A counter that both sides increment is not a last write at all. You need a merge that knows what an increment means, or you need one leader for that key.
This is the active-active shape. It is a legitimate design when a region must accept writes during a partition, and it is the wrong default in a new-grad design. One primary in one region, with a practiced failover, answers the interview. Multi-region design is where active-active belongs, as an advanced topic, after you can say what you do with a conflict.
Leaderless
Any replica can take a write. You write to W of N copies and read from R. If R plus W is greater than N, a read quorum overlaps a write quorum, so in the happy case, where you actually hit the nodes that hold the data, the reader sees the latest write. That overlap is not linearizability. Sloppy quorums, retries, and lost replies all break the story, and Quorums and leaders is the page that takes it apart.
The Dynamo paper is this design: a shopping cart that stays writable during a partition, with sloppy quorum and hinted handoff. If the preferred nodes are down, the write lands on fallback nodes, and a hint sends it home later. The overlap guarantee is weaker until the hint lands. That paper is not the product DynamoDB, which came later and uses a primary per partition. Say the paper or the product. Amazon Dynamo keeps them apart. For a first design, a leader is easier to reason about than a quorum you have not specified.
Synchronous and asynchronous
Synchronous replication means the primary does not acknowledge the client until the replica has stored the entry. A committed write is on two machines. A slow replica, or a dead one, stalls every write. If you wait for every replica, the slowest one sets the latency. Waiting for one, or for a majority, is a different contract. The majority version is the aside at the bottom.
Asynchronous replication means the primary acknowledges after its own log is durable, and the replica catches up later. Writes stay fast. A failover loses the tail: anything the primary acked and had not shipped is gone. A lower bound on that lag is the time to ship the entry. A same-datacenter round trip on the teaching list is 0.5 ms. Lag is not a constant. A stalled applier turns a fraction of a millisecond into a long prefix, and the lost tail is everything acked during that stall.
Lag and read-your-writes
You write to the primary. Your next read goes to a replica that has not applied it. The user does not see their own write, refreshes, and sends it again. That is a broken read-your-writes guarantee. The guarantee says a read in this session sees the writes this session has already completed.
Three ways to get it back. Read from the primary for a while after a write. Send a session token that means “I need log position at least N,” and let the replica refuse if it is behind so the read can go to the primary. Compare a version on the row and retry the primary on a miss. All three cost a primary read, or a retry, in exchange for not lying to the user.
Two neighbor guarantees are worth naming now and learning properly in Consistency models. Monotonic reads: a later read should not go to a replica further behind than one you already read, or a message reappears as missing. Consistent prefix: you do not observe a reply whose parent message is still in the unshipped tail, if the log ordered the parent first. Eventual consistency is the weaker statement people reach for: if updates stop, replicas converge. It says nothing about what this user reads before then.
A published example of the primary-read choice is Uber Schemaless. Each shard has a master and two minions. Replication to the minions is asynchronous. Reads default to the master so a client sees its write. If the master is down they can accept a write onto another node and hand it off later, the same idea as hinted handoff, which is a different contract and easy to mix up with “we always read the master.” Uber Schemaless and Ringpop is the full writeup. The number they published for a typical configuration is 4,096 shards. That is their scale, not your starting count.
Failover and fencing
Failover promotes a replica to primary. The dangerous moment is the old primary coming back, or never having noticed that it was demoted. Both accept writes. That is split brain, and the two logs disagree.
Fencing stops the old primary from committing. A lease expires, so it knows it should stop, but a lease plus a clock is a weak fence if the old process keeps running anyway. A generation number, also called a fencing token, is checked by storage: each epoch has a number, and a write from an older epoch is rejected. The new primary writes with the new number. The old one can still be alive. It cannot commit. Leader election for a service is this lease-plus-token, or a term in a consensus protocol. The bully algorithm and a bare clock are poor answers.
What a log ships
The replication stream is an ordered log of changes, each with a position. People call that position a log sequence number. An entry carries enough to redo the change: the key and the new value, or the operation, depending on the engine. The primary appends it locally. A sender reads from a position and pushes the following entries. The replica appends them and advances its stored position. It applies in order. If position 10 is missing, it cannot apply 11, or the row would skip a state. Lag is a prefix, not a random subset of writes. The gap between the primary’s position and the replica’s position is the tail.
Shipping the log is not shipping a full copy of the database on every commit, and it is not a promise that a reader on the replica can see the entry. The entry is visible there only after that replica applies it. Synchronous replication means the position you acknowledged is at or below the replica’s stored position. Asynchronous replication means the acknowledged position can sit ahead of every replica.
What the replica replays is a separate choice from when you ack.
Statement shipping replays the SQL text. The replica runs the statement again, including SET balance = balance - 10 and a call to NOW. If the replica’s row is not the row the primary saw, or the clock differs, the copies diverge. A short statement that changes a million rows ships a small log and does a large, possibly different, thing on the other side.
Row shipping replays the changed rows, the values the primary actually stored, not the statement. The primary applied the subtraction when the balance was 50 and recorded 40, and it recorded the timestamp it wrote. The replica sets 40 and that timestamp. It does not recompute. One statement that touches a million rows ships a million row images. Because the stream is logical, a replica can sometimes carry a different index. The copies still agree on the rows.
Log shipping replays the storage engine’s own write-ahead log. Page splits and byte-level changes, the physical consequence of the write. Apply is simple and fast, which is what you want for a failover clone. The replica has to be the same engine at a compatible version. It is a copy of the pages, so you do not hang a different schema on it and expect the log to still apply.
A row image and a page image can both travel in a log. The difference is what runs a second time: a statement, a row, or the engine’s own bytes. The contract is still the position. “We replicate” without “I ack at this position, and the replica has stored up to that position” is unfinished.
The local commit log from the indexing page is the same idea on one machine: append, then ack. Replication is that log, or a log derived from it, leaving the machine. An acknowledgement that the local log is durable is not an acknowledgement that a second site has it.
flowchart LR
client[Client]
old[Old primary]
store[Storage checks the generation]
newp[New primary]
client --> old
client --> newp
old --> store
newp --> store
A worked example
One primary takes the writes for a trip’s state. A single replica in the same datacenter applies the log asynchronously. The client sets a trip to accepted. You are about to promote the replica in a failure, and you need to know which acknowledgements were lies.
Assumptions, stated as assumptions. This primary handles 50 million writes a day. During the incident the replica is 200 ms behind, because the applier stalled, not because the network is slow. Healthy lag is a different number and we will compute it too. Log positions in the story are a sketch of that gap, not a metric from a real cluster.
day 86,400 seconds, shortcut about 100,000
rate 50,000,000 / 86,400 = 578.7 writes/s
shortcut 50,000,000 / 100,000 = 500 writes/s
stall 200 ms = 0.2 s
missing tail 578.7 * 0.2 = 115.7 writes, about 116
healthy lag one same-datacenter round trip, 0.5 ms
in flight 578.7 * 0.0005 = 0.29 writes
Apply Little’s law to the stall: backlog is arrival rate times the time behind. About 116 writes were acknowledged and are not on the replica. The healthy figure is the contrast, using the 0.5 ms round trip as a lower bound on lag rather than a promise. At that bound you have a fraction of a write in flight. Asynchronous replication to a nearby replica is not “we lose data all day.” It is “a stall widens a prefix, and failover cuts that prefix off.” What the replica missed is log records. It will not recompute a statement and invent them.
Sketch the log so the positions match the arithmetic. The primary has stored through position 5,000 and is acknowledging 5,000. The replica has stored through 5,000 minus 116, which is 4,884. Then the primary’s disk dies.
Every client who received an ack for a position from 4,885 through 5,000 was told the write committed. The promoted replica has never seen those entries. The trip the rider just watched flip to accepted flips back, because the only surviving log does not contain it. About 116 writes are in that set at this rate. If the product cannot bear that, you could not ack at the primary alone.
The retry makes it worse if you are careless. The client times out, or the user taps again, and sends “mark accepted” to the new primary. If the original write was in the lost tail, the retry does the right thing: the new primary applies it. If the original write was at position 4,800, already on the replica, a naive retry applies a second accept, or double-charges, unless the operation is idempotent. Idempotency and the exactly-once myth is the repair: a client-generated key, the outcome stored, the retry returns the stored outcome. Failover without that key turns a lost tail into a duplicate side effect for the writes that actually survived.
What synchronous would have changed. The primary does not ack 5,000 until the replica has stored 5,000. The crash before the ack leaves the client unsure, which is a timeout, not a lie. The write might be on the replica, if the ack packet was what died, or it might be absent, if the primary died before the send. The idempotency key makes those two outcomes the same from the client’s side. You did not lose an acknowledged write. You paid for that on every write, including the quiet hours.
Price the wait with distance, from the fiber figure. Light in fiber is about 200,000 km/s, about 200 km per millisecond. A 4,000 km path is 4,000 divided by 200, which is 20 ms one way and 40 ms round trip, before routers. A synchronous replica across that path adds a round-trip floor of about 40 ms to every commit. A planning band for coast-to-coast is tens of milliseconds. A cross-zone replica in one region is often around a millisecond. A same-zone replica is often a fraction of a millisecond. Pick the one you mean.
Throughput has to match the wait. If each write waits 40 ms and you do one at a time, the primary completes 1 divided by 0.040, which is 25 writes a second, far under 579. To hold about 579 writes a second while each takes 40 ms, Little’s law says you need 578.7 times 0.040, about 23 writes in flight. Each user still waits the 40 ms. Concurrency hides the throughput collapse. It does not hide the latency. A synchronous cross-country replica on a user-facing accept is a latency decision you should say out loud.
The fence, a minute later. You promoted the replica. It writes with generation 2. The old primary reboots, still believes it is the primary, and tries to append position 5,001 with generation 1. Storage rejects the older generation. Without that check both nodes accept writes, the rider’s accept lands on one, a cancellation lands on the other, and the merge is a support ticket. The generation is the fence. A runbook that says “promote the replica” and does not say where the generation is checked is half a failover.
Read-your-writes is the same incident in a smaller dose. Leave the primary alive and the replica 200 ms behind. The client writes “accepted,” gets the ack, and reads the replica to render the screen. The read misses. The client sends the accept again. You now have a duplicate in flight on top of a write that was never lost. The session token is the position the write returned, 5,000. The replica serves the read only if its position is at least 5,000. Otherwise the read goes to the primary. You pay one primary read for the sessions that just wrote, and you stop showing a stale rejection to the person you already acknowledged.
Tradeoffs
| Choice | What you keep | What you pay |
|---|---|---|
| Single leader, asynchronous | A fast ack, one order, simple operations | The tail past the replica’s position can vanish on failover |
| Single leader, synchronous to one replica | An ack means two machines stored it | Every write waits, and one slow replica stalls the primary |
| Synchronous across 4,000 km | A remote copy inside the ack | A round-trip floor near 40 ms on every commit, before routers |
| Multi-leader | A region can write during a partition | Conflicts, and a merge rule that is not “the clock will do it” |
| Leaderless, R plus W greater than N | A write succeeds without one primary | Overlap holds in the happy case only. Hints and retries weaken it |
| Statement replay | A compact log when the SQL is small | Nondeterministic statements make a replica that is silently different |
| Row replay | The values the primary stored, not a recomputation | A wide statement ships every row it changed |
| Physical log replay | A fast, faithful failover clone | The same engine, and no extra schema on the replica |
| Read from the primary after a write | Read-your-writes | You just spent the write capacity on reads, so the primary stays hot |
Uber’s default, read the master, is the last row. It is the right row when a missing read-your-writes is a user-visible bug and the primary can take the reads. It is the wrong row when you added replicas specifically because the primary could not take the reads, and then sent every read back. In that case the session token is doing the real work, and the replica has to be allowed to say no.
Pitfalls
- Acknowledging on the primary and reading a random replica. The symptom is a user who does not see the write you just confirmed, then submits it again.
- Calling three asynchronous replicas “we cannot lose a write.” The symptom is a failover that drops the tail, here about 116 writes for 200 ms at 579 per second, after you already told the clients they succeeded.
- Promoting a replica with no generation check. The symptom is split brain: the old primary and the new one both accept, and the logs diverge.
- Putting the synchronous replica in another region on the user path. The symptom is every accept paying a coast-to-coast round trip, floor about 40 ms for 4,000 km, and a one-at-a-time throughput near 25 writes a second.
- Retrying a non-idempotent accept after a timeout. The symptom is two accepts, or two charges, for the writes that had reached the survivor, and a missing accept for the ones that had not.
- Treating lag as a single average. The symptom is a replica that looks caught up all morning and is seconds behind during one stall, which is the only window that matters.
- Applying a replica’s log out of order because one entry failed. The symptom is a row that skipped a state. Lag has to stay a prefix.
- Using multi-leader as the default so the diagram has two regions. The symptom is a conflict on a key you have no merge rule for, discovered by a user.
In the interview
Say the topology in the first minute. One primary, one asynchronous replica in the same region, reads of a just-written key go to the primary or carry the log position. Failover promotes the replica and bumps a generation that storage checks. Then the number. At 50 million writes a day, about 580 a second, a 200 ms stall is about 116 acknowledged writes the replica does not have. That is the tail you lose if you promote during the stall. If the product cannot lose an acknowledged accept, the ack waits for the replica, and you say what the wait costs at the distance you picked.
Skip quorum arithmetic unless they ask for a leaderless store. Skip a consensus proof. If you mention Raft, one sentence is enough: a commit is a majority, and it does not make a cross-region system fast. The bully algorithm should not come out of your mouth.
The question that usually follows is “the old primary comes back.” The answer is the generation. Storage rejects the older epoch, so a write that hits the old process fails instead of forking the log. The question after that is the client retry. The answer is an idempotency key, because some of the in-flight writes were on the survivor and some were only on the disk you just lost.
Check yourself
The primary acks through log position 5000 and dies. The replica has stored through 4884. What do those clients actually have, and what does the fence stop?
Clients acked from 4885 through 5000 were told a write committed that the surviving log does not contain. Promoting the replica drops that tail. The fence is a generation check at storage. The old primary can reboot and try to write. An older generation is rejected, so it cannot fork a second history next to the new primary.
A client writes to the primary and reads a replica that is behind. Which guarantee broke, and how do you restore it without reading every key from the primary?
Read-your-writes broke. The session has to observe its own commit. A session token carries the log position the write returned. The replica serves the read only when it has stored at least that position, and otherwise the read goes to the primary. You pay the primary for the sessions that just wrote, not for every reader.
A synchronous replica is 4,000 km of fiber away. What round-trip floor do you add to each commit, and what throughput do you get if writes wait one at a time?
Fiber is about 200 km per millisecond, so 4,000 km is 20 ms one way and 40 ms round trip before routers. One-at-a-time commits complete 1 over 0.040, about 25 writes a second. Holding a higher rate means that many writes in flight, from rate times 0.040, and each user still waits the 40 ms.
You require R plus W greater than N, a preferred node is down, and the write goes to a fallback. Does the next read have to see that write?
Not yet. The overlap argument needs the read quorum to hit a node that actually stored the write. A sloppy quorum parked it on a fallback, and hinted handoff has not brought it home. Until the hint lands, a read of the preferred nodes can miss it. That is the availability you bought, and the guarantee you weakened.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Uber Schemaless; Amazon Dynamo, DeCandia and others; Raft, Ongaro and Ousterhout.