System Design

Core Concepts

Replication and Leader Election

A single machine fails by stopping. A replicated system fails by disagreeing. Replication does not remove failure, it converts a loud failure into a quiet one, and leader election is where the conversion happens.

Why you are doing this at all

On 21 October 2018, GitHub was replacing a piece of failing optical network equipment. The work cut their main East Coast facility off from the rest of their network for 43 seconds. Service was degraded for the next 24 hours.

The network came back almost at once, and nothing was broken for those 24 hours. The day went on something else. During those 43 seconds, two halves of a replicated MySQL setup had each done something reasonable. Afterwards, nobody could safely say which set of writes was the real one.

This article is about the gap between those 43 seconds and those 24 hours.

A database on one machine has one failure worth planning for: it stops. Everyone notices at once, and nobody is confused about what happened. A machine that is off can't serve anyone a wrong answer.

If you replicate it, keeping copies of the data on several machines, the stopping problem mostly goes away. A new kind of problem takes its place. Two nodes hold different data, and both answer questions. A write returns success and then disappears. Two processes both believe they are the leader, the one node allowed to accept writes, and each has good reason to believe it. A replica is 40 minutes behind, and its health check is green.

Replication does not remove failure. It turns a loud failure into a quiet one. You trade "the database is down" for "the database is giving wrong answers". Quiet failures cost much more, because your monitoring was built to catch the loud kind.

Everything below follows from that trade. The acknowledgement level is the point at which a write is reported as successful. The level you pick decides which wrong answer you get after a failover, when a replica takes over from a failed leader. The number of replicas decides how many nodes can disagree. And leader election exists only because the question "is it up?" has no exact answer. The best you can do is a guess with a timeout on it.

Five things people call replication

Replication means keeping more than one copy of the same data, and keeping every copy up to date. It buys availability and read throughput.

Backup is a copy of the data as it was at some moment in the past, which you can go back to. It protects you from writes you regret.

These are different things, and neither one can replace the other. Teams keep losing data because they treat them as the same.

Partitioning puts different data on different machines. It is independent of replication, and you can have either one without the other. Partitioning buys write throughput, and replication does not. The partitioning article covers it.

Caching is replication with a TTL (time to live, how long a copy is kept before it expires), with no durability, and with permission to be wrong. Every cache tier is a replica. Someone chose how stale it may be in a config file, usually without realising they were making a consistency decision.

Consensus means getting several nodes to agree on one ordered list of values. Raft and Paxos are the best-known ways to do it. You can build replication on consensus, but most replication isn't built that way. People who mix the two up reach for Raft when all they needed was a follower, a copy that replays the leader's writes, and an alert.

What it buys, and what it does not

The list of things replication does not do is longer than the list of things it does.

It buys availability, but only if failover is automatic and correct. It buys read throughput, but only as far as your product can tolerate stale reads. Deciding which reads may be stale is a product decision, not a capacity one. It buys durability against hardware loss, if the copies sit in different failure domains: places that do not fail together, such as separate racks or separate data centres.

It does not buy write throughput. It does not buy storage headroom. It does not protect against a bad migration, a bad deploy, or a bad DELETE. And it makes your system harder to run in every way, which matters, because you will be the one running it at 3am.

When to skip it

If you can rebuild the data from a durable source in less time than your outage budget allows, replication is the expensive option. A search index, a recommendation cache, a derived aggregate table and a materialised view are all like this. For each of them, "rebuild it" is often a better answer than "replicate it". You can test a rebuild on a quiet Tuesday. A failover usually gets its first real test during an incident.

The toolkit

The axis that matters: where the acknowledgement comes from

Almost every argument about replication comes down to one question: when your write returns success, what is guaranteed to have happened?

PostgreSQL exposes the answer as one setting, synchronous_commit, so it's a good place to see all the options at once. In Postgres, the leader is called the primary, and a standby is a replica that receives the primary's log. The setting takes five values. Each one waits for one more step than the one before, so together they form a ladder.

levelsuccess meanslost if the leader dies now
offthe leader accepted it into memoryrecent committed transactions, even with no replica involved
localthe leader flushed it to its own diskeverything not yet shipped to a replica
remote_writea standby received it and wrote to its filesystemwrites lost if the standby's OS also crashes
on (default)a standby flushed it to durable storagenothing, if at least one standby survives
remote_applya standby applied it and it is visible to readersnothing, and reads on that standby cannot be stale

These are not five grades of quality. Each one fails in a different way. remote_write protects you if Postgres crashes on the standby, but not if the standby's operating system crashes, because the write may still be in the operating system's memory. on keeps your data safe, but a reader on the standby may still not see the write. Only remote_apply closes that gap, and then every commit waits for the standby to replay the write.

Where each setting says yes
A write moves left to right, from the leader's memory to a standby that has applied it. Each yellow setting sits under the step where the client gets its success. The text below each step is what is lost if the leader dies at that moment: red where writes can be lost, green where nothing is. Each step to the right adds to the wait on every commit.A write moves left to right, from the leader's memory to a standby that has applied it. Each yellow setting sits under the step where the client gets its success. The text below each step is what is lost if the leader dies at that moment: red where writes can be lost, green where nothing is. Each step to the right adds to the wait on every commit.
Each later step loses less if the leader dies, and every commit waits longer. A write moves left to right, from the leader's memory to a standby that has applied it. Each yellow setting sits under the step where the client gets its success. The text below each step is what is lost if the leader dies at that moment: red where writes can be lost, green where nothing is. Each step to the right adds to the wait on every commit.

MySQL has the same ladder, with a less obvious trap in it. MySQL calls the leader the source. In semi-synchronous replication, the source waits for at least one replica to confirm it has received a transaction before it tells the client. The rpl_semi_sync_master_wait_point setting decides when that wait happens, and it has two values. The difference between them sounds minor, and it is not.

With AFTER_SYNC, the default, the source waits for the replica's acknowledgement before it commits to its storage engine. With AFTER_COMMIT, it commits first and then waits. So with AFTER_COMMIT, other clients can read the transaction in the gap before the replica acknowledges it. If the source dies in that gap and you fail over, the value those clients read no longer exists. A user was shown a value, the value was then taken back, and nobody got an error.

