Consensus and Coordination Algorithms Questions
How independent nodes agree on shared state: Paxos and Raft, leader election, quorum reads and writes, distributed locks, coordination services such as ZooKeeper or etcd, and Byzantine fault tolerance for replicas that cannot be trusted. Covers split-brain avoidance, fencing tokens, and the cost of coordination on throughput and latency. Frames when consensus is required versus when it can be designed away.
Given N=5 replicas, quorum read size R=3 and write size W=3, estimate qualitatively how availability changes if each node independently has probability p of being unreachable. Explain how increasing W affects write availability and read latency. You don’t need to compute exact formulas but explain the reasoning and give numeric intuition for p=0.05 and p=0.2.
Sample Answer
Direct answer
With N = 5, R = 3, W = 3, an operation succeeds whenever at least 3 of the 5 replicas answer, so it fails only when 3 or more are unreachable at once. With independent failures that is rare at p = 0.05 (about 1 in 860 operations fail, far better than a single node's 1 in 20) but real at p = 0.2 (about 1 in 17). Raising W makes writes need more replicas, so write availability drops and write latency rises; its benefit is that you can then lower R while keeping R + W > N, which makes reads both faster (you wait for fewer, faster replies) and more available.
Terms
- Quorum: the number of replicas that must respond for an operation to succeed.
Wis the write quorum andRthe read quorum. R + W > N: every read quorum overlaps every write quorum in at least one replica, so a read always sees the latest acknowledged write. With 5 replicas,R = 3, W = 3overlap in at least 1.- Availability here: the probability that enough replicas are reachable for the operation to succeed.
The reasoning
Each replica is independently unreachable with probability p. An operation needing k replicas fails only if more than N - k are down. Intuition before numbers: with k = 3 of 5 you can lose 2 replicas and still succeed, and losing 3 independent replicas at once needs three unlikely events together, so failure probability scales roughly like p³ when p is small.
The exact tail sum (not required, but it gives the numbers):
P(success)=i=k∑N(iN)(1−p)ipN−iLeading term for k = 3, N = 5: failure is about
(the 10 counts the number of ways to choose which 3 of the 5 replicas are the ones that are down; each such choice contributes roughly p^3 of failure probability, and the terms are summed)
which gives 10 x 0.05³ = 0.00125 at p = 0.05 (the exact value is 0.00116) and 10 x 0.2³ = 0.08 at p = 0.2 (exact 0.058; the rough estimate is worse at large p because the smaller terms are no longer negligible).
Numbers, computed
W increases while R = N - W + 1 keeps the overlap. Latency uses an assumed per-replica reply time of 1 ms plus an exponential tail with a 2 ms mean (most replies arrive close to that 1 ms baseline, but a thinning tail of replies, for example ones hitting a GC pause or a retry, take much longer; 2 ms is the average size of that extra delay), sampled with a fixed seed (pinning the random number generator's starting point so the same run of random numbers, and so the same printed results, come out every time this code is run).
from math import comb
import random
def p_quorum(n, k, p_down):
"""Probability that at least k of n nodes are reachable, each node
independently unreachable with probability p_down."""
up = 1 - p_down
return sum(comb(n, i) * up**i * p_down**(n - i) for i in range(k, n + 1))
N = 5
for p in (0.05, 0.2):
print(f"p = {p}")
for w in (3, 4, 5):
r = N - w + 1 # smallest R that still overlaps every write quorum
a_w, a_r = p_quorum(N, w, p), p_quorum(N, r, p)
print(f" W={w} R={r}: write avail={a_w:.5f} (fail {1-a_w:.5f}) "
f"read avail={a_r:.6f} (fail {1-a_r:.2e})")
print(f" single node: avail={1-p:.2f}")
# Read latency: a read of size R waits for the R-th fastest of the 5 replies.
random.seed(7)
TRIALS = 100_000
lat = [[random.expovariate(1 / 2.0) + 1.0 for _ in range(N)] for _ in range(TRIALS)]
for r in (5, 4, 3, 2, 1):
kth = sorted(sorted(x)[r - 1] for x in lat)
print(f"wait for {r} of 5: median={kth[TRIALS//2]:.2f} ms p99={kth[int(TRIALS*0.99)]:.2f} ms")
Output:
p = 0.05
W=3 R=3: write avail=0.99884 (fail 0.00116) read avail=0.998842 (fail 1.16e-03)
W=4 R=2: write avail=0.97741 (fail 0.02259) read avail=0.999970 (fail 3.00e-05)
W=5 R=1: write avail=0.77378 (fail 0.22622) read avail=1.000000 (fail 3.13e-07)
single node: avail=0.95
p = 0.2
W=3 R=3: write avail=0.94208 (fail 0.05792) read avail=0.942080 (fail 5.79e-02)
W=4 R=2: write avail=0.73728 (fail 0.26272) read avail=0.993280 (fail 6.72e-03)
W=5 R=1: write avail=0.32768 (fail 0.67232) read avail=0.999680 (fail 3.20e-04)
single node: avail=0.80
wait for 5 of 5: median=5.09 ms p99=13.41 ms
wait for 4 of 5: median=3.31 ms p99=7.82 ms
wait for 3 of 5: median=2.38 ms p99=5.48 ms
wait for 2 of 5: median=1.75 ms p99=4.01 ms
wait for 1 of 5: median=1.28 ms p99=2.85 ms
Numeric intuition
| p = 0.05 | p = 0.2 | |
|---|---|---|
| R = W = 3 (either operation) | fails about 1 in 860 | fails about 1 in 17 |
| W = 4 writes | fail about 1 in 44 (20x worse than W = 3) | fail about 1 in 4 |
| W = 5 writes | fail about 1 in 4.4 | fail about 2 in 3 |
| R = 2 reads (paired with W = 4) | fail about 1 in 33,000 | fail about 1 in 150 |
Reading it:
- At
p = 0.05,R = W = 3is a clear win over one node: failure drops from 5% to about 0.1%. - At
p = 0.2, even majority quorums fail about 6% of the time. Replication cannot rescue nodes that are down a fifth of the time; fix the nodes or add replicas. - Increasing
Whurts writes fast:W = 5means any single down replica blocks every write, so write availability falls below that of a single node (0.774 against 0.95 atp = 0.05). - Read latency: a read waits for the
R-th fastest reply, so latency falls asRfalls: in the model the median goes from 2.38 ms atR = 3to 1.75 ms atR = 2and the p99 (99th percentile) from 5.48 ms to 4.01 ms. RaisingWfrom 3 to 4 by itself (keepingR = 3) does not change read latency; the read gain comes only from the lowerRit permits. Writes pay the mirror image: waiting for the 4th fastest of 5 moves the median from 2.38 ms to 3.31 ms.
Choosing
- Balanced, general purpose:
R = W = 3. Best combined availability for 5 replicas. - Read-heavy, writes can tolerate occasional failure or retry:
W = 4, R = 2. Reads get faster and far more available; writes get noticeably less available. - Avoid
W = 5unless writes are rare and can queue: a single slow or down node blocks all of them.
Caveats a senior answer adds
- Independence is the biggest assumption. Replicas in the same rack, zone or deployment fail together; the real failure rate of a quorum is dominated by correlated events. Spread replicas across failure domains.
- Unreachable is not the same as slow. A replica in a garbage-collection pause counts as down for latency purposes even though it is up; the p99 figures are where that shows.
- Overlap alone is not full consistency.
R + W > Nmakes a read see the latest acknowledged write only with correct versioning (tagging each value with a counter or timestamp so the newest can be identified), read repair (a read that notices a replica is holding a stale value and pushes the newest value to it) and handling of concurrent writes (deciding an order, or a merge rule, when two writes to the same key overlap in time); sloppy quorums (writing to substitute nodes during failures) break the overlap guarantee.
Design a multi-region consensus strategy for propagating a configuration change (for example, a pricing or routing rule) so that the change takes effect in every region within 2 seconds, without producing split-brain during a network partition. Compare a strongly-consistent approach such as Paxos or Raft against a faster approach that pins a leader and uses short-lived leases, and say which you would recommend and why.
Sample Answer
Direct answer
I would commit every configuration change through a Raft (or Paxos) group with one voting member per region (as opposed to a non-voting member, which receives the same replicated log but does not count toward the majority needed to commit, useful for a read-only replica or a region still catching up), then push the committed value to each region through watches (a subscribe-style API: a caller registers interest in a key and the store pushes a notification the instant it changes, instead of the caller polling) into an in-memory cache. In the healthy case that lands everywhere in roughly a quarter of a second, so the 2-second target does not force you to give up consensus. The "pin a leader and use short leases" design is faster by about one cross-region round trip, but it is only free of split brain if a quorum grants the lease, the new leader waits out the old lease plus a clock-drift margin, and every region rejects updates from an older leader. Once you add those, you have rebuilt consensus with a lease optimisation, and you saved roughly 70 ms on a 2000 ms budget. One thing no design can promise: a region cut off by a partition cannot receive a change, so the real guarantee is that it keeps serving the last committed version, knows it is stale, and never accepts a competing one.
Terms used below
- Consensus: a protocol that makes a group of machines agree on one ordered sequence of values even when some crash or messages are lost. Raft and Paxos are the two standard ones; Raft elects a leader that orders all writes, while Paxos reaches the same kind of agreement through rounds of majority voting without requiring a single leader role in its basic form (production variants typically add one anyway, for efficiency).
- Quorum: a majority of the voting members (2 of 3, 3 of 5). Any two majorities overlap in at least one member, which is why two conflicting values cannot both be committed.
- Term / epoch: a number that increases every time leadership changes. Messages carrying an older term are ignored.
- Lease: permission to act as leader until a stated time, which must be renewed before it runs out.
- Split brain: two nodes each believing they are the leader and issuing different values.
- Linearizable: every reader sees writes in one order, and never sees an older value after a newer one has been acknowledged.
Requirements I am designing to
| Requirement | Interpretation |
|---|---|
| Takes effect everywhere within 2 s | from the admin's successful write to every region's services using it, in normal operation |
| No split brain | one totally ordered sequence of config versions; no region ever acts on a version that was not committed, or on two different "latest" versions |
| During a partition | regions keep serving; the side that holds a majority can still accept changes; the cut-off side serves its last committed version and raises an alarm |
| Change rate | human- or pipeline-driven, a few changes per minute, not thousands per second |
The low write rate matters: it is why paying one cross-region round trip per change is cheap, and why a single consensus group is enough.
Design
flowchart LR
A[Admin API] -->|propose v| L[Voter us-east<br/>Raft leader]
L <-->|replicate| W[Voter us-west]
L <-->|replicate| E[Voter eu-west]
L -->|watch| AE[Config agents us-east]
W -->|watch| AW[Config agents us-west]
E -->|watch| AU[Config agents eu-west]
AE --> SE[Service caches]
AW --> SW[Service caches]
AU --> SU[Service caches]
- Write path. The admin API sends the change to the Raft leader (with etcd or Consul, replicated key-value stores that run Raft internally, that is just a transactional put). It commits once a majority, the leader plus the nearest other region, has written it to disk. The commit index (the position in the replicated log at which this change was durably agreed) becomes the config's version number.
- Fan-out (one update triggering delivery to many recipients). Config agents in each region watch their local voter, so propagation traffic crosses the ocean once per region, not once per server. An agent applies a version only if it is higher than the one it already holds, so a delayed or duplicated notification can never move a region backwards.
- Serving. Services read from an in-memory snapshot the agent updates. The request path never touches consensus, so a slow or partitioned coordination cluster cannot add latency to user requests.
- Mixed-version window. Regions switch within a few hundred milliseconds of each other, not at the same instant. Design the change so that a short mix is safe: for pricing, stamp each quote with the version it used and honour it at checkout; for routing, make the new rule accept traffic shaped by the old one. If a change truly must flip everywhere at once, ship it in two steps (stage version v, then flip a flag once every region reports v loaded).
- Staleness detection. A follower knows when it last heard from the leader. If a region has not heard for more than 2 s, its agents mark config as stale and alert, then apply a per-setting policy decided in advance: pricing and routing keep the last known good value (fail static), while an emergency kill switch may fail closed (default to the safe, disabled state rather than keep whatever setting it last had, since an unknowingly-stale "on" is worse than "off" for a kill switch).
Why this has no split brain during a partition
| Partition | What happens |
|---|---|
| eu-west cut off | us-east and us-west still form a majority and keep committing. eu-west keeps serving its last committed version and alerts after 2 s. It cannot invent a version, because it cannot commit alone. |
| Leader region (us-east) cut off | us-west and eu-west elect a new leader in a higher term. The old leader can no longer commit anything (no majority), so the admin's write either fails or is retried against the new leader. The two sides never hold two different committed values. |
| All regions isolated from each other | no majority anywhere: no changes are accepted, every region serves its last committed version. That is the correct outcome. |
The requirement "applied in every region within 2 s" cannot hold for a region that no message can reach. Saying so explicitly, and defining what that region does instead, is the honest answer. The CAP theorem (under a network partition, a system must choose between consistency and availability) says the same thing formally.
The leader-pinned lease alternative
How it works. One region is designated leader and pushes each change straight to every region, with no quorum wait. It holds a short lease, say 1.5 s, and if it dies another region takes over when the lease expires.
Where it is faster. It skips the wait for the nearest voter's acknowledgement: about one round trip, roughly 70 ms in the numbers below.
Where it breaks. The danger is in the takeover. If a region decides on its own that the leader is dead (its lease timer expired locally), a leader that is merely slow or partitioned from that region, but still reachable by others, keeps pushing. Two leaders now push different versions to different regions: split brain. To make it safe you need all of the following:
- A quorum grants the lease, so a region cannot promote itself. That quorum is a consensus group.
- The new leader waits the old lease length plus a margin for the old holder's clock running slow, before acting.
- The old leader stops pushing before its lease ends, as measured on its own clock minus the same margin.
- Every region rejects a push carrying an older epoch than one it has already seen. This is the fencing step, and it is what makes a leader that paused and woke up late harmless.
With those four pieces, this is Raft-style consensus with a leader lease (the lease lets the leader serve reads without a quorum round), not an alternative to it.
Worked example: the numbers
Assumed inter-region round-trip times (RTT) are round planning figures, not measurements: us-east to us-west 65 ms, us-east to eu-west 75 ms, us-west to eu-west 140 ms. Other inputs: 5 ms disk flush, 100 ms Raft heartbeat interval, 50 ms from watch notification to services using the new value.
# Planning assumptions (round figures, not measurements)
RTT = {frozenset({"east", "west"}): 65, frozenset({"east", "eu"}): 75, frozenset({"west", "eu"}): 140}
def rtt(a, b):
return 0 if a == b else RTT[frozenset({a, b})]
REGIONS, LEADER = ["east", "west", "eu"], "east"
FSYNC, HEARTBEAT, APPLY = 5, 100, 50 # disk flush, Raft heartbeat interval, watch->agent->reload (ms)
BUDGET = 2000
commit = min(rtt(LEADER, r) for r in REGIONS if r != LEADER) + FSYNC
print(f"commit (leader + nearest voter): {commit} ms")
for r in REGIONS:
# a follower receives the entry one-way, but only learns it is committed from the
# leader's NEXT AppendEntries (Raft's replicate-and-heartbeat message, which also
# carries the leader's commit index): worst case one heartbeat interval later
known = commit if r == LEADER else commit + HEARTBEAT + rtt(LEADER, r) / 2
total = known + APPLY
print(f"{r:>5}: applied by {total:6.1f} ms (headroom {BUDGET - total:6.1f} ms)")
# Lease hand-off safety: the new leader must wait out the old lease on ITS clock,
# padded for the worst rate at which the old holder's clock can run slow.
LEASE_MS, MAX_DRIFT = 1500, 0.01 # 1.5 s lease, clocks may disagree in rate by 1%
wait = LEASE_MS * (1 + MAX_DRIFT)
print(f"lease hand-off wait: {wait:.0f} ms, leaving {BUDGET - wait - APPLY:.0f} ms of the budget after a failover")
Output (executed):
commit (leader + nearest voter): 70 ms
east: applied by 120.0 ms (headroom 1880.0 ms)
west: applied by 252.5 ms (headroom 1747.5 ms)
eu: applied by 257.5 ms (headroom 1742.5 ms)
lease hand-off wait: 1515 ms, leaving 435 ms of the budget after a failover
What the numbers say:
- Healthy path: the slowest region applies the change at about 258 ms, leaving more than 1.7 s of headroom for a retransmitted message or a slow agent. The heartbeat term is the conservative bound; many implementations send the new commit index as soon as it advances.
- What the lease design would save: the 70 ms commit wait, which is 3.5% of the budget.
- What a failover costs either way: with a 1.5 s lease, a change issued just as the leader dies waits 1515 ms for the hand-off before it can even start propagating, leaving 435 ms. A consensus leader election has the same shape (election timeout plus one voting round). So "within 2 s" can hold through a failover only if the election or lease timeout is kept well under 2 s, and shortening it trades against false failovers on a jittery WAN (wide-area network). I would state the SLO (service-level objective) as "2 s in normal operation, plus at most one failover time during leader loss".
Recommendation and what would change it
Recommend: consensus (Raft, via etcd, Consul or an equivalent managed store) for the write, local watches for fan-out, in-memory caches for serving, monotonic versions everywhere, and a pre-decided stale-config policy per setting. It meets the budget with more than 1.7 s to spare, split brain is ruled out by quorum overlap rather than by clock assumptions, and it is the design operators already know how to run.
What would flip the choice:
- A budget below one cross-region round trip (say 50 ms): no synchronous cross-region scheme fits. You would give each region authority over its own settings, or accept eventual consistency with last-writer-wins, and give up "no split brain" for global settings.
- Very high write rates (thousands of changes per second): a single Raft group becomes the bottleneck; shard the configuration by key range into several groups.
- Only two regions: no majority survives the loss of either one. Add a third site as a voting witness that stores the log but serves no traffic.
Trade-offs and pitfalls
- Consensus on the request path. Reading config from etcd on every request adds a cross-region hop and makes the coordination cluster a hard dependency. Cache locally and read from memory.
- Believing a lease alone prevents split brain. A lease is a clock-based promise. Without a quorum granting it and fencing at the receivers, a paused leader acts after its lease ended.
- Even voter counts. Four voters (voting members: the ones whose acknowledgement counts toward a majority) tolerate one failure, the same as three, while making every commit wait for one more acknowledgement.
- Timestamp-based "activate at 12:00:00.000" everywhere. It moves correctness onto clock synchronisation. Use it only with a known clock-error bound and a version check.
- Letting a region go backwards. Without "apply only if version is higher", a delayed notification can revert a region to an older price. Version monotonicity is as important as the consensus itself.
Given high availability requirements during possible network partitions, explain how you would choose quorum sizes and read/write routing to meet specific RTO/RPO targets while balancing consistency (CAP trade‑offs). Provide example quorum configurations and practical implications for latency, throughput and data correctness.
Sample Answer
Direct answer
Start from the targets. RPO (recovery point objective: how much acknowledged data you may lose) of zero means a write must be acknowledged by enough replicas, in enough independent failure domains, that any failure you plan for leaves a copy. RTO (recovery time objective: how long you may be unavailable) sets how quickly the survivors must take over, which bounds failure detection plus leader election. Then pick N replicas, a write quorum W and a read quorum R so that W + R > N (every read quorum overlaps every write quorum, so reads see the latest acknowledged write) and 2W > N (two conflicting writes cannot both succeed). For most systems that need RPO 0 across a zone or region loss, the answer is N = 5 with W = R = 3, placed 2/2/1 across three failure domains (independent units, such as availability zones or regions, that can fail together as one: shared power, network, or an entire data centre), reads routed to the leader or through a quorum.
The rules behind quorum choice
A quorum is the number of replicas that must respond for an operation to succeed.
W+R>N⇒every read quorum shares a replica with every write quorum 2W>N⇒two concurrent writes cannot both reach a quorumWrites stay available while at most N - W replicas are down; reads while at most N - R are down. RPO 0 for losing a whole failure domain additionally requires that the W acknowledgements always include at least one replica outside any single domain. With 2/2/1 placement and W=3 this holds automatically: the largest domain holds only 2 of the 5 replicas, so any 3 acknowledgements can never come entirely from one domain, meaning at least one of the 3 is always in a different domain from the other two. That is exactly why 2/2/1 with W=3 is the placement recommended below; a placement like 3/1/1 would let the domain holding 3 replicas satisfy W=3 on its own, which does not guarantee RPO 0 for that domain's loss (the table below confirms this: placement (3, 1, 1) does not keep a majority after losing one zone).
CAP (the result that during a network partition a system must choose between consistency, every read seeing the latest write, and availability, every request getting a non-error response): quorums are how you make that choice explicit. A side of the partition that cannot assemble W replicas must refuse writes if you want consistency, or accept them on the replicas it can reach if you want availability.
Example configurations
This short program enumerates common configurations and checks which zone placements survive losing one zone:
def describe(n, w, r):
return {
"N": n, "W": w, "R": r,
"read_sees_latest_write": w + r > n,
"no_conflicting_writes": 2 * w > n,
"writes_survive_down": n - w,
"reads_survive_down": n - r,
}
print(f"{'N':>2} {'W':>2} {'R':>2} W+R>N 2W>N writes-ok-with-down reads-ok-with-down")
for n, w, r in [(3, 2, 2), (3, 3, 1), (3, 1, 3), (3, 1, 1), (5, 3, 3), (5, 4, 2), (5, 2, 4)]:
d = describe(n, w, r)
print(f"{n:>2} {w:>2} {r:>2} {str(d['read_sees_latest_write']):>5} {str(d['no_conflicting_writes']):>5}"
f" {d['writes_survive_down']:>19} {d['reads_survive_down']:>18}")
# Which placements of 5 replicas over 3 zones keep a majority (3) after losing ANY one zone?
print()
for placement in [(2, 2, 1), (3, 1, 1), (3, 2, 0)]:
worst = min(5 - z for z in placement)
print(f"placement {placement}: worst-case survivors after one zone loss = {worst} -> majority kept: {worst >= 3}")
Output:
N W R W+R>N 2W>N writes-ok-with-down reads-ok-with-down
3 2 2 True True 1 1
3 3 1 True True 0 2
3 1 3 True False 2 0
3 1 1 False False 2 2
5 3 3 True True 2 2
5 4 2 True True 1 3
5 2 4 True False 3 1
placement (2, 2, 1): worst-case survivors after one zone loss = 3 -> majority kept: True
placement (3, 1, 1): worst-case survivors after one zone loss = 2 -> majority kept: False
placement (3, 2, 0): worst-case survivors after one zone loss = 2 -> majority kept: False
Reading the table against targets:
| Config | RPO | Write availability | Read availability | Best for |
|---|---|---|---|---|
| N=3, W=2, R=2, one replica per zone | 0 for one zone loss | Survives 1 down | Survives 1 down | Default for a single region with 3 zones |
| N=3, W=3, R=1 | 0 | Any single failure stops writes | Survives 2 down | Read-heavy data where brief write outages are acceptable |
| N=3, W=1, R=1 | Not zero: an acknowledged write on one node dies with it | Survives 2 down | Survives 2 down, stale | Caches, metrics, anything re-derivable |
| N=5, W=3, R=3, placed 2/2/1 | 0 for one zone or region loss | Survives 2 down | Survives 2 down | Cross-region systems of record |
| N=5, W=4, R=2 | 0 | Survives only 1 down | Survives 3 down | Read-heavy, rarely written configuration |
Configurations with 2W not greater than N (W=1 of 3, W=2 of 5) allow two concurrent writes to succeed on disjoint replicas, so they need conflict resolution (versions, merge rules) and are not a basis for "no lost updates".
Meeting an RTO
For a leader-based system (Raft or Paxos underneath), the outage after a leader dies is roughly detection + election + client retry. With etcd's documented defaults (100 ms heartbeat, a periodic "I'm still leader" message so followers don't start an election; 1000 ms election timeout, how long a follower waits without hearing from the leader before starting an election of its own), that is on the order of one to two seconds, plus however long clients take to retry against the new leader. If the RTO is 30 seconds, these defaults have large margin; if it is sub-second, you need lower timeouts, which requires a fast, stable network (etcd's guidance: election timeout at least 10 times the round-trip time) or else you trade outage length for spurious elections.
For a leaderless system (Dynamo-style quorums, after Amazon's Dynamo design, where any replica accepts writes and the client or a coordinator waits for W of them), there is no election: as long as W replicas are reachable, writes continue, so RTO for a single replica failure is effectively the client's timeout and retry.
Read and write routing
- Writes always go to the leader (leader-based) or to a coordinator (in a leaderless design, whichever node the client's request happens to land on, acting as a temporary go-between for that one request) that waits for W acknowledgements (leaderless).
- Linearizable reads (a read that reflects every write already acknowledged to a client, with no stale or out-of-order result): route to the leader, which confirms it is still leader with a quorum round or a lease (a time-limited grant from the other replicas that lets the leader answer without re-checking every time, until it expires) before answering, or read from R replicas and take the newest version.
- Local, possibly stale reads from the nearest replica for data where staleness is acceptable. This lowers latency and spreads load but gives up the W + R > N guarantee for those reads.
- Across regions, per-region quorums (such as Cassandra's LOCAL_QUORUM, a quorum computed only among the replicas in the caller's own region rather than across the whole cluster) keep latency local but mean a write acknowledged in one region may not exist in another yet: RPO for a region loss is no longer zero.
Practical implications
Latency. A write returns when the W-th fastest replica acknowledges. With replicas 2/2/1 across regions A, B, C and assumed round trips of 1 ms within A and 65 ms from A to B, a W=3 write from a coordinator in A waits for A's second replica (1 ms) and the first B replica (65 ms): about 65 ms. Raising W to 4 means waiting for the second-fastest remote replica, and the tail latency (the 99th percentile, p99) of that replica now drives yours.
Throughput. Every write is sent to all N replicas regardless of W; W only changes how many you wait for. Larger N multiplies network and disk work per write. A higher R multiplies read work.
Correctness. W + R > N alone does not make a leaderless store linearizable: concurrent writes, clock-based last-writer-wins (when two writes conflict, whichever carries the later timestamp wins and the other is discarded, which breaks down if clocks disagree between nodes), sloppy quorums (accepting writes on stand-in replicas during a partition, then handing them back later) and failed writes that partially landed can all produce anomalies. If you need linearizability, use a consensus protocol, or add versioning and read repair (when a read notices some replicas answered with an older version, write the newest version back to those stale replicas so they heal) and test it.
Trade-offs and pitfalls
- Even N (4 or 6) buys no extra fault tolerance for majority quorums and costs latency.
- Two failure domains cannot give RPO 0 and availability through the loss of either one: whichever domain holds the majority takes the system down when it fails.
- Counting replicas instead of failure domains: 5 replicas with 3 in one zone look robust and are not.
- Tuning quorums without writing the target first: say "RPO 0 for a zone loss, RTO under 60 seconds" and derive the numbers from it.
Why does a distributed database need leader election? Describe common algorithms and systems used for it (Raft, Paxos, ZooKeeper, etcd), how leader election affects availability, and what an architect must consider during network partitions and leader churn.
Sample Answer
Direct answer
A replicated database keeps several copies of each piece of data, and those copies must agree on the order of writes. The simplest way to get one order is to let exactly one node, the leader, accept writes and tell the others (the followers) what to apply. Leader election is the protocol that picks that node and replaces it when it fails, and it must never let two nodes both believe they are leader at the same time. Raft and Paxos are the algorithms; etcd and ZooKeeper are systems that package them. The price is a short write outage every time the leader dies or gets cut off, plus the rule that only the side of a partition holding a majority may keep working.
Why a leader at all
Without a single writer, two replicas can accept conflicting writes to the same row at the same moment ("set balance to 80" on one node, "set balance to 50" on another), and the cluster ends up with copies that disagree. Resolving that afterwards is either impossible (money) or needs merge rules the application must supply. A leader serialises writes: it assigns each write a position in a log (entry 41, 42, 43...), and every follower applies the same log in the same order, so every copy ends in the same state. This pattern is called state machine replication.
Two terms appear in every leader-election protocol:
- Quorum (majority): more than half the voting members, for example 3 of 5. Any two majorities of the same group share at least one member, and that shared member is what stops two leaders from being elected for the same period.
- Term (Raft) / epoch (ZooKeeper) / ballot (Paxos): a number that increases with every election. Messages carry it, and a node that sees a higher number steps down. It is how the cluster tells the current leader from an old one.
The common algorithms and systems
| Name | What it is | How it elects a leader |
|---|---|---|
| Raft | A consensus algorithm (consensus: getting a group of nodes to agree on one value, or one sequence of values, even if some fail) designed to be easy to understand | A follower that hears no heartbeat (a small periodic message a leader sends just to prove it is still alive, carrying no new log entries of its own) for a randomised election timeout increments the term, votes for itself and asks the others for votes. It wins with a majority. Voters refuse a candidate whose log is less up to date than their own, so a new leader always holds every committed write. |
| Paxos (Multi-Paxos) | The older, more general consensus algorithm | A node runs a "prepare" round with a higher ballot number; once a majority promises to ignore lower ballots it acts as the stable leader and skips that round for later writes. Leader election is not specified as a separate piece, which is why real implementations differ a lot. |
| ZooKeeper | A coordination service (a small, strongly consistent key-value store for configuration, locks and membership) | Internally it uses Zab (ZooKeeper Atomic Broadcast), a Paxos-like protocol with its own leader election and epochs. Applications use it for their own elections by creating ephemeral sequential nodes (a znode, ZooKeeper's basic object, like a file in a tiny filesystem; "ephemeral" means it is deleted automatically when the client that created it disconnects, "sequential" means ZooKeeper appends an ever-increasing number to its name): the lowest sequence number is leader, and the node disappears when that client's session (its live connection to ZooKeeper) dies. |
| etcd | A coordination store built on Raft (the store behind Kubernetes) | Its own members elect a Raft leader. Applications elect their leader with a key attached to a lease (a time-limited grant that expires unless the holder keeps renewing it); the client library offers an election API that does this for you. |
Note the two layers. A database such as CockroachDB or TiKV (distributed SQL/key-value databases that split their data into many small pieces) embeds Raft and elects a leader per data range (one such piece: a contiguous slice of the keyspace, replicated and led independently of the other pieces). A service that is not itself replicated (say, one active scheduler among three instances) borrows an election from etcd or ZooKeeper instead of implementing consensus.
How leader election affects availability
While there is no leader, the cluster cannot accept writes, and strongly consistent reads (reads guaranteed to reflect every write acknowledged before them, rather than possibly returning slightly old data) also stall. The outage is roughly:
failure detection time + election time + client retry time.
Worked example with etcd's documented defaults (heartbeat 100 ms, election timeout 1000 ms): a leader crashes. Followers wait up to about 1 s without a heartbeat, one starts an election, and with a network round trip of a few milliseconds it wins almost immediately. Clients that were mid-request see an error or timeout and retry. So a leader crash costs on the order of one to two seconds of write unavailability, not zero. A 5-member cluster tolerates 2 simultaneous failures (3 of 5 is still a majority); a 3-member cluster tolerates 1.
Reads that can accept slightly old data may be served by any follower during the gap, which is a deliberate trade of freshness for availability.
What an architect must consider
Network partitions. Suppose 5 nodes split into groups of 3 and 2. Only the group of 3 can elect a leader and commit writes; the group of 2 must refuse writes. If the old leader was in the group of 2, it keeps thinking it is leader until it notices it cannot reach a majority. That is the split brain risk (two nodes both acting as leader). Raft prevents two committed histories because the minority leader cannot get majority acknowledgements, but the stale leader can still serve stale reads or keep doing side effects outside the database unless:
- reads go through the leader with a majority check or a leader lease (a period during which the leader knows no one else can be elected), and
- external side effects carry a fencing token (the term number, checked by the receiving system so it rejects anything from an older term).
Placement. Put members in at least three failure domains (availability zones or regions). With two zones, losing the zone holding the majority takes the cluster down.
Leader churn. Frequent re-elections cost more than one clean failover, because each election is a write outage. Common causes are an election timeout set too close to the real network round trip, slow disks (a leader stuck in a disk sync misses heartbeats), long garbage-collection pauses and overloaded CPUs. The fixes are tuning the timeout to at least 10 times the round trip time (etcd's own guidance), fast dedicated disks, and alerting on the rate of leader changes rather than just on "is there a leader".
Cluster size. Use an odd number of voters, usually 3 or 5. Going from 5 to 7 tolerates one more failure but every write now waits for 4 acknowledgements instead of 3, so writes get slower.
Trade-offs and pitfalls
- Consensus is not free availability. It trades availability during partitions for correctness. If the data can tolerate conflicts (a "likes" counter, a shopping cart), a leaderless eventually consistent design (every replica can accept writes independently, and copies converge to the same value over time rather than agreeing instantly) may be the better fit.
- Rolling your own election with a heartbeat and a timeout (whoever has not heard from the leader for 5 s takes over) produces two leaders the first time a network is slow rather than dead. Borrow a proven implementation.
- Believing the process that holds leadership is the only one acting. A leader paused by garbage collection can wake up and act after it has been replaced. Fencing tokens, not timeouts, make that safe.
- Watching only "leader exists". A cluster that re-elects every few minutes looks healthy on that metric while clients see repeated error spikes.
What role do heartbeats and failure detectors play in leader-based distributed systems? Describe the difference between a heartbeat message and a full liveness check, and how timeout selection affects detection speed versus false positives.
Sample Answer
Direct answer
In a leader-based system, followers need to know when the leader has died so they can elect a new one, and the leader needs to know which followers are still with it. Heartbeats are small periodic "I am alive" messages, and a failure detector is the logic that turns missing heartbeats into a suspicion that a node has failed. A heartbeat only proves the process can send a packet; a full liveness check proves it can actually do its job (read, write, reach its dependencies). The timeout sets the balance: short timeouts detect real crashes quickly but also declare healthy-but-slow nodes dead, causing needless elections.
How it works in a leader-based system
- The leader sends a heartbeat to each follower every interval (for example 100 ms). In Raft (a leader-based consensus protocol) the heartbeat is an empty AppendEntries message (the message Raft normally uses to replicate log entries), so it also carries the leader's term (a number that increases with every election, letting nodes tell a current leader from an old one) and commit progress (the log position it has confirmed a majority has stored).
- Each follower resets a timer whenever it hears from the leader. If the timer expires, the follower suspects the leader and starts an election.
- A failure detector can only ever suspect. In a real network, a crashed node and a very slow node look identical from outside, so no timeout can be both always fast and always right.
Heartbeat vs full liveness check
| Heartbeat | Full liveness (health) check | |
|---|---|---|
| What it proves | The process is running and the network path works | The node can do real work: write to disk, serve a request, reach its database |
| Cost | Tiny, sent every 100 ms or so | Heavier, run every few seconds |
| Typical false "healthy" | A leader whose disk is hung still sends heartbeats from a separate thread, so followers keep it in charge while no write can commit | Rare: it exercises the real path |
| Typical use | Consensus-level leader detection | Load balancers, orchestrators deciding to restart or remove a node |
Real systems combine them. For example, a leader that cannot reach a majority (more than half the cluster's voting members) stops considering itself leader even though its heartbeat thread is fine (Raft's CheckQuorum idea), and a health check that writes a test value catches the hung-disk case that heartbeats miss.
Timeout selection: speed vs false positives
Worked example with assumed numbers: heartbeat every 100 ms, and each heartbeat independently has a 1% chance of being lost or arriving too late. A healthy leader is falsely suspected only if k heartbeats in a row all go missing, probability 0.01^k, and there are 864,000 heartbeat slots per day at a 100 ms interval.
INTERVAL_MS = 100 # heartbeat period
LOSS = 0.01 # chance any single heartbeat is lost or late, independently
WINDOWS_PER_DAY = 24 * 3600 * 1000 // INTERVAL_MS
for k in (2, 3, 5, 10):
timeout_ms = k * INTERVAL_MS
p_false = LOSS ** k # k consecutive misses from a healthy peer
per_day = p_false * WINDOWS_PER_DAY # one chance per heartbeat slot
print(f"timeout={timeout_ms:5d} ms ({k:2d} missed beats): "
f"false-suspicion rate = {per_day:.3g}/day per monitored peer, "
f"crash detected within {timeout_ms} ms")
Output:
timeout= 200 ms ( 2 missed beats): false-suspicion rate = 86.4/day per monitored peer, crash detected within 200 ms
timeout= 300 ms ( 3 missed beats): false-suspicion rate = 0.864/day per monitored peer, crash detected within 300 ms
timeout= 500 ms ( 5 missed beats): false-suspicion rate = 8.64e-05/day per monitored peer, crash detected within 500 ms
timeout= 1000 ms (10 missed beats): false-suspicion rate = 8.64e-15/day per monitored peer, crash detected within 1000 ms
The lesson: each extra missed heartbeat you require costs one interval (100 ms) of detection time and cuts random false alarms by a factor of 100. Going from 200 ms to 500 ms takes false suspicions from about 86 a day to almost never, for 300 ms of extra detection time.
The catch: those tiny numbers assume losses are independent. Real false positives come from correlated delays: a 2-second garbage-collection pause, a saturated network link, or a slow disk stalls every heartbeat at once, and no reasonable k hides that. So in practice:
- Set the heartbeat interval near the network round-trip time and the election timeout at around 10 times the round-trip time (a common rule of thumb, also given in the tuning guidance for etcd, a Raft-based key-value store), then check it against the longest pause you actually observe.
- Randomise election timeouts (for example 150 to 300 ms in the Raft paper) so followers do not all time out together and split the vote (several followers become candidates in the same term at once, each collects fewer than a majority, and the election fails with no leader chosen).
- Consider an adaptive detector (depth beyond most interviews): the phi-accrual detector used by Cassandra (a distributed NoSQL database) and Akka (a toolkit for building distributed, concurrent systems on the JVM) tracks the recent distribution of heartbeat arrival times and outputs a suspicion level instead of a yes/no, so it automatically tolerates a peer on a slower link.
Pitfalls
- Treating a missed heartbeat as proof of death. It is a suspicion; the system must stay safe when the "dead" leader is actually alive, which is why Raft uses terms and majorities rather than trusting the detector.
- Running heartbeats on a thread that keeps working while the real work path is stuck, so the node looks healthy while doing nothing.
- Tuning timeouts on a quiet test cluster and then seeing election storms under production load, when pauses get longer.
Unlock Full Question Bank
Get access to all 23 Consensus and Coordination Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.