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.
When would you recommend using strong-consensus protocols such as Raft or Paxos versus eventual-consistency approaches? As a Solutions Architect, compare latency, throughput, failure modes, operational overhead, and appropriate use cases like metadata management versus user-facing high-volume data.
Sample Answer
Direct answer
Use a strong-consensus protocol (Raft or Paxos: replicas commit each write only once a majority has stored it, so everyone sees one agreed order) for small, high-value state where a conflict or a lost write is a correctness failure: cluster membership, leader leases, shard maps, schema and configuration, locks. Use eventual consistency (replicas accept writes independently and converge later) for large, high-volume, user-facing data where a briefly stale read is harmless and conflicts can be merged: timelines, activity feeds, counters, carts, telemetry. Before reaching for either, check whether a plain relational database already gives you the consistency you need, because for a lot of "metadata" it does, and you already operate it.
The comparison
Throughout this table, a quorum is the minimum number of replicas that must respond before an operation counts as done; a write quorum of 1 means one replica's acknowledgement is enough, while consensus protocols require a majority.
| Axis | Strong consensus (Raft/Paxos) | Eventual consistency (leaderless, meaning any replica can accept a write directly with no elected coordinator, or async replication) |
|---|---|---|
| Write latency | At least one round trip from leader to the nearest majority, plus a disk sync; cross-region this means tens to hundreds of ms | Can acknowledge after one local replica (write quorum of 1), so local-network latency |
| Read latency | Linearizable reads (every read reflects all writes acknowledged before it started) need the leader to confirm it still leads; stale reads can come from any replica | Any replica, local latency, possibly stale |
| Throughput | Bounded by one leader per consensus group; scale by splitting data into many groups | Scales roughly with replica count; any node accepts writes |
| Behaviour during a network partition | Minority side stops accepting writes (chooses consistency over availability) | Both sides keep working; conflicts appear and must be resolved |
| Failure modes | Unavailability: quorum loss, leader-election gaps, slow disk causing leader churn | Anomalies: stale reads, lost updates under last-writer-wins (when two writes conflict, whichever carries the later timestamp wins and the other silently vanishes), resurrected deletes (a deleted item reappearing because a replica that missed the delete, or an old un-deleted copy, gets merged back in before the delete marker has fully propagated), divergence needing repair |
| Operational overhead | Odd-sized voter sets across failure domains, careful membership changes (adding or removing a voting replica has to go through a protocol step, not just editing a config file, or it can split one majority into two disjoint ones), disk and network latency sensitivity, snapshots and compaction (periodically writing the full state to disk, then discarding the older log entries it now makes redundant, so the log does not grow forever) | Anti-entropy repair (a background job where replicas compare their data, often via hashes, and reconcile anything that never fully propagated), tombstone management (keeping delete markers around long enough for the delete to reach every replica before safely discarding them), conflict-resolution code, harder correctness testing |
| Typical data size | Small: etcd's documented default storage quota is 2 GiB with 8 GiB suggested as a maximum, and requests default to at most 1.5 MiB | Terabytes to petabytes |
Why metadata and user data fall on opposite sides
Metadata (which node owns shard 17, which instance is the active scheduler, what the current config version is) is small, read often, written rarely, and every component acts on it. If two nodes disagree about who owns shard 17, both may write to it and corrupt it. The cost of consensus (a few milliseconds per rare write) is trivial next to that risk.
User-facing high-volume data (likes, views, a social feed, sensor readings) is large and written constantly. A "like" counter off by one for two seconds harms nobody; making every like wait for a cross-region majority would add latency to the hottest path and cap throughput at what one leader per group can order.
Worked example: a feed service takes 50,000 writes per second. With consensus sharded into groups whose leaders each sustain, say, 5,000 ordered writes per second (an assumed figure; measure your implementation), you need at least 50,000 / 5,000 = 10 groups before any headroom, each with 3 or 5 replicas, and every write pays a majority round trip. An eventually consistent store absorbs the same load by adding nodes, with no per-write coordination. Meanwhile the same service's shard map changes a few times a day; putting that in etcd costs nothing measurable.
The alternative that often wins for metadata: a relational database
Many teams reach for etcd or ZooKeeper for metadata that fits comfortably in a relational database such as Postgres with a synchronous standby (a replica that must confirm it has durably stored a write before the primary reports success, so no acknowledged write ever exists on only the primary) and managed failover (an automated system that detects the primary is dead and promotes the standby, without a human doing it by hand). That choice is often better when:
- The metadata is relational and queried in rich ways (joins, filters, reporting), which a key-value store makes painful.
- It needs multi-row transactions (move a tenant: update its shard, quota and routing rows atomically).
- Failover in tens of seconds is acceptable, and you already run and back up the database.
Note that the database's own automated failover usually relies on a consensus-backed arbiter underneath (a managed service's control plane, or a tool like Patroni using etcd, a small, strongly-consistent key-value coordination store built on Raft, or Consul or ZooKeeper to pick the primary), so you are still using consensus, just not operating it yourself.
A dedicated consensus store still wins when you need:
- Watches: clients notified within milliseconds when a key changes, rather than polling.
- Leases and ephemeral keys: a key that disappears automatically when its owner stops renewing, which is the core of leader election and service membership.
- Fast failover (about a second with etcd's default 1000 ms election timeout) and independence from the database whose failover you might be coordinating.
Decision rule I would give a team
- Would a stale read or a merged conflict cause a correctness failure (double allocation, two leaders, lost money)? If no, prefer eventual consistency.
- If yes, is the data small and coordination-shaped (leases, membership, watches)? Use etcd, ZooKeeper or Consul (HashiCorp's service-discovery and coordination store, also Raft-based).
- If yes and it is relational or transactional, a relational database with synchronous replication is usually the simpler answer.
- If yes and it is large and high-volume (a ledger, inventory), use a database with consensus built in and sharded (distributed SQL databases such as Google Spanner, CockroachDB, TiDB or YugabyteDB), not a coordination store.
What would flip the recommendation: a hard requirement to keep writing in a region cut off from the others (only eventual consistency can do that), or a need for strict ordering on high-volume data (then sharded consensus, accepting the latency).
Trade-offs and pitfalls
- Putting user data in etcd or ZooKeeper because it is already there: the size limits and single-leader write path will bite.
- Using eventual consistency for leadership or locks: an asynchronously replicated lock can be held by two clients after a failover.
- Assuming consensus means exactly-once side effects: a deposed leader can still act on stale belief unless downstream systems check a fencing token (a number that increases with each new leader, used to reject the old one).
- Mixing both without saying which data is which: document, per dataset, which consistency level applies and why.
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.
Propose performance optimizations to increase the throughput of a Raft-backed replicated log running on modern SSDs. Explain the correctness and persistence trade-offs involved, and how you would tune the relevant parameters.
Sample Answer
Direct answer
A naive Raft log (the replicated log of Raft, a leader-based consensus protocol where a leader commits an entry once a majority of nodes have stored it) commits one entry per round of "leader writes, leader sends, follower fsyncs, follower acks", so throughput is capped at a few hundred entries per second by fsync latency, not by the SSD's bandwidth. The big wins, in order: batch many entries per fsync and per message, pipeline several AppendEntries (AppendEntries: the RPC message a Raft leader uses to send new log entries to, and replicate them on, its followers) in flight, write the leader's disk in parallel with replication, and keep the apply and snapshot work off the replication path. The one thing you must not do is acknowledge an entry before it is durably on disk, because Raft's safety proof assumes a node never forgets what it acknowledged or voted for.
Why fsync, not bandwidth, is the limit
fsync asks the operating system to force buffered writes onto stable storage and waits for the device to confirm. On a modern SSD this takes on the order of a millisecond or less, and it costs about the same whether it flushes 1 KB or 64 KB. So one fsync per entry wastes almost all of the device's bandwidth. Raft requires each follower to persist an entry before acknowledging it, and each node to persist its term and vote before answering an election, so those fsyncs are on the critical path.
Worked model
A ceiling model for a 5-node cluster. All inputs are assumptions stated in the code, chosen as round numbers; the point is how each optimisation moves the bottleneck, not the absolute figures.
# Throughput ceilings for a 5-node Raft log. All inputs are assumptions.
N = 5
ENTRY_B = 1024 # bytes per log entry
RTT_MS = 0.5 # leader <-> follower round trip
FSYNC_MS = 1.0 # one fsync on the WAL device
NIC_BPS = 10e9 / 8 # 10 Gbit/s leader NIC, in bytes/s
DISK_BPS = 1e9 # sustained sequential write, bytes/s
def ceiling(batch, inflight, parallel_leader_fsync):
# Commit round: leader fsync, then send, then follower fsync + ack,
# unless the leader writes its own disk while replicating.
leader = 0 if parallel_leader_fsync else FSYNC_MS
round_ms = leader + RTT_MS + FSYNC_MS
# Pipelining keeps `inflight` rounds outstanding, but each follower's
# fsyncs are serial, so rounds cannot complete faster than one per fsync.
rounds_per_s = min(inflight * 1000 / round_ms, 1000 / FSYNC_MS)
by_rounds = rounds_per_s * batch
by_nic = NIC_BPS / (ENTRY_B * (N - 1)) # leader sends each entry N-1 times
by_disk = DISK_BPS / ENTRY_B
return min(by_rounds, by_nic, by_disk), round_ms
steps = [
("naive: 1 entry, 1 in flight, serial fsync", 1, 1, False),
("+ leader fsync in parallel with replication", 1, 1, True),
("+ pipelining (4 in flight)", 1, 4, True),
("+ batching (64 entries per fsync)", 64, 4, True),
("+ batching (512 entries per fsync)", 512, 4, True),
]
for label, b, d, par in steps:
tput, rms = ceiling(b, d, par)
print(f"{label:45s} round={rms:.1f} ms ceiling={tput:9,.0f} entries/s")
print(f"NIC bound {NIC_BPS/(ENTRY_B*(N-1)):,.0f}/s, disk bound {DISK_BPS/ENTRY_B:,.0f}/s")
Output:
naive: 1 entry, 1 in flight, serial fsync round=2.5 ms ceiling= 400 entries/s
+ leader fsync in parallel with replication round=1.5 ms ceiling= 667 entries/s
+ pipelining (4 in flight) round=1.5 ms ceiling= 1,000 entries/s
+ batching (64 entries per fsync) round=1.5 ms ceiling= 64,000 entries/s
+ batching (512 entries per fsync) round=1.5 ms ceiling= 305,176 entries/s
NIC bound 305,176/s, disk bound 976,562/s
What the model shows: parallel leader writes and pipelining help, but they are capped at one fsync per millisecond per follower (1,000 rounds/s). Batching is what breaks the fsync ceiling: 512 entries per fsync reaches the leader's network card limit, because the leader sends every entry to four followers (1 KB x 4 per entry against 1.25 GB/s). At that point the next lever is the network, not the disk.
The optimisations, and the correctness trade-off of each
| Optimisation | What it does | Correctness / persistence consequence |
|---|---|---|
| Batching (group commit) | Collect all entries that arrived while the previous fsync ran; write and fsync them together; send them in one AppendEntries | Safe. Each entry is still durable before it is acked. Costs latency: an entry may wait for the current batch. Use adaptive batching (send whatever is queued when the previous round finishes) rather than a fixed timer, so light load stays low-latency. |
| Pipelining | Send the next AppendEntries before the previous one is acknowledged | Safe, because followers still check the previous-entry index and term (Raft's log-matching check: a follower only accepts new entries if its own log already agrees with the leader at the point just before them, so pipelined messages cannot silently reorder or corrupt the log). On a rejection the leader must back up nextIndex (its per-follower guess of the next log position to send) and resend, so bound in-flight messages to limit wasted work. |
| Leader writes its disk in parallel with sending | Leader does not wait for its own fsync before replicating | Safe per the Raft dissertation: the leader counts itself in the majority only once its own write completes, and an entry can be committed by a majority of followers even if the leader's disk is slower. |
| Asynchronous apply | Apply committed entries to the state machine (the actual application data, produced by executing each committed log entry in order, e.g. a key-value map) on a separate thread | Safe as long as reads that need the latest state wait for appliedIndex (the highest log position actually executed against the state machine so far) to reach the read's index. Replies to clients must wait for apply. |
| Snapshot tuning | Take snapshots less often, and without blocking the log (copy-on-write, meaning a write creates a new copy of the changed data instead of overwriting it in place, so the snapshot keeps reading a stable old version while writes continue, or a background thread) | Safe. Too-frequent snapshots steal disk bandwidth; too-rare ones make restarts and follower catch-up slow and let the log grow. |
| Dedicated WAL (write-ahead log, the append-only file each node fsyncs entries to) device, preallocated segment files | Avoids contention and file-metadata updates on each fsync | Safe; preallocation avoids an extra metadata journal flush (the filesystem's own bookkeeping write, separate from your data, normally needed whenever a file grows) when the file grows. |
| Skipping fsync, or acking from page cache (the OS's in-memory copy of recently written data, which is lost on a crash before it reaches the disk) | Removes the disk from the critical path | Unsafe. A follower that acks, crashes and restarts without the entry may form a different majority that elects a leader missing a committed entry: committed data is lost. Also unsafe for term and vote: a node that forgets its vote can vote twice in one term, allowing two leaders. |
| Battery- or capacitor-backed write cache | fsync returns once data is in power-protected cache | Safe only if the hardware genuinely protects the cache on power loss (enterprise SSDs with power-loss protection: a capacitor that keeps the drive powered just long enough to flush its cache to flash after the power cuts). Verify, do not assume. |
Tuning the parameters
Using the etcd/raft library (the Raft implementation behind etcd, a widely used consistent key-value store) as a concrete example (its Config struct), the knobs map directly onto the model:
MaxSizePerMsg: the largest AppendEntries payload. Bigger means more entries per round (throughput) but longer transmission and larger memory per in-flight message. Tune up until batches stop growing under peak load.MaxInflightMsgs: the pipelining depth per follower. A reasonable starting point is enough messages to cover one round trip: (round time x arrival rate) / entries per message. Concretely, using the model above: with single-entry messages (before batching), a 1.5 ms round trip, and a steady arrival of 800 entries/s,MaxInflightMsgs ~= (0.0015 s x 800) / 1 ~= 1.2, so 2 is the bare minimum; the model above used 4 to leave headroom for jitter and for the wasted round after anextIndexrejection. Too high wastes work after a rejection and holds memory.- Heartbeat and election ticks: not throughput knobs, but a leader saturated by large batches must still send heartbeats (small periodic empty AppendEntries a leader sends just to prove it is alive) in time, measured in ticks (etcd/raft's internal timer unit; a leader must send a heartbeat before enough ticks pass that a follower calls an election); very large messages can delay heartbeats on a slow link.
- Snapshot frequency (in etcd, the number of committed entries between snapshots): trade restart and catch-up time against the write amplification (writing more bytes to disk than the logical size of the data, because snapshotting rewrites already-durable state) of snapshotting.
Tuning method: load-test at the target entry size, watch fsync latency percentiles, batch size distribution, in-flight count and CPU, and raise one knob at a time until either latency at the p99 (99th percentile) breaks the SLO (service-level objective) or the next bottleneck (network, CPU for encoding, apply thread) appears.
Beyond a single log (depth beyond most interviews)
- Sharding into many Raft groups (multi-Raft) spreads leaders across machines; each group has its own log. Combine their WAL writes into one fsync per node to keep the fsync count flat as groups grow.
- Reads off the log: serve linearizable reads (each read reflects every write that completed before it, as if there were a single copy of the data) with leader leases (a time-bound promise from a majority that lets the leader serve reads locally without asking anyone) or ReadIndex (asking the leader for its current commit position and waiting to apply it before answering) instead of appending a read entry, so reads do not consume log throughput.
- Payload separation: store large values outside the log and replicate only a reference, reducing the bytes each follower must receive and fsync.
Pitfalls
- Measuring throughput with fsync disabled in a benchmark and quoting it as production capacity.
- Fixed batch timers (for example "flush every 5 ms"), which add latency at low load for no benefit.
- Letting apply fall behind: commit throughput looks great while reads block and memory grows with unapplied entries.
- Forgetting that the leader's network egress is
(n - 1)times the write rate; at large batch sizes it is the next bottleneck.
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.
You need a global configuration key-value store accessed by many microservices (feature flags, leader election, service discovery). Does this require consensus (e.g., Raft)? Explain the criteria you'd use to decide whether to use a consensus-backed service versus a lightweight eventually-consistent or database-backed alternative.
Sample Answer
Direct answer
Not all of it. Split the store by what goes wrong if a reader sees a stale value. Leader election and locks need a consensus-backed service (one where a majority of replicas agree on every write, such as etcd or ZooKeeper), because a stale read there means two instances both believe they are leader. Feature flags and service discovery do not: a flag that flips a few seconds late, or a service list that briefly includes a dead instance (which clients already survive through retries and health checks), is a latency problem rather than a correctness problem. My recommendation for a typical microservice estate: a small 3-node consensus cluster only for election and locks, and flags plus discovery served from an eventually consistent layer that is cheaper and stays readable during partitions.
Key terms
- Consensus (for example Raft): a protocol where a leader replicates each write to a majority before acknowledging it, giving linearizable behaviour: every read reflects every write acknowledged before it started, as if there were one copy.
- Eventually consistent: replicas may disagree briefly but converge if writes stop. Reads are fast and available during partitions, but can be stale.
- Database-backed: using an existing relational database (single primary) as the source of truth.
- Lease: a time-limited grant from the coordination service. The holder must renew it before it expires or the service revokes it automatically, which is how a dead or partitioned holder's claim disappears without anyone deciding by hand.
- Fencing token: a number that increases every time a lease or lock is granted. Whatever the lease protects (a downstream write, a job run) checks the token and refuses anything carrying an older one, so a holder that was paused past its expiry and wakes up late gets rejected even though it still believes it holds the lease.
- Watch: a subscription a client places on a key so the coordination service pushes it a notification the next time that key changes, instead of the client polling.
- Split-brain: two nodes each believing they are the sole primary (or leader) at the same time, usually because a failover happened while the old primary was still reachable by some clients.
- Ephemeral (sequential) node: a coordination-service entry that is deleted automatically when its owning session ends, for example because the owner's process crashed; "sequential" means the service appends an increasing number to the entry's name, useful for ordering.
The decision criteria
| Criterion | Question to ask | Points toward consensus when... |
|---|---|---|
| Cost of a stale read | If a reader sees a value 5 seconds old, is anything corrupted, or just late? | Stale data breaks mutual exclusion or ordering |
| Need for atomic compare-and-set | Do writers need "set only if unchanged" or unique ownership? | Yes, and it must hold across failover |
| Need for liveness detection | Must a key vanish automatically when its owner dies (leases, ephemeral keys)? | Yes: leases with fencing tokens are a consensus-service primitive |
| Partition behaviour | During a partition, would you rather refuse (CP: consistent, not available) or serve stale (AP: available, possibly stale)? | Refuse is correct for locks; serve stale is correct for flags and routing |
| Write rate and size | Writes per second and data size | Low: consensus stores favour small data. etcd's documented defaults are a 1.5 MiB request limit and 2 GiB storage quota, with 8 GiB as the suggested maximum |
| Read fan-out | How many readers, how often? | Consensus clusters handle modest read loads; massive fan-out (one write that a large number of readers must all learn about) belongs on caches or watch-driven local copies |
| Existing infrastructure | Do you already run a highly available database or a consensus cluster? | Reuse beats adding a system your team must operate |
Applying them to the three uses
| Use | Stale read consequence | Recommendation |
|---|---|---|
| Leader election | Two active leaders: duplicate jobs, conflicting writes | Consensus-backed (etcd lease plus election key, or ZooKeeper ephemeral sequential nodes), with fencing tokens passed downstream |
| Feature flags | A flag takes effect a few seconds later on some instances | Eventually consistent: store flags in the database of record, publish versioned snapshots, and have each service hold an in-memory copy refreshed by push or polling |
| Service discovery | A request goes to a dead instance and is retried | Eventually consistent is fine (health-checked registry, DNS, or the platform's own endpoint list), as long as clients retry and use timeouts |
Note that "eventually consistent" does not forbid using a consensus system underneath. Kubernetes endpoints (the list of pod IP addresses backing a Service) live in etcd, but consumers read them from watch caches and tolerate lag. The point is which guarantee the reader relies on.
When a database-backed lock is acceptable: if you already run a single-primary relational database that your services depend on anyway, a lease row updated with a conditional statement (UPDATE ... SET owner = me, token = token + 1, expires_at = ... WHERE expires_at < now()) gives mutual exclusion as long as the database itself does not split-brain during failover. With asynchronous replicas, a failover can lose the last lease update, so two owners are possible. Accept this when the database's failover is synchronous or when the protected job is idempotent; otherwise use a real consensus service.
Worked example: sizing the read load
An estate of 400 services with 5 instances each (2,000 instances), each needing 150 flags and a list of its dependencies.
- Polling the consensus cluster every 5 s for flags: 2,000 / 5 = 400 reads per second, each returning 150 flags. Manageable, but grows linearly with instances and polling frequency, and is wasted work since flags change perhaps a few times per hour.
- Watch plus local cache: 2,000 long-lived watch streams and near-zero steady-state reads; each flag change fans out once per watcher, so a change to one flag read by every instance produces 2,000 notifications. This is where a consensus cluster starts to hurt at scale: large simultaneous fan-out during a deploy or restart storm, when every instance also re-lists on reconnect.
- Snapshot publishing: the flag service writes a versioned JSON document (for example 150 flags x 200 bytes = 30 KB) to object storage or a CDN (content delivery network), and instances fetch it every 30 s: 2,000 / 30 = about 67 small GETs per second to infrastructure built for that, and the consensus cluster sees zero flag traffic.
The leader-election load is tiny in comparison: perhaps 50 elected roles renewing a lease every 3 s is about 17 writes per second, well within a 3-node etcd cluster.
Trade-offs and pitfalls
- Putting everything into the consensus store because it is there. It becomes a shared dependency whose outage takes down flags, discovery and elections at once, and it is the least horizontally scalable component you own.
- Believing a strongly consistent store gives correct leader election by itself. It does not stop a paused former leader from acting after its lease expires; downstream writes need fencing tokens or idempotency.
- Using eventual consistency for kill switches you rely on for safety. A flag that disables a dangerous code path in an incident should have a bounded propagation time (and monitoring of each instance's config version), even if it is not linearizable.
- Reading from followers without realizing it. Some stores serve serializable (possibly stale) reads from followers by default or on request: each client sees its own reads in a consistent order, but different clients' reads can reflect different points in time, unlike the linearizable guarantee defined above. An election recipe needs linearizable reads.
- What would flip the recommendation: a small estate (tens of instances) already running etcd or ZooKeeper can reasonably keep flags there too; the separation pays off when fan-out or blast radius (how much breaks when one component fails) becomes the dominant risk.
Unlock Full Question Bank
Get access to all 36 Consensus and Coordination Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.