A read that a failover takes back
The source commits balance = 50 before the replica has the change (1). Client B reads 50 (2). The source dies before it sends the change, so the replica never gets it (3). The replica is promoted with 40, and client B's next read returns 40, in red (4). Nobody gets an error at any point.The source commits balance = 50 before the replica has the change (1). Client B reads 50 (2). The source dies before it sends the change, so the replica never gets it (3). The replica is promoted with 40, and client B's next read returns 40, in red (4). Nobody gets an error at any point.
With AFTER_COMMIT, a client can read a value that a failover then erases. The source commits balance = 50 before the replica has the change (1). Client B reads 50 (2). The source dies before it sends the change, so the replica never gets it (3). The replica is promoted with 40, and client B's next read returns 40, in red (4). Nobody gets an error at any point.

This is a quiet failure, and one configuration flag decides whether you can have it.

Quorums, and why even numbers are strictly worse

A quorum is the number of nodes that must accept a write before it counts. For a majority quorum, that is floor(N/2) + 1 of the N nodes. If you work this out for each replica count, the even counts come out badly.

Back of envelopeWrite unavailability by replica count, majority quorum, 99% per node
Each node independently up 99% of the time.
A write needs floor(N/2)+1 nodes.

  N   quorum   tolerates   P(no quorum)   minutes/year
  ────────────────────────────────────────────────────
  1        1           0      1.00e-02          5,256
  2        2           0      1.99e-02         10,459
  3        2           1      2.98e-04            157
  4        3           1      5.92e-04            311
  5        3           2      9.85e-06            5.2
  6        4           2      1.96e-05           10.3
  7        4           3      3.42e-07           0.18
  8        5           3      6.78e-07           0.36

Two replicas are twice as bad as one, because a majority of
two is two. Four are twice as bad as three. Six are twice as
bad as five. Every even count pays for a machine and tolerates
no more failures than the odd count below it, while adding one
more thing that can be down.

Two replicas are worse than one machine. This surprises people, and it is not a trick. A majority of two is two. So a two-node majority quorum fails whenever either node fails, which happens twice as often as one node failing. The second machine doubled your exposure and bought nothing.

Write downtime by replica count
Each bar is the minutes a year with no write majority, on a log scale. The teal bars are the odd counts and the red bars the even ones. Two replicas lose 10,459 minutes a year against 5,256 for one, and each even count is about twice the odd count before it.Each bar is the minutes a year with no write majority, on a log scale. The teal bars are the odd counts and the red bars the even ones. Two replicas lose 10,459 minutes a year against 5,256 for one, and each even count is about twice the odd count before it.
Every even count is worse than the odd count below it. Each bar is the minutes a year with no write majority, on a log scale. The teal bars are the odd counts and the red bars the even ones. Two replicas lose 10,459 minutes a year against 5,256 for one, and each even count is about twice the odd count before it.

Why quorum beats waiting for everyone

If a majority is enough, you do not wait for the slowest replica. You wait for one near the middle, and in the tail that makes a huge difference. The tail is the slowest one percent or so of writes, the part your p99 latency measures. The p99 is the latency that 99 percent of writes come in under.

Back of envelopeQuorum against full synchrony, per write
Each replica independently exceeds its own p99 latency 1% of
the time, independently.

Wait for all 5 replicas: delayed if ANY is slow
  1 − 0.99^5                              = 4.90%

Wait for a quorum, 3 of 5: delayed only if 3+ are slow
  C(5,3)(0.01)³(0.99)² + C(5,4)(0.01)⁴(0.99) + (0.01)⁵
  = 9.80e-6 + 4.95e-8 + 1e-10             = 0.00099%

  ─────────────────────────────────────────────────────
  full synchrony   1 write in 20 hits a slow replica
  quorum           1 write in 101,000
                                          = 4,975x fewer

Same hardware, same replicas, same network. The only
difference is how many acknowledgements you insist on, and
it moves the tail by nearly four orders of magnitude.

This is the strongest argument for majority quorums over "replicate synchronously to everything", and it is about the tail, not about throughput. If you wait for all N replicas, your write latency is the maximum of N samples, and it gets worse each time you add a replica. If you wait for a majority, it is roughly the median, and the median barely moves.

Slow writes as replicas are added
The red line waits for every replica, so a write is slow if any replica is slow: 1 in 20 at five replicas, 1 in 12 at nine. The green line waits for a majority, so a write is slow only if most replicas are slow at once: 1 in 101,000 at five. The vertical axis is a log scale.The red line waits for every replica, so a write is slow if any replica is slow: 1 in 20 at five replicas, 1 in 12 at nine. The green line waits for a majority, so a write is slow only if most replicas are slow at once: 1 in 101,000 at five. The vertical axis is a log scale.
Waiting for every replica gets worse with each one, and waiting for a majority gets better. The red line waits for every replica, so a write is slow if any replica is slow: 1 in 20 at five replicas, 1 in 12 at nine. The green line waits for a majority, so a write is slow only if most replicas are slow at once: 1 in 101,000 at five. The vertical axis is a log scale.

Replication lag is a queue, not a delay

Replication lag is how far a follower is behind the leader. It is reported in seconds, so people reason about it as latency. It is not latency. It is a queue depth divided by a drain rate: the writes still waiting to be applied, divided by how fast the follower applies them. Queues have a threshold that delays do not have. While writes arrive slower than the follower can apply them, the queue stays empty. Once they arrive faster, the queue grows for as long as that lasts.

MySQL used to apply the replication stream with a single thread. A leader with sixteen writers running at once fed a follower that replayed their writes one at a time. Modern MySQL applies in parallel, and replica_parallel_workers has defaulted to 4 since version 8.0.27, so the gap is smaller than it was. It is still there. A follower can only run in parallel the writes it can safely reorder, and that is never simply as many as the leader ran at once.

Back of envelopeTen minutes of overload, and how long it actually lasts
Leader commits at peak                    30,000 writes/s
Follower applies at                       12,000 writes/s
Backlog grows at                          18,000 writes/s

After 10 minutes of peak
  18,000 × 600                          = 10.8M writes behind
  time to apply them  10.8M / 12,000    = 900 s = 15 minutes
  → lag peaks at 15 minutes, 15 minutes after the overload ends

Peak ends, off-peak write rate            8,000 writes/s
  drain rate  12,000 − 8,000            = 4,000 writes/s
  drain time  10.8M / 4,000             = 2,700 s = 45 minutes

  ────────────────────────────────────────────────────────
  10 minutes of overload
  → 15 minutes of lag
  → 45 minutes to recover

