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.
How would you test that a 5-node Raft cluster keeps its safety guarantees under real failures: network partitions, message loss, delayed messages, disk stalls, and process pauses? What would you monitor, and what would tell you a correctness regression had crept in?
Sample Answer
Direct answer
I would not test that the cluster "stays up"; I would test that it never violates Raft's safety properties while faults are injected, and I would check that by recording every client operation and every leadership event and running a checker over that history afterwards. The approach is the one Jepsen (an open-source framework for testing distributed databases under faults) popularised: a harness drives a realistic workload through clients, a nemesis (the fault-injecting component) partitions the network, drops and delays packets, stalls disks and pauses processes on a schedule, and a checker verifies the recorded history is linearizable (every operation appears to take effect at a single instant between its start and its reply, in an order consistent with real time). Monitoring during the run explains why something happened; the checker is what tells you whether safety broke.
What "safety" means for Raft, concretely
Safety means nothing bad ever happens, even if the cluster is temporarily unavailable. For a 5-node Raft cluster (tolerates 2 failures, quorum of 3):
| Property | Plain meaning | How it shows up as a bug |
|---|---|---|
| Election safety | At most one leader per term (term: the numbered leadership period) | Two nodes both report being leader of term 7 |
| Log matching | If two logs contain an entry with the same index and term, then the logs are identical in all entries up through that index (a follower's AppendEntries check enforces this by rejecting an entry whose immediately preceding entry does not match) | Two nodes agree on the term at index i but hold different entries at index i-1 |
| State machine safety | Once an entry at index i is committed, every node applies the same entry at i | Two nodes applied different values at the same index |
| Leader completeness | A new leader has every committed entry | A write the client was told succeeded disappears after failover |
| Linearizable client view | Reads never go backwards and never miss an acknowledged write | A read after a successful write returns the older value |
Here "state machine" is used the way state machine replication uses it: the data structure the log's operations are applied to (a key-value store's data, in the examples below), which every node keeps in sync only by applying the same entries in the same order.
Availability (liveness) is measured separately: a majority side should recover a leader within a bounded time after faults heal. A cluster that stays leaderless forever is a bug, but a different class from lost writes.
Test design
1. Workload
Use operations whose history can be checked:
- Register workload: clients do read, write and compare-and-set (an atomic "update this key only if it still holds the value I last read" operation) on a handful of keys. Few keys means lots of contention, which is where bugs hide.
- Append-only set or bank workload: each client appends unique values or transfers between accounts; the invariant is "every acknowledged append is present" or "total balance is constant".
Every client records invoke with a timestamp, then ok, fail (definitely did not happen) or info (timed out, unknown outcome). Treating timeouts as unknown, not failed, is essential: a write that timed out may still have committed.
2. Faults, and why each one matters
| Fault | How to inject | What it targets |
|---|---|---|
| Network partitions (majority/minority, bridge: one node relays between two otherwise-cut-off groups, isolate leader) | iptables (Linux's kernel firewall, used here to drop packets between chosen node pairs) rules or a proxy between nodes | Stale leader in the minority still answering reads; election safety |
| Message loss | tc netem loss (netem is the network emulator in Linux traffic control) | AppendEntries retry and log repair logic |
| Delayed and reordered messages | tc netem delay ... reorder | Old-term messages arriving late and being wrongly accepted |
| Disk stalls | Fault-injecting filesystem, device-mapper delay target (a Linux block-device layer that can be told to add artificial latency to reads or writes on a virtual disk), or freezing the filesystem | fsync (forcing data onto the disk) ordering: acknowledging a vote or an append before it is durable |
| Process pauses | SIGSTOP / SIGCONT (Unix signals that freeze, then later resume, a process without killing it, so its memory and belief about being leader survive untouched) on the leader for longer than the election timeout | A paused leader waking up and acting as if still leader (the classic garbage-collection pause case) |
| Crashes and restarts, including power-loss style | SIGKILL (a signal that terminates the process immediately, with no cleanup, standing in for a hard crash), and with a filesystem that drops unsynced writes | Losing the persisted currentTerm / votedFor (the two fields Raft must fsync to disk before replying to any vote or append: the highest term this node has seen, and who it voted for in that term) and voting twice in one term |
| Clock skew (if leases are used) | Adjust clocks on individual nodes | Lease-based reads being served by a node whose lease has actually expired |
Schedule faults so they overlap (pause the leader while a partition heals, crash a follower mid-snapshot). Single isolated faults find few bugs; combinations find most.
3. The checker
Linearizability checking of the full history is done with an existing checker (Knossos or Elle in the Jepsen ecosystem, or Porcupine for Go: open-source linearizability checkers built for exactly this kind of recorded history, not something to write from scratch). Alongside it, simple invariant checks over the leadership and commit events catch the most damaging bugs cheaply. This small checker runs over events a harness records:
from collections import defaultdict
def check_history(events):
'''events: dicts recorded by a test harness during a fault-injection run.
kinds: 'leader' (node became leader in term), 'commit' (node reports log entry
at index committed with a value), 'ack' (client was told write W succeeded),
'final' (value set present on a node after healing).'''
problems = []
leaders = defaultdict(set) # term -> nodes that claimed leadership
committed = {} # index -> value first seen committed
acked, final_values = set(), None
for e in events:
if e["kind"] == "leader":
leaders[e["term"]].add(e["node"])
if len(leaders[e["term"]]) > 1:
problems.append(f"election safety: term {e['term']} has leaders {sorted(leaders[e['term']])}")
elif e["kind"] == "commit":
prev = committed.setdefault(e["index"], e["value"])
if prev != e["value"]:
problems.append(f"state machine safety: index {e['index']} committed as {prev!r} and {e['value']!r}")
elif e["kind"] == "ack":
acked.add(e["value"])
elif e["kind"] == "final":
final_values = set(e["values"])
if final_values is not None:
for lost in sorted(acked - final_values):
problems.append(f"durability: acknowledged write {lost!r} missing after heal")
return problems
healthy = [
{"kind": "leader", "term": 1, "node": "n1"},
{"kind": "commit", "node": "n1", "index": 1, "value": "x=1"},
{"kind": "commit", "node": "n3", "index": 1, "value": "x=1"},
{"kind": "ack", "value": "x=1"},
{"kind": "leader", "term": 2, "node": "n4"}, # new term after partition: fine
{"kind": "commit", "node": "n4", "index": 2, "value": "x=2"},
{"kind": "ack", "value": "x=2"},
{"kind": "final", "values": ["x=1", "x=2"]},
]
regressed = [
{"kind": "leader", "term": 3, "node": "n1"},
{"kind": "leader", "term": 3, "node": "n5"}, # two leaders in one term
{"kind": "commit", "node": "n1", "index": 7, "value": "y=a"},
{"kind": "commit", "node": "n5", "index": 7, "value": "y=b"},
{"kind": "ack", "value": "y=a"},
{"kind": "ack", "value": "y=b"},
{"kind": "final", "values": ["y=b"]},
]
print("healthy run:", check_history(healthy) or "no violations")
print("regressed run:")
for p in check_history(regressed):
print(" -", p)
Output:
healthy run: no violations
regressed run:
- election safety: term 3 has leaders ['n1', 'n5']
- state machine safety: index 7 committed as 'y=a' and 'y=b'
- durability: acknowledged write 'y=a' missing after heal
With 5 nodes, winning an election needs 3 votes. Two different candidates can each reach 3 votes in the same term only if their vote sets overlap, because 3 + 3 = 6 is more than the cluster's 5 nodes: at least one node must appear in both. That node voted for both n1 and n5 in term 3, which Raft's one-vote-per-term rule forbids while a node is running normally. The regressed history is the signature of a node that forgot its vote across a restart (it voted for two candidates in term 3), which is exactly the bug an fsync-skipping "optimisation" introduces: the node's currentTerm / votedFor was never durably written before it crashed, so on restart it had no memory of having already voted in term 3, and voted again.
4. Deterministic reproduction
Real-network tests are non-deterministic. Pair them with a deterministic simulation of the Raft implementation (single thread, simulated network and disk, a seeded random scheduler) so every failure found can be replayed from its seed, and so thousands of fault schedules can run per build. Record the seed and the fault schedule with every Jepsen-style run too.
What to monitor during the runs
Monitoring does not prove safety, but it explains failures and catches liveness regressions:
- Leader identity and term per node over time (plotted against the fault timeline).
- Commit index (how far the leader has confirmed a majority has durably stored the log) and applied index (how far this particular node has actually executed those entries into its own state machine, which normally lags the commit index slightly) per node: a node whose applied index goes down, or whose commit index jumps past the leader's, is a red flag.
- Election count and time to elect after each fault heals.
- fsync latency percentiles and the number of pending proposals.
- Client-side: error rate, unknown-outcome rate and latency percentiles (the 99th percentile, p99, matters most during failover).
What tells you a correctness regression crept in
- Any checker violation. A single non-linearizable history, a lost acknowledged write or two leaders in one term is a release blocker, not a flake. Consensus bugs are rare-event bugs; "it passed on retry" means the bug exists.
- Monotonicity violations in metrics: terms or applied indexes going backwards on a node.
- Divergent state digests (a state digest is just a hash of the whole replicated state): after faults heal and the cluster is quiet, hash the state machine on every node; any difference is a safety failure.
- Changed failure-rate baseline: run a fixed fault matrix (same seeds, same schedules) on every build. If a schedule that used to pass now fails, bisect the commits with that seed (binary-search through the commit history, rerunning the same fixed seed at each candidate commit, until the exact change that introduced the regression is found).
- Liveness drift: median time to elect after a partition heals growing between builds, often from a changed timeout or back-off.
Trade-offs and pitfalls
- Counting timeouts as failures makes the checker report false lost writes, or worse, hides real ones.
- Checking only final state misses stale reads during the fault, which is where most real linearizability bugs live (minority leaders answering reads).
- Faults that never overlap or never target the leader find little.
- Linearizability checking is expensive (the general problem is NP-complete: no known algorithm avoids trying an exponential number of possible orderings as the history grows), so keep histories short per key and use many keys, or use a checker built for the workload type.
- Testing on tmpfs (a filesystem backed by RAM instead of disk, so every write looks instantly durable even though a real crash would lose it) hides every fsync bug. Disk faults must hit a real or emulated durable device.
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.
Your organization needs a ZooKeeper-like coordination service for multi-region microservices, supporting ephemeral locks, distributed barriers, and leader election with sub-second latencies. Describe replica placement, the read and write path for each primitive, how you would handle failover, and how you would keep ephemeral operations low-latency.
Sample Answer
Direct answer
Sub-second latency and multi-region reach pull against each other, so I would not build one global quorum for everything. Each region gets its own 3-voter coordination cluster spread across three availability zones (AZs) (isolated data centres within one region), serving that region's locks, barriers and leader elections with single-digit-millisecond writes. A separate 5-voter global cluster (2/2/1 across three regions) handles the rare primitives that are genuinely global, with non-voting observers in every region to serve local reads. Every primitive is built on three building blocks: sessions (a client's heartbeat-kept connection), ephemeral nodes (entries deleted automatically when their session expires) and sequential nodes (entries whose name gets a unique increasing suffix). Failover works because session state is replicated through the log (an ordered, append-only record of every write that all voters agree on and apply in the same order, the same mechanism Raft uses), so a client can reconnect to any surviving server within its session timeout.
Why not one global quorum
A quorum is a majority of voters, and every write must reach one before it is acknowledged. With illustrative inter-region round trips (not measurements) of 65 to 140 ms, a global write costs at least 65 ms plus disk sync. A client whose nearest server is 140 ms from the leader, plus a further 65 ms for the leader to reach quorum, costs that client over 200 ms end to end: 140 + 65 = 205 ms. Still sub-second, but a contended global lock's handoff is not free either: releasing costs one write (the delete, 65 to 140 ms plus fsync), the next waiter's watch notification piggybacks on that same replicated log so it adds little on its own, and the waiter's re-check (listing children to confirm it is now lowest) needs a linearizable read, which costs a sync round trip to the leader before the read, another 65 to 140 ms, if the waiter's connected server is not the leader. Chained, that is roughly 130 to 280 ms per handoff at worst (one write plus one synced read), not several hundred, and it only approaches the lower end of "several hundred" when the client, its server and the leader all sit in different regions. Most coordination is regional anyway: a job's leader election, a deploy barrier, a per-shard lock. Keep those in-region.
flowchart TB
subgraph East[us-east region]
E1[voter az1] --- E2[voter az2] --- E3[voter az3]
EO[observer: global reads]
end
subgraph West[us-west region]
W1[voter az1] --- W2[voter az2] --- W3[voter az3]
WO[observer: global reads]
end
G[global 5-voter cluster, 2/2/1 over 3 regions] --> EO
G --> WO
Replica placement
| Cluster | Voters | Tolerates | Write latency (illustrative) |
|---|---|---|---|
| Regional (one per region) | 3, one per AZ | 1 AZ loss | 1 to 2 ms network plus fsync (the disk flush that makes a write durable before it is acknowledged) |
| Global | 5 across 3 regions, 2/2/1 | 1 full region loss | about the round trip to the nearest remote region |
| Observers | Any number, non-voting | Nothing (they add read capacity only) | Reads local; writes forwarded |
Observers receive the committed log (the same replicated write stream voters apply, but they take no part in deciding when a write commits) and so do not vote, meaning adding them never enlarges the quorum or slows writes; their reads can lag the leader briefly, which the pitfalls below cover.
Read path and write path
Writes (create, delete, set): client sends to its connected server, which forwards to the leader; the leader appends to the log, replicates to a quorum, commits, applies, and the client's server replies. All writes are totally ordered by a log position (ZooKeeper calls it the zxid).
Reads: served from the connected server's local copy. Guarantee: each client sees a consistent, in-order view (it never goes backwards and sees its own writes), but may lag other clients' writes. For a linearizable read (reflecting every write acknowledged before the read began), the client first issues sync, which makes its server catch up with the leader, then reads.
Each primitive
Ephemeral lock (mutual exclusion)
- Create
/locks/job-42/lock-as ephemeral + sequential, getting for examplelock-0000000017. - List children. If mine has the lowest sequence number, I hold the lock.
- Otherwise set a watch (a one-time change notification) on the node immediately before mine only, not on the parent. When it disappears, re-check. Watching only the predecessor avoids the herd effect (also called a thundering herd below), where one release wakes every waiter.
- Release by deleting my node; if I crash, session expiry deletes it.
- Use the node's creation log position as a fencing token (an increasing number the protected resource checks to reject a stale holder).
Cost: acquiring uncontended is 1 write plus 1 read; each handoff is 1 delete, 1 notification and 1 read.
Leader election: the lock recipe where the winner is "leader" and everyone else is a standby watching their predecessor. Publish the leader's address in the lowest node's data.
Distributed barrier (N workers must all arrive before any proceeds):
- Each worker creates an ephemeral child under
/barriers/deploy-9/. - Each lists children with a watch on the parent; when the count reaches N, all proceed.
- A double barrier adds an exit phase: workers delete their node when done, and wait until the directory is empty before the next phase.
Ephemeral children mean a crashed worker drops out instead of holding the barrier forever; the application decides whether N-1 is acceptable.
Failover
Leader failure in a regional cluster: followers stop hearing heartbeats, elect a new leader (typically within one to two seconds on an intra-region network), and resume. In-flight writes that had not committed are retried by clients.
Sessions across failover: session creation, and session expiry, are both decided by the leader and replicated. Servers forward client heartbeats (session pings) to the leader's session tracker. A client that loses its server reconnects to another one with its session ID and password; if it arrives before the timeout, its ephemeral nodes survive.
The crucial tuning rule: session timeout must exceed election time plus client reconnect time. Worked numbers: election completes within about 2 s in the worst case, and a client needs about 1 s to detect the dead server and connect elsewhere. A 6 s session timeout leaves 3 s of margin; a 2 s timeout would expire every session in the region during each election, deleting every lock and triggering a thundering herd (the herd effect described above, but for elections instead of lock waiters) of re-elections.
Region failure: that region's regional cluster is gone with it; services in the region are gone too, so there is nothing to coordinate. The global cluster keeps quorum (it lost at most 2 of 5 voters).
Keeping ephemeral operations low-latency
- Stay in-region: regional quorums make every ephemeral create or delete a same-region write.
- Session heartbeats are cheap local traffic: each client pings its nearby server every third of the timeout (2 s for a 6 s timeout); the server aggregates liveness for the leader. With 10,000 clients per region that is 5,000 pings per second spread across servers, handled in memory and without disk writes.
- Expiry is batched: the leader checks sessions in time buckets and issues one close-session operation per expired session, which deletes all its ephemeral nodes in a single replicated operation.
- Watch the predecessor, not the parent, so a lock release costs one notification, not N.
- Keep node data tiny (identifiers, not payloads); large data belongs elsewhere.
Trade-offs and pitfalls
- Losing the session is losing the lock. Clients must stop protected work on the disconnected signal, not wait for the expired notification, because by then another holder may already exist.
- Local reads are not linearizable. Checking "am I still the lowest node?" from a lagging observer can be wrong; use
syncbefore safety-critical reads. - Global primitives stay global. If a lock truly must be exclusive across regions, it lives in the global cluster and pays the WAN (wide area network: the internet-scale links between regions, much slower than an in-region link) round trip; do not fake it with two regional locks.
- Timeout too short causes mass expiry; too long delays takeover after a real crash. The 6 s example means a crashed leader's lock is freed after about 6 s.
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 44 Consensus and Coordination Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.