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.
A scheduled job running across many service instances must always have exactly one active leader, in a data-center environment prone to network partitions. How would you implement this, and how would you handle split-brain and safe failover?
Sample Answer
Direct answer
"Always exactly one active leader" cannot be guaranteed in a network that can partition: a leader cut off from everyone cannot be told it has been replaced, and there will be moments with zero leaders during failover. So I restate the requirement as two properties and design for both: safety, meaning at most one instance's work ever takes effect, and liveness, meaning if a majority of the coordination service and at least one healthy instance can talk, a leader is eventually running. I would implement it with a lease-based election on a consensus-backed store (etcd or ZooKeeper: a small cluster that replicates every write to a majority), plus fencing tokens checked by whatever the job writes to, plus an idempotency key per job run as the last line of defence.
Safety and liveness, stated precisely
- Safety (nothing bad happens): for every run of the job, the side effects of at most one leader are accepted. Note the wording: not "at most one process believes it is leader". A frozen process may believe that; what matters is that its writes are refused.
- Liveness (something good eventually happens): if the coordination service's majority and some instance are reachable to each other for longer than the lease TTL plus election time, a leader is elected and the job runs.
Safety must hold under all partitions and pauses; liveness is allowed to wait out a partition. That is the correct priority for a job whose duplicate run causes damage (double billing, double emails).
Design
sequenceDiagram
participant A as Instance A
participant K as etcd (3 or 5 nodes)
participant D as Downstream DB
A->>K: grant lease TTL 10s, create /leader/billing (if absent)
K-->>A: ok, revision 33 (fencing token)
loop every 3s
A->>K: keepalive
end
A->>D: write run 2026-09-27 with token 33
D-->>A: accepted (33 >= max seen)
- Coordination cluster: 3 voters across 3 failure domains (racks or zones), or 5 if you must survive two failures. It is CP: a side of a partition without a majority refuses writes, so it can never grant the leader key to two instances.
- Election: each instance creates a lease with TTL (time-to-live) 10 s, then tries to create
/leader/billingbound to the lease using a transaction "create only if the key does not exist". The winner gets the key's creation revision, a cluster-wide increasing number, as its fencing token. Losers watch the key and retry when it is deleted. - Holding leadership: the leader renews (keeps alive) every 3 s. It keeps a local deadline:
last successful renewal + TTL - safety marginon its own monotonic clock. With TTL 10 s and margin 3 s, it stops doing leader work 7 s after its last acknowledged renewal, even if it has heard nothing to the contrary. - Fencing downstream: every write the job makes carries the token. The downstream store keeps the highest token it has seen for this job and rejects smaller ones (a conditional update,
WHERE last_token <= :token). - Idempotency: each run has a natural key, for example
billing:2026-09-27, stored with a unique constraint. A second attempt at the same run is a no-op even if fencing is somehow bypassed or a new leader retries a half-finished run.
Handling split brain: the paused-leader case
Split brain means two instances acting as leader at the same time. With the design above it can arise in exactly one way: the old leader is paused (garbage collection pause, VM freeze, or partition) past its lease, a new leader is elected, and the old one wakes up and acts before checking its deadline. Leases alone cannot stop that, because the old process was not running to see its lease expire. The fencing token makes the downstream store refuse it. This simulation replays that timeline with and without the token check:
class LockService:
"""Lease-based lock. Every grant gets a strictly larger token."""
def __init__(self):
self.token = 32
self.holder = None
self.expires_at = 0.0
def acquire(self, who, now, ttl):
if self.holder is None or now >= self.expires_at:
self.token += 1
self.holder, self.expires_at = who, now + ttl
return self.token
return None
class Storage:
"""The resource the job writes to. It remembers the highest token seen."""
def __init__(self, check_fencing):
self.check_fencing = check_fencing
self.max_token = 0
self.writes = []
def write(self, who, token, value):
if self.check_fencing and token < self.max_token:
return f"REJECTED {who} (token {token} < {self.max_token})"
self.max_token = max(self.max_token, token)
self.writes.append((who, value))
return f"ok {who} token={token}"
def run(check_fencing):
lock, db = LockService(), Storage(check_fencing)
t_a = lock.acquire("A", now=0.0, ttl=10.0) # A becomes leader
print(" t=0 A acquires, token", t_a)
# A stalls (GC pause / partition) from t=1 to t=25; lease ends at t=10
t_b = lock.acquire("B", now=12.0, ttl=10.0) # B takes over
print(" t=12 B acquires, token", t_b)
print(" t=13 ", db.write("B", t_b, "run-2026-09-27"))
print(" t=25 ", db.write("A", t_a, "run-2026-09-27")) # A wakes, still thinks it leads
print(" duplicate runs recorded:", len(db.writes))
print("without fencing check:"); run(False)
print("with fencing check:"); run(True)
Output (from running the file above unchanged):
without fencing check:
t=0 A acquires, token 33
t=12 B acquires, token 34
t=13 ok B token=34
t=25 ok A token=33
duplicate runs recorded: 2
with fencing check:
t=0 A acquires, token 33
t=12 B acquires, token 34
t=13 ok B token=34
t=25 REJECTED A (token 33 < 34)
duplicate runs recorded: 1
Without the check the run happens twice; with it, the stale leader's write is refused at the resource. This only works if the resource checks tokens. For side effects that cannot (sending an email, calling a third-party API), rely on the idempotency key held in a store that does check, and write "intent recorded with token" before performing the external call.
Safe failover timeline
| Time | Event |
|---|---|
| t = 0 s | Leader A's last successful renewal |
| t = 7 s | A's local deadline passes: A stops starting new work and aborts in-flight work at the next checkpoint |
| t = 10 s | etcd's lease expires (measured by the etcd leader), key deleted |
| about t = 10.1 s | Watchers notified; instance B wins, token 34 |
| t = 10 to 11 s | B resumes the run; its writes carry token 34 |
Worst-case leaderless gap is about TTL plus election, so about 10 to 11 s. Shorter TTLs speed failover but increase false failovers from brief network blips; for a scheduled job, 10 s of gap is usually irrelevant, while a false failover costs a duplicate-run attempt that fencing must catch.
If the etcd leader itself fails, etcd elects a new one (its documented defaults are a 100 ms heartbeat and 1000 ms election timeout), and outstanding leases are not expired by the change of etcd leader. If the job's leader is on the minority side of a partition, its renewals fail, its local deadline fires, and it stops: exactly the desired behaviour.
What if there is no consensus service?
A single-primary relational database can host the lease row instead: UPDATE leases SET owner = :me, token = token + 1, expires_at = now() + interval '10 seconds' WHERE job = 'billing' AND (expires_at < now() OR owner = :me) RETURNING token. This is safe only while the database has one writable primary; an asynchronous-replica failover can lose the last grant and hand out the same token twice. With synchronous replication, or with a job that is idempotent anyway, it is a reasonable choice that adds no new infrastructure.
Trade-offs and pitfalls
- Checking
am I leader?once and then working for an hour. Leadership must be re-validated at checkpoints and every write fenced. - Using wall-clock time for the local deadline. Use a monotonic clock; wall clocks jump with NTP (Network Time Protocol) corrections.
- Assuming two nodes are enough. A 2-node coordination cluster needs both nodes for a majority, so it tolerates zero failures.
- Heartbeat-only leader election between the job instances themselves (no quorum: no requirement that a majority of members agree before anyone acts, the property this whole design has relied on throughout) cannot tell "the leader is dead" from "I am partitioned" and is where most real split brains come from.
Design a follower-reads optimization for a strongly-consistent key-value system that allows slightly stale reads from followers while guaranteeing clients can request fresher data when needed. Describe API semantics, staleness bounds, and how you would ensure monotonic reads and session guarantees.
Sample Answer
Direct answer
Let clients choose the freshness they need per read, and make every follower able to prove how fresh it is before it answers. The API offers three modes: linearizable (as fresh as a leader read), bounded staleness (no older than a stated interval), and at least this version (a session token). Followers track a closed timestamp (a time the leader has promised no new write will ever be committed at or below) and their applied log index; a follower serves a read only if that evidence satisfies the request, otherwise it waits briefly or redirects. Monotonic reads and read-your-writes come from a session token the client carries: the highest log index it has written or observed.
Background in plain terms
In a strongly consistent key-value store built on Raft or Paxos (consensus algorithms that commit each write once a majority of replicas has stored it), one leader orders all writes into a log and followers apply the log a little later. Reading from the leader is always fresh but concentrates load and, across regions, adds latency. Reading from a follower is cheap and local but might miss the last few writes. The design problem is to make follower reads safe by construction: the system, not luck, decides whether a follower is fresh enough.
API semantics
Get(key, consistency)
consistency =
LINEARIZABLE -- reflects every write acknowledged before the call
BOUNDED_STALENESS(max_age) -- reflects every write committed at or before now - max_age
AT_LEAST(session_token) -- reflects every write up to the index in the token
Response: value, served_index, served_by, freshness_timestamp, new_session_token
Put(key, value) -> commit_index, new_session_token
- Default is LINEARIZABLE, so nobody gets stale data by accident.
- Every response returns the index it reflects, so clients and debugging tools can see exactly how fresh an answer was.
- A request that cannot be satisfied locally within a small wait budget is forwarded to the leader, never answered stale.
Real systems expose the same menu: CockroachDB has exact-staleness reads (reading as of one specific past timestamp you name, rather than "as fresh as possible" or "within some window"; follower_read_timestamp()) and bounded-staleness reads (with_max_staleness(...), with_min_timestamp(...)); Consul has stale, default and consistent read modes and returns X-Consul-LastContact so a client can see how long ago the answering server heard from the leader.
How each mode is served from a follower
Linearizable follower reads (ReadIndex)
ReadIndex is Raft's technique for letting a follower serve a linearizable read without itself becoming leader: it asks the current leader for the leader's latest commit index, confirms that leader is genuinely still in charge, then simply waits until its own state has caught up to that index before answering.
sequenceDiagram
participant C as Client
participant F as Follower
participant L as Leader
C->>F: Get(k, LINEARIZABLE)
F->>L: What is your commit index?
L->>L: Confirm leadership with a majority heartbeat
L-->>F: commit index 1042
F->>F: Wait until applied index is at least 1042
F-->>C: value at index 1042
Here, commit index is how far the leader has confirmed a majority of replicas have durably stored the log, while applied index is how far this particular follower has actually executed those log entries into its own copy of the data, which can lag the commit index slightly. A read is only safe to answer once the follower's applied index has caught up to the commit index the leader just reported, which is exactly what the wait step checks. The follower pays one round trip to the leader (small message, no data), but the data read and its bandwidth stay local. Confirming leadership matters because the process answering "what is your commit index" might already have been replaced: the heartbeat check makes it confirm, via a fresh exchange with a majority of the cluster's members, that it is still recognised as leader right now, and Raft guarantees only one leader can win a majority in a given term. A leader that has actually been deposed cannot pass that check, so it cannot hand out a commit index at all, rather than handing out a stale one.
Bounded staleness
The leader periodically publishes a closed timestamp T with the log index where it takes effect. A follower that has applied up to that index can serve any read at a time at or below T. It serves BOUNDED_STALENESS(max_age) if
where epsilon is the maximum clock uncertainty between nodes. Worked example: the leader closes timestamps about 3 s behind real time, clock uncertainty is 250 ms, and a client asks for data at most 10 s old. A follower whose closed timestamp is 3.2 s behind satisfies 3.2 + 0.25 = 3.45 s, which is within 10 s, so it answers locally. A follower cut off from the leader for 12 s has a closed timestamp at least 12 s behind; it must redirect. The staleness bound is only as good as the clock-uncertainty bound, so the system must track clock offset and refuse bounded reads on a node whose clock is out of tolerance.
Session guarantees
A session is one client's sequence of operations. Two guarantees matter:
- Monotonic reads: once you have seen version N, you never later see anything older.
- Read-your-writes: after your write commits at index N, your reads reflect it.
Both reduce to one rule: the client carries a token equal to the highest index it has written or read, and every read is AT_LEAST(token). This simulation shows the failure without the token and the fix with it:
class Replica:
def __init__(self, name):
self.name, self.applied, self.data = name, 0, {}
def apply(self, index, key, value):
self.data[key], self.applied = value, index
class Client:
'''Carries a session token: the highest log index it has written or read.'''
def __init__(self):
self.token = 0
def read(self, replica, key, use_token=True):
need = self.token if use_token else 0
if replica.applied < need:
return f"{replica.name} applied={replica.applied} < token={need}: wait or redirect"
self.token = max(self.token, replica.applied)
return f"{replica.name} applied={replica.applied} -> {key}={replica.data.get(key)}"
log = [(1, "bal", 100), (2, "bal", 80), (3, "bal", 50)]
fast, slow = Replica("f1"), Replica("f2")
for i, k, v in log:
fast.apply(i, k, v)
for i, k, v in log[:1]:
slow.apply(i, k, v) # f2 is two entries behind
for label, use_token in [("without session token", False), ("with session token", True)]:
c = Client()
print(label)
print(" read 1:", c.read(fast, "bal", use_token))
print(" read 2:", c.read(slow, "bal", use_token))
Output:
without session token
read 1: f1 applied=3 -> bal=50
read 2: f2 applied=1 -> bal=100
with session token
read 1: f1 applied=3 -> bal=50
read 2: f2 applied=1 < token=3: wait or redirect
Without the token, a load balancer that sends the second read to a lagging follower makes the balance jump from 50 back to 100. With it, the lagging follower knows it is not allowed to answer.
Practical details for the token:
- Return it in every response and accept it on every request; store it in the client library, or in a cookie for browser sessions that span servers.
- Because a Raft log index of a committed entry never changes meaning across leader changes, the index alone is a valid token; include the term too (the number that increases every time a new leader is elected) if you want to detect a client talking to a cluster that was restored from backup.
- The wait budget is short (tens of milliseconds); after that, redirect to the leader rather than queue indefinitely.
Staleness bounds you can promise
- Bounded staleness: bounded by max_age, provided clocks are within epsilon. Without clock bounds, only index-based guarantees are safe.
- Session reads: no wall-clock bound at all; the guarantee is ordering relative to what the client has seen.
- Unbounded "any replica" reads should not be offered on this system, or only behind an explicit name like
STALE_OKfor diagnostics.
Trade-offs and pitfalls
- Serving follower reads for authorisation decisions (can this user withdraw?) reintroduces the anomalies consensus was bought to prevent; keep those on LINEARIZABLE.
- Closed timestamps lagging under write load push bounded reads to the leader exactly when it is busiest; alert on closed-timestamp lag and size max_age against it.
- Forgetting the token on retries or across devices silently drops the guarantee; make the client library carry it automatically.
- Using a wall-clock timestamp as the session token breaks under clock skew; use the log index.
Compare using an external consensus system (e.g., etcd or Consul) vs building a lightweight custom leader-coordinator for configuration propagation and leader election for a control-plane service. Evaluate reliability, operational burden, latency, complexity, and development cost.
Sample Answer
Direct answer
Use an external consensus system, and prefer one you already run: on Kubernetes, the built-in Lease objects (a small Kubernetes API resource that one process can hold and periodically renew, giving the cluster a native way to say "exactly one owner, until it stops renewing") for leader election; otherwise etcd or Consul. A "lightweight custom coordinator" is either a single process (a single point of failure) or, once you make it highly available, a consensus implementation you now own, which is the hardest kind of code to get right and the hardest to test. The only case where custom wins is when you can build it on top of a strongly consistent store you already operate (a database row with a lease and a compare-and-set, an atomic "update this row only if it still holds the value I expect" operation), which is custom glue, not custom consensus.
What the control plane actually needs
A control-plane service (the part of a platform that decides configuration and assignments, as opposed to the data plane that serves traffic) typically needs:
- Leader election: exactly one active instance makes decisions, and a replacement takes over when it dies.
- Configuration propagation: every worker learns the current config version quickly and in order, and can resume after a disconnect without missing a change.
- Fencing: a deposed leader that wakes up late (after a garbage-collection pause or a network stall) must not be able to apply stale decisions.
etcd and Consul provide the primitives: leases or sessions (grants that expire unless renewed), atomic compare-and-set transactions, watches (etcd's push notifications: subscribe to a key and get told the instant it changes) or blocking queries (Consul's version of the same idea: an HTTP request that just hangs open until the watched key changes or a timeout elapses), and a monotonically increasing revision (etcd's cluster-wide counter, which goes up by one on every write anywhere in the store; each key remembers the revision at which it was last changed) or index that doubles as a fencing token.
Evaluation
| Criterion | External (etcd / Consul / Kubernetes Lease) | Lightweight custom coordinator |
|---|---|---|
| Reliability | Raft-replicated across 3 or 5 members; tolerates 1 or 2 failures; years of production and published failure testing | A single coordinator is a single point of failure. Heartbeat-and-timeout failover produces two leaders the first time the network is slow rather than dead (split brain) |
| Correctness under partitions | Minority side cannot grant leadership; revisions give a fencing token for free | Must be designed and tested by you; usually the gap is discovered in production |
| Operational burden | A stateful cluster to run: backups, upgrades one member at a time, disk latency monitoring, quota management (enforcing and tracking etcd's storage-size limit so the cluster does not silently start rejecting writes). Near zero if you reuse Kubernetes' own Lease API or a managed offering | A new service to run, plus its own on-call knowledge that only the authors have |
| Latency | Leader election failover of roughly one to two seconds with etcd defaults (1000 ms election timeout); config changes reach watchers after one majority commit plus a notification hop | Can be lower in the happy path (no quorum wait), which is exactly what makes it unsafe |
| Complexity | Complexity lives in a well-understood client library (etcd's election API, Consul's lock helpers, the leader-election package in client-go, the official Kubernetes Go client library) | Complexity lives in your code: timeouts, retries, fencing, reconnection, catch-up after missed updates |
| Development cost | Days to integrate; most cost is in fencing downstream writes and in runbooks | Weeks to a first version, then an open-ended tail of edge cases and testing (fault injection: deliberately killing processes, dropping packets, or pausing nodes in a test to see how the system reacts; clock-skew scenarios: testing what happens when two nodes' clocks disagree) |
Two product details matter for the design:
- Consul sessions are tied to node health checks as well as an optional TTL (time-to-live: an expiry that renewals push back), and by default apply a lock-delay of 15 seconds after a session is invalidated, during which the lock cannot be re-acquired. That protects against a just-deposed holder still acting, at the cost of a longer failover. Tune it deliberately.
- etcd limits: requests default to at most 1.5 MiB and the storage quota defaults to 2 GiB. Config propagation is fine; shipping large artifacts through etcd is not (store them elsewhere and propagate a pointer and a hash).
Worked example: config propagation with watches
A control plane publishes routing config to 2,000 workers.
- The leader writes
config/routingwith a new version. etcd commits it at, say, revision 90412. - Each worker holds a watch on
config/from the last revision it applied. The change arrives as one event per worker: 2,000 small notifications, fanned out by etcd members, not by the leader service. - A worker that was disconnected reconnects with "watch from revision 90390" and receives every change it missed, in order, as long as that revision has not been compacted away (etcd periodically discards, or "compacts," old revision history to bound its own storage, so a watch trying to resume from a revision older than the compaction point can no longer be honoured). If it has, the worker does a full read of
config/and resumes watching from the returned revision.
The custom equivalent needs its own versioning, per-worker cursors, replay buffer and "you are too far behind, do a full resync" path: each is a place for a lost-update bug.
Fencing: the part neither option does for you
Leader election decides who should act; it cannot stop an old leader who does not know it has been replaced. So:
- The leader reads the revision of its election key (etcd) or the lock index (Consul) when it wins, and attaches it as a fencing token to every write it makes.
- Downstream systems store the highest token seen and reject writes with a lower one. In etcd you can go further and make every control-plane write a transaction conditioned on the leader key still existing with that revision.
When custom is reasonable
- Built on an existing strongly consistent store. A table row
(role, holder, lease_expires_at, token)updated with a conditional write ("only if the row is expired or already mine", incrementing the token) in Postgres or DynamoDB gives correct leader election without running new infrastructure. You still owe fencing downstream and careful clock handling (use the database's clock, not each client's). - Truly single-instance by design, where an operator restarts it and minutes of unavailability are acceptable: then you do not need election at all, just a health check and a runbook.
What would flip the recommendation toward building more: extreme scale of coordination state (millions of keys, high write rates) where etcd's size and single-leader limits do not fit. Even then the answer is usually a sharded consensus database, not a hand-written protocol.
Trade-offs and pitfalls
- Reusing Kubernetes' etcd directly for application data: use the Lease API, not raw keys, so you do not load the cluster's own control store.
- Election without fencing: two active leaders for the length of a pause, with either option.
- Treating watch delivery as exactly-once: handlers must be idempotent (applying the same config version twice is harmless) and must handle compaction.
- Underestimating the "lightweight" option's test burden: its correctness can only be shown with partition, pause and clock-skew testing, which usually costs more than running etcd.
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 replicas, explain how read quorum size R and write quorum size W interact to provide strong consistency. Provide the general condition and walk through a concrete example for N=5: list at least two (R, W) pairs that guarantee linearizability and show why the intersection property holds.
Sample Answer
Short answer
With N replicas, a write is sent to at least W of them and a read asks at least R of them. If
R+W>Nthen every read quorum must share at least one replica with every write quorum, so a read always reaches at least one replica that holds the latest completed write. For N = 5, pairs such as (R, W) = (3, 3) and (2, 4) satisfy this. Overlap is the necessary condition; turning it into full linearizability (every read returns the most recent completed write, as if there were one copy) also needs version numbers on values, a read that picks the highest version and writes it back to a quorum before returning, and, with more than one writer, write quorums that overlap each other as well.
Why the overlap holds
A quorum is simply "enough replicas that any two such groups must overlap". The argument is the pigeonhole principle: a read set A of size R and a write set B of size W are both chosen from only N replicas, so if their sizes add up to more than N they cannot be disjoint.
∣A∣+∣B∣>N⟹A∩B=∅The shared replica has seen the write, so the reader sees it too, as long as it can tell which of the values it received is newest. That is why each value carries a version (a timestamp or counter) and the reader takes the highest.
A second condition matters when several clients can write the same key. Two write quorums must overlap each other, otherwise two concurrent writes can land on disjoint replica sets and nobody can order them:
2W>NWorked example: N = 5
Here is a brute-force check over every possible subset of 5 replicas, confirming both formulas and listing every pair that satisfies read/write overlap.
from itertools import combinations
N = 5
nodes = range(N)
def always_intersect(a, b):
"""True if EVERY a-sized subset of nodes shares a node with EVERY b-sized subset."""
return all(set(x) & set(y) for x in combinations(nodes, a) for y in combinations(nodes, b))
print(" R W read-write overlap write-write overlap")
for R in range(1, N + 1):
for W in range(1, N + 1):
rw, ww = always_intersect(R, W), always_intersect(W, W)
assert rw == (R + W > N) and ww == (2 * W > N) # brute force agrees with the formulas
if rw:
print(f"{R:2} {W:2} {str(rw):18} {ww}")
# Why R + W = N is not enough: a write quorum and a read quorum that miss each other.
write_quorum, read_quorum = {0, 1, 2}, {3, 4} # W = 3, R = 2, R + W = 5 = N
print("R=2, W=3 overlap:", write_quorum & read_quorum or "none")
Output:
R W read-write overlap write-write overlap
1 5 True True
2 4 True True
2 5 True True
3 3 True True
3 4 True True
3 5 True True
4 2 True False
4 3 True True
4 4 True True
4 5 True True
5 1 True False
5 2 True False
5 3 True True
5 4 True True
5 5 True True
R=2, W=3 overlap: none
Three pairs worth discussing, all satisfying both overlap conditions:
| (R, W) | Read cost | Write cost | Replicas that can be down |
|---|---|---|---|
| (3, 3) | 3 replies | 3 acks | 2 for reads, 2 for writes. The balanced default. |
| (2, 4) | 2 replies | 4 acks | 3 for reads, only 1 for writes. Read-heavy workloads. |
| (1, 5) | 1 reply | all 5 acks | Reads survive 4 failures, but one dead replica blocks every write. |
Walk-through for (3, 3), using the same five replicas {0, 1, 2, 3, 4} as the code above: a write to key balance with version 7 is acknowledged by replicas {0, 1, 2}. A later read contacts {2, 3, 4}. Replicas 3 and 4 still hold version 6, replica 2 returns version 7. The reader picks 7 because it is highest. Any three-replica read must include at least one of {0, 1, 2}, because only two replicas (3 and 4) are outside the write set.
The pairs (4, 2), (5, 1) and (5, 2) give read/write overlap but not write/write overlap, so they only suit a design with a single writer per key (for example, a leader that serializes writes). The last line of the output shows the failure case: with R = 2 and W = 3, R + W equals N, and the read {3, 4} can miss the write {0, 1, 2} entirely.
From "sees the latest write" to linearizable
Overlap alone gives "a read after a completed write sees it". Linearizability is stricter, and two gaps remain:
- Writes in progress. Suppose a write of version 8 has reached only replica 1 when reader X queries {1, 4, 5} and returns 8, and then reader Y queries {3, 4, 5} and returns 7. Y started after X finished yet saw an older value, which violates linearizability. The fix (from the ABD algorithm, named after Attiya, Bar-Noy and Dolev, a classic quorum-based register protocol) is a read write-back: before returning version 8, X writes it to a quorum, so any later read is guaranteed to see it.
- Ordering concurrent writes. Each writer first reads the current highest version from a quorum and writes version + 1 tagged with its ID for tie-breaking. This is safe because of the write-write overlap condition above (
2W > N): any two write quorums share at least one replica, so a writer computing "current highest version" always reads a quorum that includes someone who saw every prior write, and two writers racing to use the same version number cannot both complete without a shared replica noticing the collision.
Pitfalls
- Sloppy quorums break the guarantee. Some Dynamo-style stores (leaderless, quorum-based key-value stores modeled on Amazon's Dynamo design, for example Cassandra or Riak) use a sloppy quorum: when a home replica is down, the coordinator accepts the write on a stand-in node outside the key's proper N replicas instead of blocking, and later moves that data to its rightful home once it recovers, a process called hinted handoff. The arithmetic R + W > N then no longer implies overlap, because the write quorum was not drawn from the same N.
- Counting acks from replicas that did not persist. An ack must mean the write is durable on that replica, otherwise a crash-restart silently removes it from the quorum.
- Choosing (1, N) for "fast reads" looks attractive until one replica is down and every write stalls.
- Last-writer-wins by wall-clock timestamp as the version can silently drop a write when clocks disagree; prefer logical versions (a counter or vector clock that orders writes by cause and effect, rather than relying on wall-clock time that can disagree across machines).
Unlock Full Question Bank
Get access to all 16 Consensus and Coordination Algorithms interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.