And if the off-peak rate were 12,000/s or higher, the drain
rate is zero or negative and it never recovers at all. No
amount of waiting fixes it, because waiting is not the
missing ingredient.

Two things follow, and both go against how lag is usually discussed.

Lag is the sum of past overload, not a measure of current load. Your lag graph and your load graph will not look alike. In the worksheet, reported lag keeps climbing for 15 minutes after the load has dropped, so it peaks long after the load did. An alert that fires on lag is telling you about something that happened a while ago.

Adding replicas does not reduce lag. Every replica applies the same stream at the same rate. A fifth follower is one more follower that is 15 minutes behind, and the leader has a little more to send. The only things you can change are the write rate, how much of the apply runs in parallel, and the size of the transactions.

Ten minutes of overload
The top panel is the leader's write rate, 30,000 a second for 10 minutes, against a follower that applies 12,000. The bottom panel is the lag the follower reports. It is 6 minutes when the load drops, peaks at 15 minutes another 15 minutes later, and reaches zero 45 minutes after the drop. The grey dashed line is the same overload followed by 12,000 writes a second, and there lag never comes down.The top panel is the leader's write rate, 30,000 a second for 10 minutes, against a follower that applies 12,000. The bottom panel is the lag the follower reports. It is 6 minutes when the load drops, peaks at 15 minutes another 15 minutes later, and reaches zero 45 minutes after the drop. The grey dashed line is the same overload followed by 12,000 writes a second, and there lag never comes down.
Lag keeps rising for 15 minutes after the load drops. The top panel is the leader's write rate, 30,000 a second for 10 minutes, against a follower that applies 12,000. The bottom panel is the lag the follower reports. It is 6 minutes when the load drops, peaks at 15 minutes another 15 minutes later, and reaches zero 45 minutes after the drop. The grey dashed line is the same overload followed by 12,000 writes a second, and there lag never comes down.

Leaders: one, several, or none

There are three topologies, and the one you choose decides which problems you can have.

topologywrites go tomakes easymakes impossiblewho runs it
single leaderone nodeordering, uniqueness, transactionswrite availability during failover, write scalingPostgres, MySQL, most OLTP
multi leaderany of severallocal write latency, surviving region loss for writesconflict-free updates, sane uniquenessactive-active setups, CRDT stores
leaderlessa quorum of nodesuniform availability, no failover eventordering, read-modify-writeDynamo, Cassandra, Riak

Single leader is the right default. It gives you one place where the order of writes is decided, and that is what makes uniqueness constraints, auto-increment and multi-row transactions possible at all. Everything hard about a single leader happens in one event, the failover. Everything hard about the other two topologies is spread across every write, for as long as the system runs.

Multi leader needs a specific warning. It does not remove the coordination problem. It moves it from write time to read time, where it is called conflict resolution. So ask what happens when the same row is updated in two regions in the same second. If you can't answer that before you build it, you haven't chosen multi leader. You have chosen to find out later.

Leader election is a bet you cannot avoid

Every election protocol rests on one fact.

You cannot detect that a node has failed. You can only detect that it has not responded, and those are different things. A node that has crashed and a node in a 1.5 second garbage collection (GC) pause look exactly the same from outside: both are silent. So is a node behind an overloaded switch. So is a node whose virtual machine was paused while it was moved to another host, which is called live migration.

So every leader election protocol contains a timeout, and that timeout is a bet. It says: if I have not heard from you in T, I will act as though you are dead. Sometimes the bet is wrong. When it is wrong, you get two leaders.

etcd, a key-value store built on Raft, publishes tuning guidance with real numbers. The leader sends a heartbeat, a small "I am alive" message, every 100ms by default. The default election timeout is 1000ms. That is how long a follower waits without a heartbeat before it starts an election. etcd recommends an election timeout of at least 10 times the round trip time between members, and a heartbeat interval close to that round trip time. If a leader misses two heartbeat intervals, etcd logs a warning that it failed to send a heartbeat on time. The Raft paper has each server pick its election timeout at random from a range, 150ms to 300ms in its example. That way the servers don't all time out together and split the vote.

The election timeout sets a floor under your failover time, because nobody takes over until it runs out. It also sets a ceiling on the pause a leader can survive, because a longer pause ends its leadership. The two limits pull in opposite directions.

Back of envelopeThe pause that gets your leader killed
etcd default election timeout                    1,000 ms
A JVM leader with a full GC pause of             1,500 ms

  1,500 > 1,000 → followers declare the leader dead
  → election, log catch-up, client reconnection
  → the old leader wakes up still believing it leads

If that pause happens every 20 minutes
  3 per hour × 24                        = 72 failovers/day

Raise the timeout to 3,000 ms and the pauses stop causing
elections. You have also tripled the time to detect a real
failure, on every node, forever.

There is no timeout that is both. The way out is not tuning,
it is refusing to let a process that can pause be the thing
whose silence means death.
Pauses against the election timeout
Anything to the right of a timeout line, in the red band, ends the leader's term. With etcd's 1 second default, a 1.5 second GC pause replaces a leader that was only paused. With the timeout raised to 3 seconds, the GC pause survives, in green. A 30 second freeze still replaces the leader, and every real crash now takes 3 seconds to notice. The time axis is a log scale.Anything to the right of a timeout line, in the red band, ends the leader's term. With etcd's 1 second default, a 1.5 second GC pause replaces a leader that was only paused. With the timeout raised to 3 seconds, the GC pause survives, in green. A 30 second freeze still replaces the leader, and every real crash now takes 3 seconds to notice. The time axis is a log scale.
Every timeout either replaces a paused leader or is slow to notice a crash. Anything to the right of a timeout line, in the red band, ends the leader's term. With etcd's 1 second default, a 1.5 second GC pause replaces a leader that was only paused. With the timeout raised to 3 seconds, the GC pause survives, in green. A 30 second freeze still replaces the leader, and every real crash now takes 3 seconds to notice. The time axis is a log scale.

Fencing, epochs, and the number that makes it correct

So the bet is sometimes wrong, and sometimes two nodes both believe they lead. You can't prevent that, but you can make it harmless, and there is one way to do it.

