Quorums, Raft and leader leases, step by step
Lab: count why majorities always overlap, then drive a deterministic Python teaching model of Raft through an election, log replication, a network partition with a stale leader, a lagging node that cannot win, leader-lease reads, and a lock lease that expires during a pause, with and without fencing tokens.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Why majorities
- Step 2: Elect a leader and replicate two writes
- Step 3: Predict, then split the network
- Step 4: A node with a stale log cannot win
- Step 5: Lock leases and fencing tokens
- Check your understanding
- Apply it
- Review prompt
Lessons of Distributed Systems Fundamentals
- Partial failure and the fallacies of distributed computing Concept · 20 min
- Time, clocks and ordering Concept · 20 min
- Consistency models from linearizable to eventual Concept · 25 min
- CAP and PACELC applied to real databases Worked example · 20 min
- Quorums, Raft and leader leases, step by step Lab · 25 min
- Distributed reasoning check Knowledge check · 8 questions
What you will learn
- Explain conceptually how quorums and consensus (for example Raft) provide leader election and replicated state, and when to rely on a coordination service with leases and fencing tokens.
01. Goal and setup
Lesson 4 showed etcd refusing linearizable reads on a member cut off from its peers. This lab shows the mechanism: any two majorities of a cluster share a member, and Raft turns that fact into a single leader per term and committed writes that survive failures. You will also see why a lease, a promise that expires after a time, needs extra help before it protects anything.
raft_model.py is a teaching model, not a Raft implementation. It follows the election and replication rules in Figure 2 of the Raft paper, plus a vote rule and a lease from the Raft thesis (Step 3), and simulates time and the network in one seeded process, so every run prints the same lines. It leaves out disk persistence, crashes, snapshots, membership changes and client retries; Consensus and distributed transactions goes further.
You need: Python 3.10 or newer and no packages. The outputs below come from Python 3.12.13, and Python 3.10.12 printed identical output.
raft-lab/
├── quorum.py step 1: which read and write sets overlap
├── raft_model.py steps 2-4: elections, replication, partitions, leases
└── fencing.py step 5: an expiring lock lease, with and without fencingmkdir raft-lab && cd raft-lab
python3 --versionPython 3.12.1302. Step 1: Why majorities
Save quorum.py and run it. It lists every possible write set of W nodes and read set of R nodes in a five-node cluster and counts the pairs that share no node. Before running, predict the count for W = 3, R = 3.
"""Which read sets and write sets must share a node? Count them all."""
from itertools import combinations
NODES = ["n1", "n2", "n3", "n4", "n5"]
def disjoint_pairs(w: int, r: int) -> tuple[int, int]:
writes, reads = combinations(NODES, w), list(combinations(NODES, r))
pairs = [(set(a), set(b)) for a in writes for b in reads]
return sum(1 for a, b in pairs if not a & b), len(pairs)
print("N=5: pairs of (write set, read set) that share no node")
for w, r in [(3, 3), (4, 2), (5, 1), (2, 3), (2, 2), (1, 1)]:
bad, total = disjoint_pairs(w, r)
rule = ">" if w + r > len(NODES) else "<="
print(f" W={w} R={r} W+R={w + r} {rule} 5: {bad:3} of {total:3} share no node")N=5: pairs of (write set, read set) that share no node
W=3 R=3 W+R=6 > 5: 0 of 100 share no node
W=4 R=2 W+R=6 > 5: 0 of 50 share no node
W=5 R=1 W+R=6 > 5: 0 of 5 share no node
W=2 R=3 W+R=5 <= 5: 10 of 100 share no node
W=2 R=2 W+R=4 <= 5: 30 of 100 share no node
W=1 R=1 W+R=2 <= 5: 20 of 25 share no nodeWhenever W + R is larger than N, every read set shares a node with every write set. Leaderless stores use this as R + W > N; Multi-leader and leaderless quorums lists what that rule alone does not guarantee.
Raft uses two majorities, 3 and 3 out of 5. Each node votes at most once per term, so two candidates cannot both collect three votes in one term: they would need a shared voter who voted twice. And an entry stored on a majority is present on at least one member of any majority that elects a future leader. Those two overlaps carry the rest of the lab.
03. Step 2: Elect a leader and replicate two writes
Save raft_model.py. Read the three groups of methods: elections (timeout, request_vote, vote_reply), replication (heartbeat, append_entries, append_reply) and the operator actions at the end. Then run the normal scenario.
"""A small Raft teaching model: elections, log replication, partitions, leases.
Deterministic: simulated milliseconds, one seeded random generator, no threads.
Left out on purpose: disk persistence and crashes, snapshots, membership
changes, client retries and pre-vote. See the Raft paper, Figure 2.
Usage: python3 raft_model.py normal|partition|stale [seed]
"""
import heapq
import random
import sys
NODES = ["n1", "n2", "n3", "n4", "n5"]
MAJORITY = len(NODES) // 2 + 1 # 3 of 5
DELAY = 5 # one-way message delay, ms
HEARTBEAT = 50 # leader sends AppendEntries every 50 ms
ELECTION = (150, 300) # random election timeout range, ms
DRIFT = 1.1 # assumed bound on clock-rate difference
class Node:
def __init__(self, name):
self.name, self.term, self.voted_for = name, 0, None
self.role, self.log, self.commit = "follower", [], 0
self.timer = 0 # generation of the election timer
self.heard_leader = -10_000 # last time a current leader spoke
self.votes, self.next, self.match = set(), {}, {}
self.acks, self.lease_until = {}, -1
def last(self):
return (self.log[-1][0] if self.log else 0), len(self.log)
class Sim:
def __init__(self, seed):
self.rng, self.now, self.queue, self.seq = random.Random(seed), 0, [], 0
self.nodes = {n: Node(n) for n in NODES}
self.down = set() # blocked links, as frozensets
for node in self.nodes.values():
self.reset_timer(node)
def at(self, t, fn, *args):
self.seq += 1
heapq.heappush(self.queue, (t, self.seq, fn, args))
def run(self, until):
while self.queue and self.queue[0][0] <= until:
self.now, _, fn, args = heapq.heappop(self.queue)
fn(*args)
self.now = until
def say(self, text):
print(f"t={self.now:4} ms {text}")
def send(self, src, dst, kind, **msg):
if frozenset((src, dst)) not in self.down:
self.at(self.now + DELAY, getattr(self, kind), self.nodes[dst], src, msg)
def reset_timer(self, node):
node.timer += 1
wait = self.rng.randint(*ELECTION)
self.at(self.now + wait, self.timeout, node, node.timer)
def step_down(self, node, term):
if node.role == "leader":
self.say(f"{node.name} sees term {term} and steps down to follower")
if term > node.term: # a new term: no vote cast in it yet
node.term, node.voted_for = term, None
node.role = "follower"
# ---- elections (paper section 5.2 and 5.4.1) ----
def timeout(self, node, timer):
if timer != node.timer or node.role == "leader":
return
node.term += 1
node.role, node.voted_for, node.votes = "candidate", node.name, {node.name}
self.say(f"{node.name} times out, becomes candidate for term {node.term}")
self.reset_timer(node)
last_term, last_index = node.last()
for peer in NODES:
if peer != node.name:
self.send(node.name, peer, "request_vote", term=node.term,
last_term=last_term, last_index=last_index)
def request_vote(self, node, src, m):
if self.now - node.heard_leader < ELECTION[0]:
return # a leader spoke recently: ignore
if m["term"] > node.term:
self.step_down(node, m["term"])
up_to_date = (m["last_term"], m["last_index"]) >= node.last()
grant = (m["term"] == node.term and node.voted_for in (None, src)
and up_to_date)
if grant:
node.voted_for = src
self.reset_timer(node)
elif m["term"] == node.term and not up_to_date:
t, i = node.last()
self.say(f"{node.name} refuses {src}: own log (last term {t}, "
f"index {i}) is more up to date")
self.send(node.name, src, "vote_reply", term=node.term, granted=grant)
def vote_reply(self, node, src, m):
if m["term"] > node.term:
self.step_down(node, m["term"])
if node.role != "candidate" or m["term"] != node.term or not m["granted"]:
return
node.votes.add(src)
if len(node.votes) >= MAJORITY:
node.role = "leader"
node.next = {p: len(node.log) + 1 for p in NODES}
node.match = {p: 0 for p in NODES}
node.match[node.name] = len(node.log)
self.say(f"{node.name} wins term {node.term} with votes from "
f"{sorted(node.votes)}")
self.heartbeat(node, node.term)
# ---- log replication (paper section 5.3) ----
def heartbeat(self, node, term):
if node.role != "leader" or node.term != term:
return
self.broadcast(node)
self.at(self.now + HEARTBEAT, self.heartbeat, node, term)
def broadcast(self, node):
node.acks[self.now] = {node.name}
for peer in NODES:
if peer != node.name:
self.append_to(node, peer)
def append_to(self, node, peer):
prev = node.next[peer] - 1
prev_term = node.log[prev - 1][0] if prev else 0
self.send(node.name, peer, "append_entries", term=node.term,
prev=prev, prev_term=prev_term, entries=node.log[prev:],
commit=node.commit, sent=self.now)
def append_entries(self, node, src, m):
if m["term"] < node.term:
self.send(node.name, src, "append_reply", term=node.term, ok=False,
match=0, sent=m["sent"])
return
if m["term"] > node.term or node.role != "follower":
self.step_down(node, m["term"])
node.heard_leader = self.now
self.reset_timer(node)
prev = m["prev"]
if prev > len(node.log) or (prev and node.log[prev - 1][0] != m["prev_term"]):
self.say(f"{node.name} rejects entries after index {prev}: "
f"no entry from term {m['prev_term']} there")
self.send(node.name, src, "append_reply", term=node.term, ok=False,
match=0, sent=m["sent"])
return
for i, entry in enumerate(m["entries"], start=prev + 1):
if i <= len(node.log) and node.log[i - 1][0] != entry[0]:
gone = [cmd for _, cmd in node.log[i - 1:]]
self.say(f"{node.name} deletes uncommitted {gone} from index {i}")
del node.log[i - 1:]
if i > len(node.log):
node.log.append(entry)
node.commit = max(node.commit, min(m["commit"], prev + len(m["entries"])))
self.send(node.name, src, "append_reply", term=node.term, ok=True,
match=prev + len(m["entries"]), sent=m["sent"])
def append_reply(self, node, src, m):
if m["term"] > node.term:
self.step_down(node, m["term"])
return
if node.role != "leader" or m["term"] != node.term:
return
if not m["ok"]:
node.next[src] = max(1, node.next[src] - 1)
self.say(f"{node.name} retries {src} from index {node.next[src]}")
self.append_to(node, src)
return
node.match[src] = max(node.match[src], m["match"])
node.next[src] = node.match[src] + 1
acked = node.acks.setdefault(m["sent"], {node.name})
acked.add(src)
if len(acked) >= MAJORITY: # lease: see the Raft thesis, 6.4.1
node.lease_until = max(node.lease_until,
m["sent"] + int(ELECTION[0] / DRIFT))
for n in range(len(node.log), node.commit, -1):
stored = sum(1 for p in NODES if node.match[p] >= n)
if node.log[n - 1][0] == node.term and stored >= MAJORITY:
done = [cmd for _, cmd in node.log[node.commit:n]]
self.say(f"{node.name} commits {done} ({stored}/5 stored)")
node.commit = n
break
# ---- what clients and operators do ----
def write(self, name, cmd):
node = self.nodes[name]
if node.role != "leader":
self.say(f"{name} is not leader, refuses {cmd}")
return
node.log.append((node.term, cmd))
node.match[name] = len(node.log)
self.say(f"{name} appends {cmd} at index {len(node.log)}, term {node.term}")
self.broadcast(node)
def lease_read(self, name):
node = self.nodes[name]
if node.role == "leader" and self.now < node.lease_until:
self.say(f"{name} serves a lease read (lease ends at "
f"t={node.lease_until})")
else:
self.say(f"{name} refuses a lease read (lease ended at "
f"t={node.lease_until})")
def local_read(self, name):
node = self.nodes[name]
done = [cmd for _, cmd in node.log[:node.commit]]
self.say(f"{name} ({node.role}, term {node.term}) reads its own copy: "
f"{done[-1] if done else 'nothing'}")
def cut(self, side):
self.down = {frozenset((a, b)) for a in side for b in NODES
if b not in side}
rest = [n for n in NODES if n not in side]
self.say(f"network splits {sorted(side)} | {rest}")
def heal(self):
self.down = set()
self.say("network heals")
def leader(self):
live = [n for n in self.nodes.values() if n.role == "leader"]
return max(live, key=lambda n: n.term).name
def show_logs(self):
for n in self.nodes.values():
entries = " ".join(f"{t}:{cmd}" for t, cmd in n.log)
print(f" {n.name} term={n.term} {n.role:9} commit={n.commit} "
f"log=[{entries}]")
def normal(sim):
sim.run(400)
lead = sim.leader()
sim.at(410, sim.write, lead, "x=1")
sim.at(420, sim.write, lead, "x=2")
sim.run(600)
sim.show_logs()
def partition(sim):
sim.run(400)
old = sim.leader()
sim.at(410, sim.write, old, "x=1")
sim.run(500)
buddy = next(n for n in NODES if n != old)
sim.cut([old, buddy])
sim.at(510, sim.write, old, "x=9")
for t in (560, 640):
sim.at(t, sim.lease_read, old)
sim.run(900)
new = sim.leader() if sim.leader() != old else None
if new:
sim.write(new, "x=5")
sim.at(950, sim.local_read, old)
sim.at(950, sim.local_read, new)
sim.run(1000)
sim.heal()
sim.run(1200)
sim.show_logs()
def stale(sim):
sim.run(400)
lead = sim.leader()
lagger = next(n for n in reversed(NODES) if n != lead)
sim.cut([lagger])
sim.at(410, sim.write, lead, "x=1")
sim.at(420, sim.write, lead, "x=2")
sim.run(500)
sim.cut([lead]) # old leader gone, lagger back
sim.run(1100)
sim.show_logs()
if __name__ == "__main__":
scenario = sys.argv[1] if len(sys.argv) > 1 else "normal"
seed = int(sys.argv[2]) if len(sys.argv) > 2 else 4
{"normal": normal, "partition": partition, "stale": stale}[scenario](Sim(seed))python3 raft_model.py normalt= 176 ms n3 times out, becomes candidate for term 1
t= 186 ms n3 wins term 1 with votes from ['n1', 'n2', 'n3']
t= 410 ms n3 appends x=1 at index 1, term 1
t= 420 ms n3 appends x=2 at index 2, term 1
t= 420 ms n3 commits ['x=1'] (3/5 stored)
t= 430 ms n3 commits ['x=2'] (3/5 stored)
n1 term=1 follower commit=2 log=[1:x=1 1:x=2]
n2 term=1 follower commit=2 log=[1:x=1 1:x=2]
n3 term=1 leader commit=2 log=[1:x=1 1:x=2]
n4 term=1 follower commit=2 log=[1:x=1 1:x=2]
n5 term=1 follower commit=2 log=[1:x=1 1:x=2]Raft divides time into numbered terms. Every node starts as a follower with an election timer drawn at random between 150 and 300 ms, the range the paper suggests. n3 timed out first, moved to term 1, voted for itself and asked the others; votes from n1 and n2 made three of five, so it led 10 ms later, before anyone else timed out. Random timers make such a clean win the common case.
The leader appends each client write to its log and sends it in AppendEntries messages, which also serve as heartbeats. When three of five logs hold an entry, the leader marks it committed, and later messages tell the followers. The commit loop only counts replicas for entries from the leader's own term; Section 5.4.2 of the paper shows why counting older entries can be unsafe.
04. Step 3: Predict, then split the network
The partition scenario elects a leader and commits x=1. At 500 ms it cuts the leader and one follower off from the other three. The old leader then receives x=9, and the new side receives x=5. At 1,000 ms the network heals. The old leader also tries two lease reads, explained below. Write down your predictions first:
- Will
x=9ever be committed? - Which side elects a leader, and in which term?
- What happens to
x=9after the network heals?
python3 raft_model.py partitiont= 176 ms n3 times out, becomes candidate for term 1
t= 186 ms n3 wins term 1 with votes from ['n1', 'n2', 'n3']
t= 410 ms n3 appends x=1 at index 1, term 1
t= 420 ms n3 commits ['x=1'] (3/5 stored)
t= 500 ms network splits ['n1', 'n3'] | ['n2', 'n4', 'n5']
t= 510 ms n3 appends x=9 at index 2, term 1
t= 560 ms n3 serves a lease read (lease ends at t=622)
t= 640 ms n3 refuses a lease read (lease ended at t=622)
t= 663 ms n2 times out, becomes candidate for term 2
t= 673 ms n2 wins term 2 with votes from ['n2', 'n4', 'n5']
t= 900 ms n2 appends x=5 at index 2, term 2
t= 910 ms n2 commits ['x=5'] (3/5 stored)
t= 950 ms n3 (leader, term 1) reads its own copy: x=1
t= 950 ms n2 (leader, term 2) reads its own copy: x=5
t=1000 ms network heals
t=1028 ms n1 deletes uncommitted ['x=9'] from index 2
t=1028 ms n3 sees term 2 and steps down to follower
t=1028 ms n3 deletes uncommitted ['x=9'] from index 2
n1 term=2 follower commit=2 log=[1:x=1 2:x=5]
n2 term=2 leader commit=2 log=[1:x=1 2:x=5]
n3 term=2 follower commit=2 log=[1:x=1 2:x=5]
n4 term=2 follower commit=2 log=[1:x=1 2:x=5]
n5 term=2 follower commit=2 log=[1:x=1 2:x=5]n3 still believed it led term 1 and appended x=9, but only n1 stored it: two of five, never committed, so no client heard success. The other three stopped hearing heartbeats; n2 timed out, won term 2 and committed x=5 with three copies. Briefly two nodes called themselves leader, in different terms, and only one could commit.
After the heal, n3 saw term 2 and stepped down. AppendEntries checks that the follower holds the entry just before the new ones, with the same term. Index 1 matched; index 2 held x=9 from term 1 instead of x=5 from term 2, so n1 and n3 deleted the conflict and took the leader's entry. All five logs ended identical.
At t = 950 ms, n3, still leader in its own eyes, read x=1 from its copy while the cluster had committed x=5: a leader answering from local state may already be deposed. Raft offers two fixes. The leader can confirm with a majority heartbeat round before answering (Section 8 of the paper). Or it holds a leader lease: once a majority acknowledged a heartbeat sent at time s, it may serve local reads until s plus the minimum election timeout divided by a clock drift bound, 150 / 1.1 here. Followers that heard from a leader recently ignore vote requests for 150 ms, and any new majority includes one of them, so no new leader appears sooner. Here the lease ended at 622 ms and n2 won at 673 ms.
The lease assumes no server's clock runs faster than another's by more than the bound. It needs no synchronised time of day, but a VM pause, a long garbage collection or a clock-rate change can break it, and the Raft thesis warns the system could then return arbitrarily stale data.
05. Step 4: A node with a stale log cannot win
In the stale scenario, one follower, n5, is cut off before two writes are committed. Then the leader is cut off and n5 rejoins. Predict who becomes leader.
python3 raft_model.py stalet= 176 ms n3 times out, becomes candidate for term 1
t= 186 ms n3 wins term 1 with votes from ['n1', 'n2', 'n3']
t= 400 ms network splits ['n5'] | ['n1', 'n2', 'n3', 'n4']
t= 410 ms n3 appends x=1 at index 1, term 1
t= 420 ms n3 appends x=2 at index 2, term 1
t= 420 ms n3 commits ['x=1'] (3/5 stored)
t= 430 ms n3 commits ['x=2'] (3/5 stored)
t= 500 ms network splits ['n3'] | ['n1', 'n2', 'n4', 'n5']
t= 636 ms n5 times out, becomes candidate for term 2
t= 641 ms n1 refuses n5: own log (last term 1, index 2) is more up to date
t= 641 ms n2 refuses n5: own log (last term 1, index 2) is more up to date
t= 641 ms n4 refuses n5: own log (last term 1, index 2) is more up to date
t= 663 ms n1 times out, becomes candidate for term 3
t= 673 ms n1 wins term 3 with votes from ['n1', 'n2', 'n4']
t= 678 ms n5 rejects entries after index 2: no entry from term 1 there
t= 683 ms n1 retries n5 from index 2
t= 688 ms n5 rejects entries after index 1: no entry from term 1 there
t= 693 ms n1 retries n5 from index 1
n1 term=3 leader commit=2 log=[1:x=1 1:x=2]
n2 term=3 follower commit=2 log=[1:x=1 1:x=2]
n3 term=1 leader commit=2 log=[1:x=1 1:x=2]
n4 term=3 follower commit=2 log=[1:x=1 1:x=2]
n5 term=3 follower commit=2 log=[1:x=1 1:x=2]n5 timed out first, but every voter refused it. Raft's election restriction compares the last entry of each log: the later term wins, and if the terms are equal the longer log wins. A voter refuses a candidate whose log is less up to date than its own. Every committed entry sits on a majority, and every electing majority includes one of those nodes; together with the commit rule from Step 2, the proof in Section 5.4.3 of the paper shows that no leader can lack a committed entry.
n1 won term 3 and repaired n5's log by walking backwards: n5 rejected entries whose predecessor it lacked, and n1 lowered its nextIndex until the logs matched. Side effects: n5's failed candidacy pushed everyone to term 2, which the pre-vote extension in the Raft thesis avoids, and the isolated n3 still calls itself leader of term 1 but cannot commit.
06. Step 5: Lock leases and fencing tokens
Coordination services such as etcd and ZooKeeper run consensus for you and offer leases or sessions on top: a client holds a lock while it keeps renewing a lease with a time-to-live. fencing.py models one lease that expires while its holder is paused. Predict the final value with fencing off.
"""A lease that expires during a pause, with and without fencing tokens.
Simulated seconds. The lock service hands out one lease at a time with a
6 s time-to-live and a token that grows by one with every grant (in etcd the
key's revision can play this role; in ZooKeeper the zxid).
"""
TTL = 6
class LockService:
def __init__(self):
self.holder, self.expires, self.token = None, 0, 0
def acquire(self, who, now):
if self.holder and now < self.expires:
return None # someone else holds a live lease
self.holder, self.expires = who, now + TTL
self.token += 1
return self.token
class Storage:
def __init__(self, fencing):
self.fencing, self.value, self.highest = fencing, "empty", 0
def write(self, who, value, token, now):
if self.fencing and token < self.highest:
print(f" t={now:2}s storage REJECTS {who} (token {token} < "
f"{self.highest})")
return
self.highest = max(self.highest, token)
self.value = value
print(f" t={now:2}s storage accepts {who}: {value!r} (token {token})")
def run(fencing):
print(f"fencing {'ON' if fencing else 'OFF'}")
locks, store = LockService(), Storage(fencing)
t1 = locks.acquire("worker-1", now=0)
print(f" t= 0s worker-1 gets the lease until t={locks.expires}s, token {t1}")
print(" t= 1s worker-1 checks: lease still valid, so it prepares a write")
print(" t= 1s worker-1 is paused for 9 s (VM stall, long GC, swap)")
t2 = locks.acquire("worker-2", now=7)
print(f" t= 7s worker-2 gets the lease until t={locks.expires}s, token {t2}")
store.write("worker-2", "report v2", t2, now=8)
store.write("worker-1", "report v1", t1, now=10) # resumes, still sure
print(f" final value: {store.value!r}\n")
run(fencing=False)
run(fencing=True)fencing OFF
t= 0s worker-1 gets the lease until t=6s, token 1
t= 1s worker-1 checks: lease still valid, so it prepares a write
t= 1s worker-1 is paused for 9 s (VM stall, long GC, swap)
t= 7s worker-2 gets the lease until t=13s, token 2
t= 8s storage accepts worker-2: 'report v2' (token 2)
t=10s storage accepts worker-1: 'report v1' (token 1)
final value: 'report v1'
fencing ON
t= 0s worker-1 gets the lease until t=6s, token 1
t= 1s worker-1 checks: lease still valid, so it prepares a write
t= 1s worker-1 is paused for 9 s (VM stall, long GC, swap)
t= 7s worker-2 gets the lease until t=13s, token 2
t= 8s storage accepts worker-2: 'report v2' (token 2)
t=10s storage REJECTS worker-1 (token 1 < 2)
final value: 'report v2'worker-1 checked its lease and it was valid; the pause came after the check, so its write arrived after the lease expired and after worker-2 had written. Checking again just before writing only narrows the gap. Without fencing, the older report silently replaced the newer one.
A fencing token is a number that grows with every grant. The storage remembers the highest token it has accepted and rejects anything lower. Two conditions make it work: tokens must increase strictly, and the resource itself must check them, not the client. The etcd documentation says its lock API cannot provide mutual exclusion by itself, because lease time is measured on separate clocks, and suggests the key's revision as a fencing token, the role Chubby's sequencers play.
For leader election, an exclusive job runner or shared configuration, use a coordination service rather than your own consensus code, then make each protected resource check a fencing token or make the operation safe to repeat. If the resource cannot check tokens, as with sending an email, design for duplicates.
07. Check your understanding
08. Apply it
- Run
python3 raft_model.py partition 5and find the split vote: two candidates in the same term, neither with three votes. Explain how the next term resolves it. - Add check-quorum: a leader without majority acknowledgements for one minimum election timeout steps down. Predict, then check, whether n3 still answers the read at 950 ms.
- Add your coordination service to the guarantee sheet: which operations use consensus, what a cut-off member answers, and which resources check its fencing tokens.
09. Review prompt
Without looking back:
- Why can two candidates never both win the same term?
- When is a Raft entry committed, and why did
x=9disappear after the heal? - State the election restriction and the argument for why it keeps committed entries.
- How does a leader lease work, and which assumption can break it?
- Why does a lock lease need a fencing token, and who must check it?
References
- The Raft Consensus Algorithm
- In Search of an Understandable Consensus Algorithm, extended version (Ongaro and Ousterhout)
- Consensus: Bridging Theory and Practice, sections 4.2.3 and 6.4 (Ongaro, PhD thesis)
- How to do distributed locking (Martin Kleppmann, 2016)
- etcd documentation: notes on the usage of lock and lease
- The Chubby lock service for loosely-coupled distributed systems (Burrows, 2006), section 2.4
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.