Consensus, leader election and distributed locks
How a group of machines agrees on one order of events when some of them crash. Quorums, Raft leader election and log replication in a tested simulation, then leases and the fencing tokens that make a distributed lock safe.
ConceptCore35 min readUpdated
- 1 architecture diagram
- 2 sequence flows
- 7 code samples
- 9 interviewer follow-ups
- 4 self-checks
On this page13 sectionsHLDLLDSenior depth
Read first: Time, clocks and ordering
- State what consensus guarantees (agreement, validity, and progress only while a majority can talk) and why any two majorities overlap.
- Walk through Raft: terms, randomised election timeouts, the vote rule, log replication, the commit rule and the properties that keep committed entries safe.
- Size a consensus group (3 or 5 nodes, never 4) and say what it costs in latency and what it cannot do (scale the data path).
- Explain why a lock with a timeout is not safe on its own, and fix it with a fencing token checked by the resource.
7 code samples (449 lines), collapsed so the explanation stays in focus.
A single database server is easy to reason about and easy to lose. Add a backup and you have a new question: when the primary stops answering, who decides that it is dead, who takes over, and how do you stop the old one from carrying on as if nothing happened? Ask each node and you get a vote that depends on who can still talk to whom. Consensus is the family of protocols that answers the question safely: a group of machines agree on one value, or one ever-growing sequence of values, even though some of them crash and messages are lost, delayed or reordered.
The classic statement has three properties. Agreement: no two nodes decide differently. Validity: the decided value was proposed by someone. Termination: every working node eventually decides. A 1985 result by Fischer, Lynch and Paterson (FLP) showed that no deterministic protocol can guarantee all three in an asynchronous network if even one node may crash, because you cannot tell a crashed node from a slow one. Real protocols keep safety (agreement and validity) unconditionally and give up guaranteed liveness: they make progress whenever the network behaves well enough for a while, which in practice is nearly always. Raft uses randomised timeouts for exactly this.
The mechanism behind safety is the quorum. A quorum is a majority of the group. Any two majorities of the same group share at least one node, so a decision made by one majority is remembered by someone in every later majority. That overlapping node is what stops two sides of a partition from both deciding.
What consensus is used for:
| Use | What the group agrees on |
|---|---|
| Leader election | Which node is the primary for this period |
| Replicated state machine | The order of commands, so every replica ends in the same state |
| Configuration and metadata | Cluster membership, shard maps, schemas |
| Locks and leases | Who currently owns a resource |
| Sequencing | The next transaction or ID block |
Real systems built on it: etcd and Consul (Raft), ZooKeeper (ZAB, a similar protocol), Kafka's controller quorum (KRaft, replacing ZooKeeper; see logs, streams and Kafka), CockroachDB and TiKV (a Raft group for each range of keys), Spanner (a Paxos group for each split) and Google's Chubby lock service (Paxos). Paxos, Lamport's protocol from the late 1980s, came first and is notoriously hard to implement correctly. Raft (Ongaro and Ousterhout, 2014) is equivalent in power but designed to be understandable: one strong leader, and the problem split into election, replication and safety. Most new systems use Raft.
What it is not for: the bulk data path. Every write goes through one leader and waits for a majority, so a group does not get faster by adding nodes; it gets slower. Large systems keep the consensus group small and critical (metadata, leadership) and scale the data by running many small groups, one per shard.
A group of n nodes needs a majority, n/2 + 1 rounded down, to act. With n = 2f + 1 nodes it keeps working through f failures. Three nodes survive one failure, five survive two. Four nodes also survive only one (the majority of four is three), so the fourth node adds cost, more traffic and more chances to fail without adding any fault tolerance. Use an odd number.
How much does that buy? Suppose each node is up 99% of the time, independently of the others. The sample computes the chance that a majority is up.
C# · How available is a majority-quorum cluster if each node is up with probability `up`…
using System;
using System.Diagnostics;
// How available is a majority-quorum cluster if each node is up with probability `up`, independently of the others?
double Choose(int n, int k) { double r = 1; for (int i = 1; i <= k; i++) r = r * (n - k + i) / i; return r; }
double Available(int n, double up)
{
double total = 0;
for (int alive = n / 2 + 1; alive <= n; alive++) total += Choose(n, alive) * Math.Pow(up, alive) * Math.Pow(1 - up, n - alive);
return total;
}
double DowntimeMinutesPerYear(int n) => (1 - Available(n, 0.99)) * 365 * 24 * 60;
Debug.Assert(Math.Abs(Available(3, 0.99) - 0.999702) < 1e-9);
Debug.Assert(Available(4, 0.99) < Available(3, 0.99)); // a fourth node makes the cluster less available, not more
Debug.Assert(Available(5, 0.99) > 0.99998 && Available(7, 0.99) > Available(5, 0.99));
Debug.Assert(DowntimeMinutesPerYear(1) > 5_000 && DowntimeMinutesPerYear(1) < 5_300); // one node: about 3.6 days
Debug.Assert(DowntimeMinutesPerYear(3) > 150 && DowntimeMinutesPerYear(3) < 160); // three: about 2.6 hours
Debug.Assert(DowntimeMinutesPerYear(5) > 5 && DowntimeMinutesPerYear(5) < 5.5); // five: about 5 minutes| Nodes | Failures tolerated | Majority available | Downtime a year |
|---|---|---|---|
| 1 | 0 | 99.0000% | 3.6 days |
| 3 | 1 | 99.9702% | 2.6 hours |
| 4 | 1 | 99.9408% | 5.2 hours |
| 5 | 2 | 99.9990% | 5 minutes |
| 7 | 3 | 99.99997% | 11 seconds |
The table is optimistic, because it assumes independent failures. Nodes that share a rack, a power feed, a zone or a bad deployment fail together, which is why placement matters as much as the count. Spread a five-node group across three zones (2, 2 and 1) so that losing a zone still leaves a majority. A group in two regions cannot survive losing the region that holds the majority, so real designs use three. Multi-region design computes what a quorum across regions costs in latency.
Placement also sets latency. A write is acknowledged once the leader and enough followers have it, so it waits for the (f+1)-th fastest node: in a five-node group, the third. Nodes in nearby zones keep that to a few milliseconds; a group spread across continents pays the round trip to the nearest majority on every write.
Time in Raft is divided into terms, numbered 1, 2, 3 and so on. A term has at most one leader. Every node is a follower, a candidate or the leader, and every message carries the sender's term. Terms are Raft's clock: a node that sees a higher term than its own adopts it and, if it was a leader or candidate, steps down. A message from an older term is ignored.
The leader sends heartbeats (empty AppendEntries messages) to every follower. A follower that hears nothing for a random election timeout (the Raft paper suggests 150 to 300 ms inside a data center) becomes a candidate, increments its term, votes for itself and asks the others to vote.
A node grants a vote only if two things hold:
- It has not already voted in this term. One vote per term, remembered across a restart, is what makes two leaders in one term impossible: two different majorities would have to overlap in a node that voted twice.
- The candidate's log is at least as up to date as its own. The log is compared by the term of the last entry, then by length. This is the rule that protects committed data: an entry is committed only after a majority stores it, and any candidate that wins needs a majority of votes, so at least one voter holds every committed entry and will refuse a candidate that lacks it.
The timeouts are random on purpose. If two candidates start together, the votes split and nobody wins, but each retries after a different random delay, and one of them gets there first. In practice an election resolves in one or two rounds.
The leader receives client commands, appends each one to its log as an entry stamped with the current term, and replicates it. Every entry has an index; the log is the single agreed order of commands.
Each AppendEntries message names the entry that comes just before the new ones (its index and term). A follower accepts the new entries only if its own log has an entry with that index and term. If it does not, it refuses, and the leader steps back one entry at a time until it finds where the two logs agree, then sends everything after that point. A follower overwrites any of its own entries that conflict with the leader's. This one check gives the log matching property: if two logs have an entry with the same index and term, the logs are identical up to that entry.
An entry is committed once the leader knows a majority holds it. The leader then applies it to its state machine, tells the followers the commit index in later messages, and they apply it too. One subtlety: a leader commits by counting replicas only for entries from its own term; earlier entries become committed indirectly, when a later one does. A new leader therefore appends a no-op entry as soon as it is elected, so that earlier entries are committed promptly (the paper's Figure 8 shows how counting old-term entries can lose data).
Together the rules give five guarantees:
- Election safety: at most one leader is elected in a term.
- Leader append-only: a leader never overwrites or deletes its own entries.
- Log matching: the same index and term mean the same prefix.
- Leader completeness: an entry committed in a term is in the log of every leader of a later term.
- State machine safety: no two nodes apply different commands at the same index.
The implementation below is a faithful but small Raft: elections, replication, commit and apply, with the persistent state (term, vote, log) kept across a restart. It has no log compaction and no membership changes. Time is a number of milliseconds passed in by the caller, so a test controls it completely.
C# · Role, Entry, Message, …
using System;
using System.Collections.Generic;
using System.Linq;
public enum Role { Follower, Candidate, Leader }
public sealed record Entry(int Term, int Command);
public abstract record Message(int From, int To, int Term);
public sealed record RequestVote(int From, int To, int Term, int LastLogIndex, int LastLogTerm) : Message(From, To, Term);
public sealed record VoteReply(int From, int To, int Term, bool Granted) : Message(From, To, Term);
public sealed record AppendEntries(int From, int To, int Term, int PrevIndex, int PrevTerm, Entry[] Entries, int LeaderCommit) : Message(From, To, Term);
public sealed record AppendReply(int From, int To, int Term, bool Success, int MatchIndex) : Message(From, To, Term);
// One Raft server. Time is a number of milliseconds passed in by the caller, so a test controls it completely.
public sealed class RaftNode
{
public const int NoOp = -1;
private readonly int id, size;
private readonly Random random;
private readonly Action<Message> send;
private readonly Action<int, int> onLeader; // (node, term): this node has just won an election
private readonly Action<int, int, Entry> onApply; // (node, index, entry): this node applied a committed entry
// Persistent state: it survives a restart, because a vote or an entry that was promised must not be forgotten.
public int Term { get; private set; }
private int votedFor = -1;
public readonly List<Entry> Log = new List<Entry>(); // Log[0] holds index 1
// Volatile state: rebuilt after a restart.
public Role Role { get; private set; } = Role.Follower;
public int CommitIndex { get; private set; }
private int applied;
private int electionDeadline, heartbeatDeadline, votes;
private int[] nextIndex, matchIndex; // leaders only: what each follower has, and what to send next
public RaftNode(int id, int size, int seed, Action<Message> send, Action<int, int> onLeader, Action<int, int, Entry> onApply)
{
this.id = id; this.size = size; this.send = send; this.onLeader = onLeader; this.onApply = onApply;
random = new Random(seed);
ResetElectionTimer(0);
}
public int Id => id;
// A switch for the experiment that breaks a rule on purpose. A real node has no such thing.
public bool CheckLogBeforeVoting = true;
private int LastIndex => Log.Count;
private int TermAt(int index) => index == 0 ? 0 : Log[index - 1].Term;
private void ResetElectionTimer(int now) => electionDeadline = now + random.Next(150, 300); // randomised, so ties are rare
public IEnumerable<int> Applied => Log.Take(applied).Select(e => e.Command).Where(c => c != NoOp);
public void Tick(int now)
{
if (Role == Role.Leader)
{
if (now >= heartbeatDeadline) { BroadcastAppend(); heartbeatDeadline = now + 50; }
}
else if (now >= electionDeadline) StartElection(now);
Apply();
}
public bool Propose(int command)
{
if (Role != Role.Leader) return false;
Log.Add(new Entry(Term, command));
matchIndex[id] = LastIndex;
BroadcastAppend();
return true;
}
public void Restart(int now) { Role = Role.Follower; CommitIndex = 0; applied = 0; ResetElectionTimer(now); }
private void StartElection(int now)
{
Role = Role.Candidate;
Term++;
votedFor = id; // vote for yourself, once per term
votes = 1;
ResetElectionTimer(now);
for (int peer = 0; peer < size; peer++)
if (peer != id) send(new RequestVote(id, peer, Term, LastIndex, TermAt(LastIndex)));
}
public void Receive(Message message, int now)
{
if (message.Term > Term) { Term = message.Term; votedFor = -1; Role = Role.Follower; } // a newer term always wins
switch (message)
{
case RequestVote rv: OnRequestVote(rv, now); break;
case VoteReply vr: OnVoteReply(vr, now); break;
case AppendEntries ae: OnAppendEntries(ae, now); break;
case AppendReply ar: OnAppendReply(ar); break;
}
Apply();
}
private void OnRequestVote(RequestVote rv, int now)
{
// Only vote for a candidate whose log is at least as complete as ours, so a winner never lacks a committed entry.
bool upToDate = !CheckLogBeforeVoting || rv.LastLogTerm > TermAt(LastIndex) || (rv.LastLogTerm == TermAt(LastIndex) && rv.LastLogIndex >= LastIndex);
bool grant = rv.Term == Term && (votedFor == -1 || votedFor == rv.From) && upToDate;
if (grant) { votedFor = rv.From; ResetElectionTimer(now); }
send(new VoteReply(id, rv.From, Term, grant));
}
private void OnVoteReply(VoteReply vr, int now)
{
if (Role != Role.Candidate || vr.Term != Term || !vr.Granted) return;
if (++votes > size / 2) BecomeLeader(now);
}
private void BecomeLeader(int now)
{
Role = Role.Leader;
nextIndex = Enumerable.Repeat(LastIndex + 1, size).ToArray();
matchIndex = new int[size];
Log.Add(new Entry(Term, NoOp)); // an entry of the new term: committing it commits everything before it
matchIndex[id] = LastIndex;
onLeader(id, Term);
BroadcastAppend();
heartbeatDeadline = now + 50;
}
private void BroadcastAppend() { for (int peer = 0; peer < size; peer++) if (peer != id) SendAppend(peer); }
private void SendAppend(int peer)
{
int prev = nextIndex[peer] - 1;
send(new AppendEntries(id, peer, Term, prev, TermAt(prev), Log.Skip(prev).Take(20).ToArray(), CommitIndex));
}
private void OnAppendEntries(AppendEntries ae, int now)
{
if (ae.Term < Term) { send(new AppendReply(id, ae.From, Term, false, 0)); return; } // a leader from the past
Role = Role.Follower; // there is one leader per term, and this is it
ResetElectionTimer(now);
if (ae.PrevIndex > LastIndex || TermAt(ae.PrevIndex) != ae.PrevTerm)
{
send(new AppendReply(id, ae.From, Term, false, 0)); // our logs disagree before these entries
return;
}
int index = ae.PrevIndex;
foreach (var entry in ae.Entries)
{
index++;
if (index <= LastIndex && Log[index - 1].Term != entry.Term) Log.RemoveRange(index - 1, Log.Count - (index - 1)); // drop a conflicting suffix
if (index > LastIndex) Log.Add(entry);
}
if (ae.LeaderCommit > CommitIndex) CommitIndex = Math.Min(ae.LeaderCommit, ae.PrevIndex + ae.Entries.Length);
send(new AppendReply(id, ae.From, Term, true, ae.PrevIndex + ae.Entries.Length));
}
private void OnAppendReply(AppendReply ar)
{
if (Role != Role.Leader || ar.Term != Term) return;
if (ar.Success)
{
matchIndex[ar.From] = Math.Max(matchIndex[ar.From], ar.MatchIndex);
nextIndex[ar.From] = matchIndex[ar.From] + 1;
AdvanceCommit();
}
else
{
nextIndex[ar.From] = Math.Max(1, nextIndex[ar.From] - 1); // step back until the logs agree
SendAppend(ar.From);
}
}
// An entry is committed once a majority holds it, and only entries of the leader's own term are counted this way.
private void AdvanceCommit()
{
for (int n = LastIndex; n > CommitIndex; n--)
if (Log[n - 1].Term == Term && matchIndex.Count(m => m >= n) > size / 2) { CommitIndex = n; break; }
}
private void Apply()
{
while (applied < CommitIndex) { applied++; onApply(id, applied, Log[applied - 1]); }
}
}The Cluster is the world around the nodes: a network that delivers each message after 1 to 20 ms and can drop it, nodes that can crash and restart, and partitions that split the group. It also checks the guarantees as the run goes, not only at the end: two leaders in a term, a new leader missing a committed entry, and two nodes applying different entries at one index. At the end of a run it checks that no two logs break the matching property.
C# · A simulated network and a set of nodes, with the properties Raft promises checked as the…
using System;
using System.Collections.Generic;
using System.Linq;
// A simulated network and a set of nodes, with the properties Raft promises checked as the run goes.
public sealed class Cluster
{
public readonly RaftNode[] Nodes;
public readonly List<string> Problems = new List<string>();
public readonly Dictionary<int, int> LeaderOfTerm = new Dictionary<int, int>(); // term -> the one node that won it
public readonly Dictionary<int, Entry> Committed = new Dictionary<int, Entry>(); // index -> the entry every node must agree on
public double DropRate;
public int Now { get; private set; }
private readonly Random random;
private readonly PriorityQueue<Message, (int Due, long Order)> wire = new PriorityQueue<Message, (int Due, long Order)>();
private readonly bool[] down;
private readonly int[] island; // nodes in different islands cannot talk
private long order;
public Cluster(int size, int seed)
{
random = new Random(seed);
down = new bool[size];
island = new int[size];
Nodes = Enumerable.Range(0, size).Select(i => new RaftNode(i, size, seed * 100 + i, Enqueue, OnLeader, OnApply)).ToArray();
}
private void Enqueue(Message m)
{
if (down[m.From] || island[m.From] != island[m.To] || random.NextDouble() < DropRate) return; // lost on the way
wire.Enqueue(m, (Now + random.Next(1, 21), order++)); // 1 to 20 ms in flight
}
public void Step()
{
Now++;
while (wire.TryPeek(out var m, out var due) && due.Due <= Now)
{
wire.Dequeue();
if (!down[m.To] && island[m.From] == island[m.To]) Nodes[m.To].Receive(m, Now);
}
for (int i = 0; i < Nodes.Length; i++) if (!down[i]) Nodes[i].Tick(Now);
}
public void RunFor(int ms) { for (int i = 0; i < ms; i++) Step(); }
// Election safety: two nodes must never both win the same term. Leader completeness: a new leader holds every committed entry.
private void OnLeader(int node, int term)
{
if (LeaderOfTerm.TryGetValue(term, out int other) && other != node) Problems.Add($"term {term} has two leaders: {other} and {node}");
LeaderOfTerm[term] = node;
foreach (var committed in Committed)
if (Nodes[node].Log.Count < committed.Key || Nodes[node].Log[committed.Key - 1] != committed.Value)
Problems.Add($"leader {node} of term {term} is missing committed entry {committed.Key}");
}
// State machine safety: every node that applies index i applies the same entry.
private void OnApply(int node, int index, Entry entry)
{
if (!Committed.TryGetValue(index, out var known)) Committed[index] = entry;
else if (known != entry) Problems.Add($"node {node} applied {entry} at index {index}, but {known} was committed there");
}
// Log matching: if two logs hold an entry with the same index and term, they are identical up to that index.
public void CheckLogMatching()
{
for (int a = 0; a < Nodes.Length; a++)
for (int b = a + 1; b < Nodes.Length; b++)
{
int common = Math.Min(Nodes[a].Log.Count, Nodes[b].Log.Count);
int last = Enumerable.Range(1, common).LastOrDefault(i => Nodes[a].Log[i - 1].Term == Nodes[b].Log[i - 1].Term);
for (int i = 1; i <= last; i++)
if (Nodes[a].Log[i - 1] != Nodes[b].Log[i - 1]) { Problems.Add($"logs of {a} and {b} differ at {i} but agree at {last}"); break; }
}
}
public RaftNode Leader() => Nodes.Where((n, i) => !down[i] && n.Role == Role.Leader).OrderByDescending(n => n.Term).FirstOrDefault();
public bool Propose(int command) => Leader()?.Propose(command) ?? false;
public bool IsDown(int node) => down[node];
public int DownCount => down.Count(d => d);
public void Crash(int node) => down[node] = true;
public void Restart(int node) { down[node] = false; Nodes[node].Restart(Now); }
public void Isolate(params int[] group) { Array.Clear(island); foreach (int n in group) island[n] = 1; }
public void Heal() => Array.Clear(island);
}First four scenarios, then a random run.
C# · 1. A healthy cluster elects one leader and commits every proposal on every node.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 1. A healthy cluster elects one leader and commits every proposal on every node.
var healthy = new Cluster(5, seed: 1);
healthy.RunFor(1_000);
Debug.Assert(healthy.Leader() != null);
for (int command = 1; command <= 50; command++) { healthy.Propose(command); healthy.RunFor(10); }
healthy.RunFor(500);
Debug.Assert(healthy.Nodes.All(n => n.Applied.SequenceEqual(Enumerable.Range(1, 50))));
Debug.Assert(healthy.Problems.Count == 0);
// 2. The leader crashes. Another node takes over within a second, nothing committed is lost, and the old leader catches up.
var failover = new Cluster(5, seed: 2);
failover.RunFor(1_000);
for (int command = 1; command <= 20; command++) { failover.Propose(command); failover.RunFor(10); }
failover.RunFor(200);
var firstLeader = failover.Leader();
int firstTerm = firstLeader.Term;
failover.Crash(firstLeader.Id);
int crashedAt = failover.Now;
while (failover.Leader() == null && failover.Now < crashedAt + 3_000) failover.Step();
int electionMs = failover.Now - crashedAt;
Debug.Assert(failover.Leader() != null && failover.Leader().Id != firstLeader.Id && failover.Leader().Term > firstTerm);
Debug.Assert(electionMs < 1_000);
for (int command = 21; command <= 40; command++) { failover.Propose(command); failover.RunFor(10); }
failover.Restart(firstLeader.Id);
failover.RunFor(1_000);
Debug.Assert(failover.Nodes.All(n => n.Applied.SequenceEqual(Enumerable.Range(1, 40))));
Debug.Assert(failover.Problems.Count == 0);
// 3. The leader is cut off with one other node. The three on the other side elect a leader; the old leader cannot commit.
var split = new Cluster(5, seed: 3);
split.RunFor(1_000);
var oldLeader = split.Leader();
split.Isolate(oldLeader.Id, (oldLeader.Id + 1) % 5);
Debug.Assert(oldLeader.Propose(1001)); // it does not know yet, so it accepts the command
split.RunFor(1_500);
var newLeader = split.Leader();
Debug.Assert(newLeader.Id != oldLeader.Id && newLeader.Term > oldLeader.Term);
Debug.Assert(!oldLeader.Applied.Contains(1001)); // only two of five nodes hold it: it can never commit
for (int command = 1; command <= 10; command++) { split.Propose(command); split.RunFor(10); }
split.Heal();
split.RunFor(2_000);
Debug.Assert(split.Nodes.All(n => !n.Applied.Contains(1001))); // the uncommitted entry was overwritten everywhere
Debug.Assert(split.Nodes.All(n => n.Applied.SequenceEqual(Enumerable.Range(1, 10))));
split.CheckLogMatching();
Debug.Assert(split.Problems.Count == 0);
// 5. How long does a leader crash leave the cluster without a leader? Measured over 100 different random schedules.
var gaps = new List<int>();
for (int seed = 1; seed <= 100; seed++)
{
var probe = new Cluster(5, seed);
probe.RunFor(1_000);
probe.Crash(probe.Leader().Id);
int from = probe.Now;
while (probe.Leader() == null && probe.Now < from + 5_000) probe.Step();
gaps.Add(probe.Now - from);
}
gaps.Sort();
Debug.Assert(gaps[50] < 400 && gaps[99] < 1_500);What the scenarios show: a healthy five-node cluster elects a leader within a second and commits 50 proposals on every node. When the leader crashes, another is elected within about 200 ms and the old leader, once restarted, catches up from the new one. Across 100 different random schedules the cluster spent a median of 198 ms without a leader after a crash, 425 ms at the 95th percentile and 458 ms at worst, which is what the 150 to 300 ms timeout range predicts. In the partition test the old leader took a command it could never commit, because only two of five nodes had it. The three-node side elected a new leader with a higher term and carried on, and when the partition healed the old leader's uncommitted entry was overwritten on every node, while everything committed was kept.
Now the chaos test: for six simulated seconds nodes crash and restart, the network splits and heals, and 10% of messages are lost, while a client keeps sending commands. It is run for 100 seeds. Then the same test is run with one rule removed, to show that the rules are doing work.
C# · 4. Random chaos: crashes, restarts, partitions and 10% message loss. Count the runs in…
using System;
using System.Diagnostics;
using System.Linq;
// 4. Random chaos: crashes, restarts, partitions and 10% message loss. Count the runs in which something went wrong.
Cluster RunChaos(int seed, Action<RaftNode> breakRule)
{
var cluster = new Cluster(5, seed) { DropRate = 0.1 };
foreach (var node in cluster.Nodes) breakRule(node);
var chaos = new Random(seed * 7919);
int next = 1;
for (int t = 0; t < 6_000; t++)
{
if (t % 25 == 0) cluster.Propose(next++); // a client keeps sending commands
if (t % 300 == 0)
switch (chaos.Next(4))
{
case 0: if (cluster.DownCount < 2) cluster.Crash(chaos.Next(5)); break;
case 1: for (int n = 0; n < 5; n++) if (cluster.IsDown(n)) { cluster.Restart(n); break; } break;
case 2: cluster.Isolate(Enumerable.Range(0, chaos.Next(1, 3)).Select(_ => chaos.Next(5)).Distinct().ToArray()); break;
default: cluster.Heal(); break;
}
cluster.Step();
}
cluster.Heal(); // everything recovers...
cluster.DropRate = 0;
for (int n = 0; n < 5; n++) if (cluster.IsDown(n)) cluster.Restart(n);
cluster.RunFor(3_000);
cluster.Propose(next++);
cluster.RunFor(1_000);
cluster.CheckLogMatching();
return cluster;
}
bool WentWrong(Cluster c) => c.Problems.Count > 0 || c.Leader() == null || c.Nodes.Select(n => string.Join(",", n.Applied)).Distinct().Count() != 1;
int correct = 0, withoutLogCheck = 0, terms = 0, committed = 0;
for (int seed = 1; seed <= 100; seed++)
{
var honest = RunChaos(seed, n => { });
if (WentWrong(honest)) correct++;
terms += honest.LeaderOfTerm.Count;
committed += honest.Committed.Count;
if (WentWrong(RunChaos(seed, n => n.CheckLogBeforeVoting = false))) withoutLogCheck++;
}
Debug.Assert(correct == 0); // the real rules never break safety
Debug.Assert(withoutLogCheck > 20); // and the rule matters: drop the log check and runs go wrongIn the 100 chaos runs of real Raft the checker found nothing, across 476 elections and 19,962 committed entries. With the log check removed from the vote rule, 65 of the 100 runs broke: new leaders without committed entries and nodes applying different commands at the same index. In every one of those runs the nodes ended in the same state once everything healed, so a test that only compared final states would have passed. Checking the guarantees as the run goes is what caught it. That is true of any concurrent system: a bug that corrupts data and later "heals" is still a bug.
Reads. Serving a read from the leader's state is not automatically linearizable: a leader cut off from the group may not know it has been replaced, and would return stale data. There are three fixes. Send the read through the log, which is correct and slow. Use ReadIndex: the leader notes its commit index, confirms with a round of heartbeats that a majority still follows it, and answers once it has applied that index. Or use leader leases: the leader may answer alone while a lease granted by the followers is valid, which is fast but depends on bounded clock drift (see time, clocks and ordering). Reads from a follower are cheap and may be stale unless the follower first asks the leader for its read index. etcd serves linearizable reads by default and offers a stale "serializable" read as an option.
Membership. Changing the set of nodes is dangerous, because two sets of nodes can each form a majority of their own configuration. Raft changes membership one server at a time (the thesis version) or through a joint configuration that needs both majorities (the paper version). Use your implementation's own add and remove operations, one at a time, and wait for each to finish.
Snapshots. The log cannot grow forever. Each node periodically snapshots its state machine and discards the log before that point. A follower that is far behind receives the snapshot instead of millions of entries.
Speed. A write costs one local disk flush on the leader, one network round trip to the nearest majority, and a flush on those followers (the storage engines lesson explains why the flush is the expensive part). Leaders batch several commands into one message and pipeline messages to followers. Throughput is bounded by the leader's disk and network, so a bigger group does not help.
Timeouts. The election timeout must be comfortably larger than the heartbeat interval, the network round-trip time and the worst disk stall, or the group elects leaders it does not need. etcd's defaults are a 100 ms heartbeat and a 1,000 ms election timeout, and its tuning guide recommends an election timeout of at least ten round trips. Across regions, raise both.
Two safety features worth knowing by name: Pre-Vote, where a node asks whether it would win before incrementing its term, so a partitioned node does not force the group to a higher term when it returns; and CheckQuorum, where a leader steps down if it cannot reach a majority, so a cut-off leader stops serving stale reads.
A lease is a grant that expires: "you are the leader until 12:00:30". A distributed lock with a time limit is a lease. The hazard is the one from the clocks lesson. The holder checks that it holds the lock, is paused (a garbage collection, a virtual machine freeze) for longer than the lease, and wakes up to write, while the lock service has already given the lock to someone else.
The fix does not live in the lock. It lives in the resource being protected. Every time the lock service grants the lock it also returns a fencing token, a number that is larger than any it has issued before. The client sends the token with each write, and the storage system remembers the highest token it has seen and rejects any lower one.
C# · A lock service with leases. Every successful acquire returns a fencing token larger than…
using System;
// A lock service with leases. Every successful acquire returns a fencing token larger than any before it.
public sealed class LockService
{
private long lastToken;
private string holder;
private long expiresAt;
public long? TryAcquire(string client, long now, long leaseMs)
{
if (holder != null && holder != client && now < expiresAt) return null; // someone else holds an unexpired lease
holder = client;
expiresAt = now + leaseMs;
return ++lastToken;
}
}
// The protected resource. With checking on, it refuses a write whose token is older than one it has already seen.
public sealed class FencedStore
{
private long highestToken;
public string Value { get; private set; } = "";
public bool Write(long token, string value, bool checkToken)
{
if (checkToken && token < highestToken) return false;
highestToken = Math.Max(highestToken, token);
Value = value;
return true;
}
}C# · Client A takes the lock, then freezes (a garbage-collection pause) for longer than its…
using System;
using System.Diagnostics;
// Client A takes the lock, then freezes (a garbage-collection pause) for longer than its lease.
var lockService = new LockService();
var unfenced = new FencedStore();
var fenced = new FencedStore();
long tokenA = lockService.TryAcquire("A", now: 0, leaseMs: 10_000).Value;
Debug.Assert(lockService.TryAcquire("B", 5_000, 10_000) == null); // B is refused while A's lease is valid
long tokenB = lockService.TryAcquire("B", 11_000, 10_000).Value; // A's lease ran out, so B gets the next token
Debug.Assert(tokenB > tokenA);
unfenced.Write(tokenB, "written by B", checkToken: false);
fenced.Write(tokenB, "written by B", checkToken: true);
// A wakes up at 15,000. It still believes it holds the lock, because nothing told it otherwise.
bool acceptedWithoutFencing = unfenced.Write(tokenA, "written by A, too late", checkToken: false);
bool acceptedWithFencing = fenced.Write(tokenA, "written by A, too late", checkToken: true);
Debug.Assert(acceptedWithoutFencing && unfenced.Value == "written by A, too late"); // B's data is overwritten by a stale holder
Debug.Assert(!acceptedWithFencing && fenced.Value == "written by B"); // the store refuses itThe stale holder's late write corrupted the unprotected store and was refused by the fenced one. Where does the token come from? From the consensus system: ZooKeeper's transaction id or a node's version number, etcd's revision, Chubby's sequencer. All of them increase with every change the group agrees on.
Redis locks. A single Redis instance with SET key value NX PX ttl is a fine way to avoid duplicate work: if the lock is wrong now and then, the cost is a repeated job. It is not a correctness tool, because it has no fencing token and relies on timing. The Redlock algorithm, which takes the lock on five independent Redis instances, was criticised by Martin Kleppmann in 2016 for exactly that (it depends on bounded clock drift and pauses, and gives no token), and its author replied in defence. The practical resolution is the one above: for efficiency, a simple lock is enough; for correctness, use a lock service backed by consensus and check a fencing token at the resource.
Often the better design has no lock at all. If the resource supports a conditional write (a version number, an If-Match header, a unique constraint), that conditional write is the fence: a stale writer's update simply fails. See the patterns in transactions and isolation levels.
| Situation | What happens | Defence |
|---|---|---|
| A leader is partitioned from the group | It keeps believing it leads and may serve stale reads | Terms and majority commit keep writes safe; CheckQuorum and ReadIndex keep reads safe |
| Elections happen again and again | Latency spikes while there is no leader | Election timeout above round trip and disk stalls; Pre-Vote; fix the slow disk or the pauses |
| The leader's disk is slow | Every write stalls and heartbeats are late, so elections start | Fast local disks, alert on flush latency, transfer leadership away |
| Two of three nodes are lost | The group stops accepting writes, by design | Restore a node; practise recovery from a snapshot; never restart two at once |
| A group of two or four | No more fault tolerance than one node fewer | Use three or five |
| Membership changed carelessly | Two disjoint majorities can both elect a leader | One change at a time through the supported operation |
| The nodes fail together | The whole quorum goes at once (one zone, one bad release) | Spread across zones; roll upgrades one node at a time |
| A lease relies on skewed clocks | Two nodes both believe they hold it | Bound the drift, leave margin, check a fencing token |
| A timeout lock guards a correctness property | A paused client writes after losing the lock | Fencing token or a conditional write at the resource |
Interviewer follow-upL5What problem does consensus solve, and why not just use a primary and a backup?How to answer
A backup cannot tell whether the primary is dead or only unreachable. If it takes over while the primary is still serving, there are two primaries (split brain) and data diverges. Consensus makes the takeover a decision that a majority has to agree on, so only one node can be the leader at a time, and anything it accepted as committed is guaranteed to be known to whoever leads next.
Interviewer follow-upL5Why does a group need a majority, and why three or five nodes rather than four?How to answer
Any two majorities overlap in at least one node, so two sides of a partition cannot both decide, and a later decision always meets a node that remembers the earlier one. With n = 2f + 1 nodes the group tolerates f failures. Four nodes need three for a majority and tolerate only one failure, the same as three, while costing more and adding another node that can fail. Five tolerate two.
Interviewer follow-upL6Walk through what Raft does when the leader crashes.How to answer
Followers stop receiving heartbeats. The first follower whose random election timeout fires becomes a candidate, increments the term, votes for itself and requests votes. Followers vote at most once per term and only for a candidate whose log is at least as up to date as theirs. With a majority it becomes leader, appends a no-op entry for its term and starts sending heartbeats, which stop other elections and replicate its log. Followers whose logs disagree are repaired by stepping back to the last matching entry. In the simulation this took a median of about 200 ms.
Interviewer follow-upL6How does Raft keep a new leader from losing committed entries?How to answer
Two rules together. An entry is committed only when a majority holds it. A candidate needs votes from a majority, so at least one voter holds every committed entry, and voters refuse any candidate whose log is less up to date, so a candidate without a committed entry cannot win. In addition a leader commits entries from earlier terms only indirectly, by committing a current-term entry (hence the no-op), which avoids a case where counting old entries could be overwritten later. Removing the up-to-date check made 65 of 100 simulated runs lose or contradict committed entries.
Interviewer follow-upL6Your distributed lock sometimes lets two workers in at once. Why, and how do you fix it?How to answer
The lock is a lease, so it expires; a worker that was paused (garbage collection, a stalled virtual machine, a slow network call) can resume after expiry and carry on believing it holds the lock. Checking the lock before each step does not help, because it can pause after the check. The fix is a fencing token issued with each grant and verified by the protected resource, which rejects stale tokens. Or avoid the lock and use a conditional write. A single Redis lock is acceptable only where a duplicate run is harmless.
Interviewer follow-upL6What is split brain and how does a consensus protocol prevent it?How to answer
Two parts of a system each believe they are the primary and accept writes, so the data diverges. Consensus prevents it by requiring a majority for every decision: a leader that cannot reach a majority cannot commit anything, and terms let a node recognise and step down when a newer leader exists. The remaining danger is reads from a stale leader, which ReadIndex, leader leases with bounded drift or CheckQuorum address.
Interviewer follow-upL7How do you serve linearizable reads in a Raft-based store, and what does it cost?How to answer
Options are to put each read through the log (one full replication round), to use ReadIndex (the leader records its commit index and confirms leadership with a heartbeat round, then answers after applying it), or to use leader leases (the leader answers locally while its lease is valid, which saves the round trip but needs a bound on clock drift). Follower reads can be made linearizable by asking the leader for the read index first. State the trade-off: latency of a round trip versus reliance on clocks versus staleness.
Interviewer follow-upL7Design leader election for a service with a hundred instances using etcd or ZooKeeper.How to answer
Each instance creates an ephemeral key bound to a session with a lease, and the lowest creation revision (or the lowest sequence number, in ZooKeeper) is the leader. Each other instance watches only the key just ahead of it, not all of them, so one change wakes one instance and not a hundred. If the leader's session expires it loses leadership. Because it may not know that yet (a pause), every write the leader makes to shared state carries the key's revision as a fencing token and the resource rejects older ones. Keep the leader's work idempotent for when leadership flaps.
Interviewer follow-upL7When would you not use consensus, and how do large systems scale it?How to answer
Not on the bulk data path, and not where eventual consistency is enough: it costs a majority round trip per write, limits throughput to one leader and gives up availability on the minority side of a partition. Use it for the small, critical state (leadership, membership, shard maps, locks). Large systems partition the data and run an independent small group per partition (CockroachDB, TiKV and Spanner do), so the number of groups grows with the data while each group stays small and fast. Where conflicts are rare and merging is possible, CRDTs or leaderless replication avoid it.
When a design needs a coordinator (one leader, one lock holder, one agreed configuration), say that it is a consensus problem and name the tool: "a three or five node etcd or ZooKeeper group for leader election and configuration, never on the data path." Then say how the failure cases are covered: a majority so a partition cannot produce two leaders, fencing tokens so a paused holder cannot corrupt data, timeouts tuned above network and disk latency, and three zones so losing one still leaves a quorum.
Consensus lets a group agree on one sequence of decisions through crashes and lost messages. Safety rests on quorums: any two majorities overlap, so a later decision always meets a node that remembers an earlier one. Progress needs a majority to be reachable, and it is guaranteed only while the network behaves, which is why timeouts are randomised. Raft splits the problem into leader election (terms, one vote per term, the log up-to-date rule), log replication (a consistency check on every message, commit on a majority and the no-op for a new term) and five safety properties that the simulation checks under crashes, partitions and message loss. Groups should be three or five nodes spread across zones, hold only small critical state and scale by sharding into many groups. Locks with timeouts are leases and are unsafe on their own: the resource must reject stale holders with a fencing token, or a conditional write.
Try answering out loud before you reveal each answer.
QuestionA cluster has five nodes and two crash. Can it still commit writes? What if a third crashes?Reveal answer
Yes after two: three nodes are a majority of five, so the leader (or a new one) can still get the acknowledgements it needs. After a third crash only two nodes are left, which is not a majority, so nothing can be committed. The cluster stops accepting writes rather than risk two sides deciding differently, and resumes when a node returns.
QuestionWhy must a Raft node refuse to vote for a candidate whose log is shorter or older than its own?Reveal answer
An entry is committed only after a majority stores it. A candidate needs votes from a majority, so at least one voter has every committed entry. If voters ignored the log, a candidate that lacks a committed entry could win and overwrite it. In the simulation, removing this check made 65 of 100 runs produce leaders missing committed entries.
QuestionA client holding a lock with a 30-second lease is paused for 40 seconds and then writes to the database. How do you stop the write from corrupting data?Reveal answer
Have the lock service issue a fencing token with every grant and have the database remember the highest token it has accepted. The paused client's token is older than the one issued to the new holder, so the database rejects the write. A check of the lock before writing is not enough, because the client can pause after the check.
QuestionWhat can go wrong if a leader answers reads from its own state without confirming it is still the leader?Reveal answer
If a partition cut it off and a new leader was elected, it does not know it has been replaced and returns stale data, so the reads are not linearizable. Fix it with ReadIndex (confirm with a majority before answering), with a leader lease that depends on bounded clock drift, or by sending reads through the log.
- Diego Ongaro and John Ousterhout, In Search of an Understandable Consensus Algorithm (opens in a new tab) (USENIX ATC 2014), the Raft paper, and the Raft site (opens in a new tab), with a visualisation, the implementation list and Ongaro's thesis.
- Leslie Lamport, Paxos Made Simple (opens in a new tab) (2001).
- Michael Fischer, Nancy Lynch and Michael Paterson, Impossibility of Distributed Consensus with One Faulty Process (opens in a new tab) (JACM, 1985): the FLP result.
- Mike Burrows, The Chubby lock service for loosely-coupled distributed systems (opens in a new tab) (OSDI 2006), and Patrick Hunt et al., ZooKeeper: Wait-free coordination for Internet-scale systems (opens in a new tab) (USENIX ATC 2010).
- Martin Kleppmann, How to do distributed locking (opens in a new tab), and Salvatore Sanfilippo, Is Redlock safe? (opens in a new tab): the Redlock exchange, including fencing tokens.
- etcd documentation, Tuning (opens in a new tab): heartbeat interval, election timeout and disk latency.
- Kyle Kingsbury, Jepsen: etcd 3.4.3 (opens in a new tab): how a Raft-based system was tested for safety under faults.
- Martin Kleppmann, Designing Data-Intensive Applications (opens in a new tab), the chapters on the trouble with distributed systems and on consistency and consensus.