Every election increments a number, and the resource being protected rejects anything carrying an old one.

The number is usually called the epoch. The resource is whatever the leader writes to, such as a database or a file server. Rejecting writes that carry an old number is called fencing, and a number used this way is a fencing token.

Here is how it plays out. The old leader holds a lease, a lock with a time limit that expires unless the holder keeps renewing it. It wakes from its pause, still sure the lease is valid, and tries to write. The storage layer looks at the number on the write, sees that it is older than the current one, and refuses. The old leader finds out it has been replaced by being told no. It has no other reliable way to find out.

Two leaders, with and without a fence
In both rows, leader A freezes and its lease expires (1). Node B is elected with epoch 5 and writes (2). Then A wakes and writes with epoch 4 (3). In the top row the database checks nothing, so both writes land. In the bottom row it remembers the highest epoch it has seen, 5, and refuses A's write. The check happens at the database, not in the leader.In both rows, leader A freezes and its lease expires (1). Node B is elected with epoch 5 and writes (2). Then A wakes and writes with epoch 4 (3). In the top row the database checks nothing, so both writes land. In the bottom row it remembers the highest epoch it has seen, 5, and refuses A's write. The check happens at the database, not in the leader.
The database refuses the old epoch, so the second leader does no harm. In both rows, leader A freezes and its lease expires (1). Node B is elected with epoch 5 and writes (2). Then A wakes and writes with epoch 4 (3). In the top row the database checks nothing, so both writes land. In the bottom row it remembers the highest epoch it has seen, 5, and refuses A's write. The check happens at the database, not in the leader.

The same mechanism appears in four well-known systems, under four names.

systemthe numberchecked by
Rafttermfollowers, on every AppendEntries
Kafkaleader epochfollowers, when deciding where to truncate
Chubbythe sequencer's lock generation numberthe file server the client is writing to
GFSchunk version numberchunkservers

Kafka's version is useful to study because it was a fix. Kafka publishes its design changes as numbered Kafka Improvement Proposals (KIPs). Before KIP-101, a follower decided how far to cut back, or truncate, its log by looking at the high watermark. That is the point in the log up to which every in-sync replica has the data. In some failover sequences, this left the leader and a follower holding different data. KIP-101 replaced the high watermark with the leader epoch. A follower now asks the leader where the relevant epoch starts in the log, and truncates to that point. Leadership changing twice in quick succession still caused problems, and a follow-up, KIP-279, fixed those. Confluent's distributed systems engineers needed two attempts to get epochs right, in a system whose whole job is an ordered log. Do not expect to get it right by intuition.

Chubby, Google's lock service, shows what to do when you do not control the resource. The Chubby paper describes a sequencer: an opaque token that includes the lock's generation number. The client passes it to the file server, and the file server checks it. Some servers can't be changed to check a sequencer. For those, Chubby offers a lock delay. If a holder loses its lock without releasing it, nobody else can take the lock for a while, usually about a minute. This is the fallback. If you cannot fence, you wait longer than any pause you expect to see, and a minute of unavailability is the price of not being able to check a number.

Failover time, budgeted end to end

Teams tune the election timeout. Few add up the whole failover path, and when you do, the consensus protocol turns out to be the fast part.

Back of envelopeHow long a failover actually takes
Detection, at etcd's default election timeout      1,000 ms
Election, Raft randomised 150 to 300 plus a
  round trip for votes                               250 ms
Log catch-up, new leader 500 ms behind
  500 ms x 30,000 writes/s = 15,000 entries
  applied at 12,000/s                              1,250 ms
  ──────────────────────────────────────────────────────────
  everything the consensus layer controls          2,500 ms

Client reconnection, DNS TTL of 30 s              30,000 ms
  ──────────────────────────────────────────────────────────
  total observed by users                         32,500 ms

  consensus layer                                     7.7%
  finding out where to reconnect                     92.3%

Halving the election timeout improves the total by 1.5%.
Replacing DNS failover with a client that watches the
topology and reconnects in 500 ms takes the total to
3,000 ms, an 11x improvement, with zero consensus tuning.
Where a 32.5 second failover goes
The purple part of each bar is what the consensus layer controls: 1 second to detect, 0.25 to elect and 1.25 to catch up. The blue part is clients reconnecting. With DNS failover, clients wait out a 30 second TTL, which is 92.3 percent of the total. A client that watches the topology reconnects in 0.5 seconds, and the same failover takes 3 seconds.The purple part of each bar is what the consensus layer controls: 1 second to detect, 0.25 to elect and 1.25 to catch up. The blue part is clients reconnecting. With DNS failover, clients wait out a 30 second TTL, which is 92.3 percent of the total. A client that watches the topology reconnects in 0.5 seconds, and the same failover takes 3 seconds.
The consensus layer is 7.7 percent of the failover. The purple part of each bar is what the consensus layer controls: 1 second to detect, 0.25 to elect and 1.25 to catch up. The blue part is clients reconnecting. With DNS failover, clients wait out a 30 second TTL, which is 92.3 percent of the total. A client that watches the topology reconnects in 0.5 seconds, and the same failover takes 3 seconds.

The method

The method, with an answer at each step
Each box is one step, with an example answer taken from this article: one zone, RPO zero, three replicas, a rule per read path, and an RTO of about 33 seconds. Step 6, in yellow, names the fence, and it is the step most often missing.Each box is one step, with an example answer taken from this article: one zone, RPO zero, three replicas, a rule per read path, and an RTO of about 33 seconds. Step 6, in yellow, names the fence, and it is the step most often missing.
Steps 1 to 5 set cost and speed. Step 6 decides whether two leaders can write. Each box is one step, with an example answer taken from this article: one zone, RPO zero, three replicas, a rule per read path, and an RTO of about 33 seconds. Step 6, in yellow, names the fence, and it is the step most often missing.

1. Name the failure you are buying protection from, and the ones you are not. One disk, one machine, one rack, one zone, one region, one bad deploy. Each needs a different answer, and replication is the answer to every one of them except the bad deploy.

2. Choose where the acknowledgement comes from, and say what is lost on failover. Pick a level from the ladder and state the RPO out loud. The RPO, or recovery point objective, is how much acknowledged data a failure may lose, as a number of writes or seconds. If you cannot state it, you have not chosen.

3. Pick an odd replica count, and price the quorum. Say the number, say why it is odd, and say how many failures at once it survives. If the replicas share a failure domain, say that the independence assumption does not hold.

4. Decide who may read a follower. This looks like an infrastructure decision, but it is a product decision. A read path is one kind of read the product makes, such as loading a profile page. Name which read paths can tolerate stale data and which must go to the leader. Reads in the second group get no read scaling at all.

5. Budget the failover time, end to end. Add up detection, election, log catch-up and client reconnection. Include the last one, because it is usually the largest and it is usually forgotten.

6. Name the resource that rejects a stale leader, and the number it checks. If you cannot name both, your design allows two leaders, and nothing else in the discussion changes that.

Worked examples, start to finish

There are four systems here, and the obvious approach fails differently in each. It loses data without telling anyone, it ties availability to distance, it allows two leaders, and it treats a queue as a delay.

A single region primary with read replicas

You run a Postgres primary for an OLTP workload, online transaction processing: many small reads and writes from users. It has two replicas in other zones and takes 8,000 writes a second. Read traffic is growing, so you point the read-heavy endpoints at the replicas. You leave replication asynchronous, because that is the default and write latency is good.

Two things are now true, and nobody wrote either of them down.

The first is your RPO. With asynchronous replication, the leader acknowledges a write before any replica has it. If the leader's disk dies, you lose every write that has not been shipped yet. At 8,000 writes a second and a typical shipping lag of 200ms, that is 1,600 writes gone, and each of them already got a success response.

The second is worse, because it happens all the time, not only in a disaster. A user updates their profile, and the write goes to the leader. The page load after the save goes to a replica that is 300ms behind at that moment, and the profile page shows the old value. This is the missing-own-write anomaly from the consistency models article. Here it has a specific cause: two different people chose the acknowledgement level and the read routing.

The user's own edit goes missing
The save goes to the leader, and the user gets an ok (1). Replication, the orange dashed arrow, reaches the replica 300 ms later (2). The page load goes to the replica at 100 ms, before the change has arrived, and comes back with the old name, in red (3).The save goes to the leader, and the user gets an ok (1). Replication, the orange dashed arrow, reaches the replica 300 ms later (2). The page load goes to the replica at 100 ms, before the change has arrived, and comes back with the old name, in red (3).
The page load reaches the replica before the write does. The save goes to the leader, and the user gets an ok (1). Replication, the orange dashed arrow, reaches the replica 300 ms later (2). The page load goes to the replica at 100 ms, before the change has arrived, and comes back with the old name, in red (3).
Naive

Asynchronous replication, and read from replicas wherever it helps

This is the default, and it is fast. Write latency is one local fsync, the call that forces a write onto disk. The replicas take the read load. Everything looks correct in testing, because in testing the replica is never behind. The cost is an RPO above zero that you never measured, plus a read-your-writes bug that appears only under load, so only in production. This is the starting point, because it is what most systems run.

Senior

Quorum commit, and route reads by consistency requirement

Set synchronous_commit to on, with at least one synchronous standby, so an acknowledged write survives the loss of the leader. Then split the read paths explicitly. A read of data the same user has just written goes to the leader, and every other read may use a replica. There are two usual ways to do this. You can send a user's reads to the leader for a short window after each write. Or the write can return its position in the log, and the replica waits until it has caught up to that position before it answers.

You pay on every write: one network round trip to the standby, plus the standby's fsync. In the same region that adds single-digit milliseconds to every write, which is small but not free. And your read scaling is now capped by the share of reads that can tolerate stale data. Measure that share rather than assume it.

Staff

Stop giving every transaction the same durability

Challenge the assumption that durability is a property of the cluster. In PostgreSQL it is not. You can set synchronous_commit per transaction, and the documentation says the value in effect at commit time is the one that applies.

So give each kind of transaction the setting it needs, instead of one setting for all of them. The transaction that records a payment gets remote_apply. It waits until a standby has stored and applied the write, because a lost payment, or one the user cannot see, is a far worse event than a slow one. The transaction that appends a page view gets local, or even off, and waits for no standby. One shared setting served neither of them well.

Here are the sizes. Say 2 percent of your writes touch money and 98 percent are telemetry. Quorum commit on everything then pays the synchronous cost 50 times more often than the requirement needs. Once you split them, the expensive setting usually turns out to be affordable, because it applies to almost nothing.

What you give up: one number that describes your durability, and the ability to reason about the system without reading the code. That is a real loss. To make up for it, you need a written policy that says which class each transaction belongs to. Without that document, this becomes a mess within two quarters. If you can't commit to keeping it up to date, take the senior answer.

Two regions, where the obvious safety measure is the problem

Take the same system and add a requirement: it must survive losing a whole region. The first instinct is to make replication to the second region synchronous, because that seems to be what "no data loss" means.

Back of envelopeWhat synchronous cross-region replication costs
Regions 70 ms apart round trip.

Latency, per write
  local fsync                                    ~1 ms
  + cross-region round trip                      70 ms
  → every write                                  ~71 ms
  a request doing 3 sequential writes            ~213 ms

Availability, if a remote ack is required
  P(local up) × P(remote up) × P(link up)
  0.999 × 0.999 × 0.999                        = 0.997
  → unavailable                                  0.3%
                                               1,577 min/yr
  versus local-only at 0.999                       525 min/yr

  → 3x WORSE availability, in the name of safety

Quorum of 5 placed 2 + 2 + 1 across three regions
  a write in region A needs 3 of 5
  it has 2 locally, and needs 1 more
  → nearest other region, not the farthest        25 ms
  → and it survives losing any one region entirely

The synchronous version is worse on both counts at once. Writes are slower, and availability is lower than if you did not replicate across regions at all. If every write needs an acknowledgement from one particular remote node, that node's availability multiplies into yours. The network link between the regions has become a single point of failure for writes.

The quorum version fixes both, because any majority will do. Place five nodes across three regions: two, two and one. A write in the first region then needs only one acknowledgement from outside that region, and it takes the first one to arrive, which comes from the nearest region. Latency becomes the distance to the nearest other region, not the farthest: here 25ms instead of 70ms. And if you lose any one region, a majority is still left.

For many systems, zero RPO across regions is not worth a cross-region round trip on every write, even the 25ms one. The better choice is asynchronous cross-region replication with a stated RPO of a few seconds. That is a sound design, and stating the number is what makes it sound.

Naive

Replicate synchronously to the other region

This is what "we cannot lose data" turns into when nobody does the arithmetic. It is the only option in this article that is worse on both counts than the thing it replaced. Every write gains a 70ms round trip. Write availability becomes the product of two regions and the link between them, and the worksheet above puts that at three times worse than not replicating across regions at all. The reasoning behind it is sound. Only the arithmetic is missing.

Senior

Asynchronous cross-region, with a written RPO

Ship the log to the second region asynchronously, and measure the shipping lag. Write down the resulting RPO as a number, and get someone senior to agree to it. Most businesses will happily accept a few seconds of possible loss in exchange for surviving a regional disaster, once the trade is stated rather than implied.

The cost: some acknowledged data can be lost, and you need a written procedure for what happens to it. Promoting the second region now has a known data cost, so a person should make that call, not automation.

Staff

Stop requiring a specific remote acknowledgement

Challenge the assumption that "durable in another region" means "acknowledged by that region". It does not. Any majority will do. So place five voters, the nodes that count towards the quorum, across three regions as two, two and one, and require any three of them.

Here are the sizes. A write in the first region has two local acknowledgements and needs one more, and it takes that from whichever region answers first. Latency becomes the distance to the nearest other region, 25ms here instead of 70ms. Any one region can be lost entirely, and writes keep going. You get zero RPO for a region failure, at roughly a third of the naive version's latency cost.

Five voters across three regions
The client's write reaches the leader in region A (1). The leader and its local voter make two of the three votes in about a millisecond (2). The third comes from region C after 25 ms, and the write commits (3). Region B's votes take 70 ms, and nothing waits for them. Losing any one region leaves at least three voters.The client's write reaches the leader in region A (1). The leader and its local voter make two of the three votes in about a millisecond (2). The third comes from region C after 25 ms, and the write commits (3). Region B's votes take 70 ms, and nothing waits for them. Losing any one region leaves at least three voters.
A write waits for the nearest region, not the farthest. The client's write reaches the leader in region A (1). The leader and its local voter make two of the three votes in about a millisecond (2). The third comes from region C after 25 ms, and the write commits (3). Region B's votes take 70 ms, and nothing waits for them. Losing any one region leaves at least three voters.

What you give up: three regions instead of two, so a bigger bill and a third place to operate. A cross-region write is still slower than a local one. A workload that needs commits in single-digit milliseconds cannot have zero cross-region RPO at any price. Say that out loud instead of trying to engineer around it. And region placement now affects correctness. If you put three of the five voters in one region, writes there commit without waiting for any other region. Losing that region then loses acknowledged writes, which is the problem you started with.

Electing a leader for a stateful worker

Take a job scheduler where exactly one instance may be active. If two run, every scheduled job fires twice.

The obvious approach is a lock. Each instance tries to set a key in Redis with a TTL. The holder keeps refreshing the key, and whoever holds it is the leader. It works in testing. It fails the way the toolkit described. The holder pauses, the TTL runs out, a second instance takes the lock, and then the first one wakes up. Both now believe they hold the lock, and each is right about what it saw.

Naive

A lock with a TTL, refreshed by the holder

This is cheap and obvious, and it works about 99 percent of the time. The other 1 percent is the problem. A GC pause is enough to let the TTL run out while the process still believes it is the leader. So is a hypervisor stall during live migration, a saturated network, or a container throttled by its CPU quota. Nothing in the design notices, because the old leader's next action succeeds. A longer TTL does not fix this. It only means a longer pause is needed, and pauses have no upper limit.

Senior

A lease from a consensus store, with an honest self-check

Take the lease from a coordination service that runs consensus, such as etcd or ZooKeeper, rather than from a single Redis node. That way the grant itself survives one machine dying. Next, have the leader check the clock before every action, and stop working when the lease will expire before the action can finish.

This is much better, and it is what most careful implementations do. But it still relies on the leader noticing for itself. So it relies on the leader's clock, and on the leader getting scheduled at all. A process frozen for 30 seconds runs no checks during those 30 seconds. If it freezes between a check and a write, it wakes up and sends the write without checking again, because as far as it knows the check has just passed.

Staff

Move the check to the resource, or delete the leader

There are two assumptions to challenge here, and challenging either one works.

The first assumption is that the leader can be trusted to know it is the leader. For the reasons above, it never can. So pass the lease's generation number with every write, and have the storage layer reject anything below the highest number it has seen. The old leader's write fails, and that is how it finds out it has been replaced. This is Chubby's sequencer, Raft's term and Kafka's leader epoch. If the resource cannot check a number, use Chubby's fallback, a lock delay of about a minute. It gives up availability to get safety, because nothing else is left to trade.

The second assumption is that you need a leader at all. Often the requirement is not "one active instance" but "each job runs once", and those are different. Split the jobs across instances by a hash of the job ID, so each instance owns its own slice and no two slices overlap. Then there is no election, and no single leader for the whole fleet. A slice still changes hands through a lease when its owner dies, and a paused old owner can still act, so two nodes can briefly both run one slice. Split brain is the state where two nodes both act as leader. Here it shrinks to one slice for a few seconds, and a check at the resource, such as a one-shot state change, makes it harmless. As a bonus the scheduler can now scale out across machines.

What you give up: any operation that needs all jobs to run in one global order, and the simplicity of one place to look during an incident. So this only works if you can confirm the requirement was per job, not global. Ask that question before you design the election. The cheapest leader election is the one you never build.

A replica that will not catch up

A backfill job rewrites a large table over a weekend. On Monday, a replica is 40 minutes behind. The read endpoints that use it are serving stale data, and the lag graph is not improving. The obvious response is to wait. The next obvious response is to add another replica.

Neither helps, and the lag worksheet in the toolkit shows why. The backlog drains at the apply rate minus the current write rate. If that difference is small, the backlog takes a very long time to drain, even after the backfill has stopped. A new replica is just a second replica that is also 40 minutes behind.

Time to clear a backlog
The red curve is how long a backlog of 10.8 million writes takes to clear, against the write rate once the backfill stops. At 8,000 writes a second it clears in 45 minutes. At 11,000 it takes 3 hours. At the apply rate, the teal dashed line, it never clears.The red curve is how long a backlog of 10.8 million writes takes to clear, against the write rate once the backfill stops. At 8,000 writes a second it clears in 45 minutes. At 11,000 it takes 3 hours. At the apply rate, the teal dashed line, it never clears.
Close to the apply rate, the drain time grows to hours. The red curve is how long a backlog of 10.8 million writes takes to clear, against the write rate once the backfill stops. At 8,000 writes a second it clears in 45 minutes. At 11,000 it takes 3 hours. At the apply rate, the teal dashed line, it never clears.

The only fixes are the ones that change those two rates. Throttle the backfill, so fewer writes arrive. Break its transactions into smaller ones, which usually lets the follower apply more of them in parallel. Or move the read traffic off the lagging replica and onto the leader, and accept the extra load there. Data that is 40 minutes old is often worse than a slower answer.

This holds well beyond replication: when a metric is a queue depth, the fix is always a rate, never a resource. Adding capacity in parallel does not drain a queue that has to be applied in order.

Where it goes wrong

Ordered by how often each one shows up, most common first.

1. Believing replication is backup

Replication copies a destructive write to every replica faster than you can react to it. Of the mistakes on this list, this one costs the most. Point-in-time recovery, which restores the data as it was at a chosen moment, is a separate requirement. So are snapshots kept for a set period, and a restore you have actually carried out. To find out whether a team has this right, don't ask "do you have backups?". Ask "when did you last restore one?"

2. Even replica counts

With a majority quorum, two replicas are worse than one, four are worse than three, and six are worse than five. The only even number you can defend is two nodes in a setup that does not use a majority quorum at all. If that is your setup, be ready to say what it does use, and what happens when the two nodes disagree.

3. Asynchronous replication plus a load balancer

Asynchronous replicas behind a load balancer break products in a way that is very hard to debug: now and then, under load, for some users, with no error anywhere. The write went to the leader, the read went to a follower, and the follower was 300ms behind. The person who set up the read routing did not choose the acknowledgement level. And nobody asked either of them whether users should be able to see their own edits.

Fix it with an explicit rule for each read path, not one global setting. And the session guarantees from the consistency models article, such as read-your-writes, prevent four of its five replication anomalies without any coordination between nodes.

4. An election timeout shorter than your worst pause

If a leader's GC pause is longer than the election timeout, the followers replace a leader that has not failed. The toolkit worked through the numbers: a 1.5 second pause against etcd's 1 second default. You get a failover every time you get a long GC pause, and each one brings its own log catch-up and a wave of client reconnections. It happens most under load, when pauses are longest.

Raising the timeout does help, but every real failure then takes longer to detect, in proportion. The better answer is to stop asking a process that can freeze completely, in a stop-the-world pause, to prove that it is alive. The consistent hashing article reaches the same conclusion about health checks and topology.

5. Leader election with no fence at the resource

An election with no fence means nothing at the resource checks an epoch, so an old leader that wakes up can still write. Of all the items here, this one is the most likely to be missing entirely rather than done badly. Ask a candidate who describes an election "what stops the old leader from writing?" The useful answers all name a number and the place where it is checked. "The lease expired" is not one of them, because the old leader does not know that.

6. Automatic failover with no way to decline

This is what happened in GitHub's 2018 incident. The lesson is not "automation is bad", so the details matter.

GitHub uses Orchestrator to manage its MySQL topology, and Orchestrator itself runs on Raft. The 43 seconds were a network partition: the network split the nodes into groups that could not reach each other. During it, Orchestrator did what it was designed to do. The Orchestrator nodes outside the East Coast facility formed a quorum, decided the primary was unreachable, and promoted a new primary in the West Coast facility. Meanwhile, the East Coast primary had accepted writes in those seconds that had not reached the West Coast. That left two sets of writes and no automatic way to merge them. The 24 hours went into merging them carefully.

Two primaries during a 43 second partition
While the network was split, the East Coast primary kept taking writes that never reached the West Coast (1). Orchestrator's quorum, made of nodes outside the East Coast facility, promoted a West Coast replica (2). The new primary then took writes of its own (3). The red boxes are the two sets of writes, and nothing could merge them automatically.While the network was split, the East Coast primary kept taking writes that never reached the West Coast (1). Orchestrator's quorum, made of nodes outside the East Coast facility, promoted a West Coast replica (2). The new primary then took writes of its own (3). The red boxes are the two sets of writes, and nothing could merge them automatically.
Each side accepted writes the other never saw. While the network was split, the East Coast primary kept taking writes that never reached the West Coast (1). Orchestrator's quorum, made of nodes outside the East Coast facility, promoted a West Coast replica (2). The new primary then took writes of its own (3). The red boxes are the two sets of writes, and nothing could merge them automatically.

So ask whether the automation can tell one kind of failure from another. A dead primary and an unreachable primary look the same from outside, and they need opposite responses. Automate the cases you can identify with confidence, and require a person for the unclear ones. In practice that comes down to one rule: if the evidence also fits a network partition, do not automatically promote a node in a different failure domain.

7. Reading lag as a latency metric

If your dashboard shows replication lag as a line next to request latency, people will read it the same way. They will be wrong in one direction: they expect lag to recover as soon as load drops. It doesn't. It recovers at the difference between two rates, the apply rate and the write rate, and that difference can be as small as you like. Alert on how fast lag is changing as well as on its value. A lag of 5 seconds that is growing is a different situation from a lag of 5 minutes that is shrinking.

8. Multi leader without a conflict policy chosen in advance

Multi leader replication does not remove coordination. It puts it off, calls it conflict resolution, and hands it to you at read time. Last-write-wins, which keeps the write with the latest timestamp, is one policy. It throws data away by design, without an error, and it depends on clocks you do not control.

If you can't answer "what happens when the same row is updated in two regions in the same second?" before you build it, you have not chosen multi leader. There are three real answers. The first is a CRDT, a conflict-free replicated data type, whose copies can always be merged; it works for data that fits one. The second is a merge written in the application. The third is to partition writes by key, so each key has exactly one home region. That last one is single leader per key, and it is usually what people wanted in the first place.

If you memorise nothing else

factwhy it matters
A single machine fails by stopping, a replicated one by disagreeingyour monitoring was built for the first kind
Replication is not backupit propagates a bad write at network speed
Two replicas are worse than one for write availabilitya majority of two is two
Every even replica count is worse than the odd one below it3, 5, 7. There is no argument for 4 or 6
Waiting for all N replicas is the maximum of N samples4.9% of writes hit a slow replica at N=5
Waiting for a majority is roughly the median0.001% at the same N, a 5,000x difference
Replication lag is a queue depth, not a latency10 minutes of overload can cost 45 to recover
Adding replicas does not reduce lagthey all replay the same stream at the same rate
You cannot detect failure, only silencea GC pause and a crash produce identical evidence
Any election timeout is a bet, and no value is safe1s kills leaders that pause; 3s hides real failures
A lock without a fence is a suggestionthe leader is the component you cannot trust
The epoch must be checked at the resourceRaft term, Kafka leader epoch, Chubby sequencer, GFS chunk version
Kafka needed KIP-101 and then KIP-279 to get epochs rightdo not expect to get this correct by intuition
Client reconnection is usually most of your failover timeconsensus is the fast part; DNS is not
Requiring a specific remote ack multiplies availabilitiessync cross-region can be 3x less available than not doing it
A majority does not care which majorityquorum turns the farthest region into the nearest one
Durability can be per transaction, not per clusterPostgres allows it, almost nobody uses it

What is expected at each level

Mid-level

Explain single leader replication: writes go to one node, followers replay its log, and reads can go to either. Know the difference between synchronous and asynchronous replication, and be able to say what asynchronous loses on failover. Know that replication is not partitioning, and that it is not backup.

You are not expected to raise quorum arithmetic, fencing tokens or the queueing behaviour of lag on your own. You are expected to answer well when asked. Suppose you are asked what happens if the leader dies right now. This is a good mid-level answer: "any write that was acknowledged but not yet shipped is lost, so I would want to know how much that is."

The mistake to avoid is saying "we replicate for redundancy" without naming the failure that protects against, and without noticing that a bad DELETE is not one of them.

Senior

You drive this, and three things must come up without prompting.

An RPO and an RTO, as numbers. Not "synchronous replication" but "acknowledged writes survive one zone loss, so RPO is zero for that failure, and RTO is about 33 seconds." The most common senior miss here is naming the acknowledgement level without naming what it loses. It sounds complete, and it is not.

An odd replica count, with the quorum stated. Say the number, say what it tolerates, and say whether the replicas fail independently. Proposing four replicas lands badly. So does proposing a number without saying what it survives.

Read routing as a decision, not a default. State which read paths may use a follower and which may not, and why. If your design has asynchronous replicas behind a load balancer with no rule about them, you have shipped a read-your-writes bug, and the interviewer will find it.

Two things are disqualifying: automatic failover with nothing that stops the old leader from writing, and treating replication as a backup strategy.

Staff+

The question moves from how to design the replication to how much of it the system should do at all.

Name the failure class, then match the mechanism to it. Disk, machine, rack, zone, region and bad deploy each need a different answer, and replication is not the answer to a bad deploy. Saying which failures you are deliberately not covering counts for more than covering all of them badly.

Do not give every transaction the same durability. Different transactions need different guarantees, and Postgres, for one, lets you set them per transaction. One setting for everything means you either overpay on the common path or get the important one wrong. Say which transactions are in which class.

Budget failover end to end, and attack the largest part. The parts are detection, election, catch-up and client reconnection. The largest is almost always the last one. So the most useful work is in the client library and in service discovery, the system that tells clients where the primary is, not in the consensus settings. Teams often tune election timeouts while they lose 30 seconds to a DNS TTL.

Put the correctness check in the resource, not in the coordinator. That means fencing tokens, epochs or generation numbers. Say where the number is checked, and what happens to a write that arrives with an old one. That is the clearest sign that you have run one of these systems.

Decide what failover should be manual. Automation that cannot tell a dead primary from an unreachable one will, sooner or later, promote a new primary on the far side of a network partition. Automate the cases you are sure of, require a person for the unclear ones, and be able to say which is which.

And be able to say what you would not build. Each of these can cost a team a quarter.

The first is a custom leader election protocol, when etcd or ZooKeeper already does the hard part and the real gap was a fencing check at the storage layer. The second is multi-region synchronous replication, which can be slower and less available than the asynchronous version it replaced. The third is an active-active multi-leader deployment with no conflict policy, which means you find the conflicts in production.

The fourth is failover automation with no manual override, which sets you up for your own version of the GitHub incident. The fifth is an extra replica to fix replication lag, which cannot work, because lag is a rate problem. The sixth is a whole replication tier for derived data that could have been rebuilt from source in 10 minutes, with a procedure you can test on a Tuesday.

Sources

Every figure attributed to a company, project or paper below comes from that published source. The quorum, tail and lag figures are arithmetic, with the inputs stated in each worksheet.

  • October 21 post-incident analysis, GitHub. The 43 second partition, Orchestrator's Raft-based topology management, the quorum forming outside the affected facility, the writes accepted and not replicated, and the 24 hours of degraded service that followed.
  • Asynchronous Commit and Write Ahead Log configuration, PostgreSQL documentation. The five synchronous_commit levels, what each guarantees, and that the setting is evaluated per transaction at commit time.
  • Semisynchronous Replication, MySQL 8.0 manual. The AFTER_SYNC and AFTER_COMMIT wait points, and that under AFTER_COMMIT other clients can observe a transaction that a subsequent failover may erase.
  • Replication Threads, MySQL manual. The applier thread model, and that replica_parallel_workers defaults to 4 from 8.0.27 onward, making replicas multi-threaded by default.
  • KIP-101, Alter Replication Protocol to use Leader Epoch rather than High Watermark for Truncation and KIP-279, Apache Kafka. Why high watermark based truncation permitted log divergence, the leader epoch that replaced it, and the follow-up needed for fast failover edge cases.
  • The Chubby Lock Service for Loosely-Coupled Distributed Systems, Burrows, OSDI 2006. Sequencers carrying a lock generation number validated by the resource, and the roughly one minute lock delay offered for servers that cannot check one.
  • Tuning and FAQ, etcd. The 100ms default heartbeat interval and 1000ms default election timeout. The guidance that election timeout be at least 10 times the round trip time. And the warning emitted when a leader misses two heartbeat intervals.
  • Raft, from Ongaro and Ousterhout's work at Stanford. The randomised election timeout, with 150ms to 300ms as the paper's example range, and the term number carried on every replication call.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.