本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
26Replication and Consensus
A service kept on one machine stops when that machine stops. Keeping copies on several machines lets it survive, and raises the question the previous chapter prepared: the copies receive requests in different orders and lose messages, so what does a client see, and how do the copies stay alike? This chapter states what a client may expect from a set of copies, counts how many copies a read and a write must reach, proves that agreement between machines is impossible in general and shows how a real protocol, Raft, reaches it anyway, then commits one transaction across several machines and finds the case where it must wait.
You already know
A history is linearisable if its operations can be ordered so that the order is a correct sequential history and keeps every operation that returned before another was called before it; sequential consistency asks only that each thread’s operations keep their program order (Definitions 13.12 and 13.9). The happened-before relation orders events linked by process order and messages; processes may crash, and messages may be lost (Definitions 25.6 and 25.2). A write-ahead log records each change on disk before the change itself, so that a crash can be recovered from (Definition 23.9).
26.1 Replication and consistency models
Definition 26.1 (Replication, primary–backup replication, state-machine replication)
Replication keeps copies of the same data, the replicas, on several machines. In primary–backup replication, one replica, the primary, receives every request, applies it and forwards the result to the backups; if it fails, a backup takes over. In state-machine replication, every replica is a deterministic state machine started in the same state, and the replicas apply the same commands in the same order, so they pass through the same states.
State-machine replication turns the problem into one of order: if every replica agrees on the sequence of commands, determinism does the rest. Agreeing on that sequence is the subject of the third and fourth sections. Before that, a client needs to know what it can expect when it talks to replicas that may lag behind each other.
Definition 26.2 (Consistency model, causal consistency, eventual consistency)
A consistency model is a set of allowed histories: the reads and writes of a set of clients on shared registers, with the value each read returned. Under causal consistency, each client sees all the writes in an order that respects their causal order, the happened-before relation in which a write precedes every read that returns its value, and each read returns the latest write in the order its client sees. Under eventual consistency, if the writes stop, all the replicas eventually hold the same values, so every client’s reads eventually return the same value for each register.
Linearisability, sequential consistency and causal consistency form a chain, each weaker than the one before: a linearisable history is sequentially consistent, since keeping real-time order keeps each client’s order, and a sequentially consistent one is causally consistent, since one total order serves every client. Eventual consistency says something of a different kind: it allows any reads while writes go on and asks only for convergence afterwards. The program below decides each model by brute force, trying every order of the operations, on four small histories of two registers and , both 0 at first.
def legal(order):
"""Every read returns the last value written before it in this order."""
mem = {}
for _, kind, key, value, *_ in order:
if kind == "w":
mem[key] = value
elif mem.get(key, 0) != value:
return False
return True
def exists_order(ops, before):
"""Some legal order of ops in which a comes first whenever before(a, b)."""
return any(
legal(p) and all(not before(b, a) for i, a in enumerate(p) for b in p[i + 1 :])
for p in permutations(ops)
)
def program(a, b):
return a[0] == b[0] and a[4] < b[4]
def linearisable(h):
return exists_order(h, lambda a, b: a[5] < b[4]) # real time
def sequential(h):
return exists_order(h, program)
$ python consistency.py
linearisable sequential causal eventual
H1 yes yes yes yes
H2 no yes yes yes
H3 no no yes yes
H4 no no no yes
In H2, A’s write of 1 to finishes before B reads 0: no order that respects real time places the read before the write, but B’s two reads in program order, 0 then 1, fit around the write. In H3, A writes and B writes at the same time; C reads and then , while D reads and then . C saw first and D saw first, so no single order fits both, yet the two writes are concurrent and each client may order them its own way. In H4, B reads A’s write of and then writes ; C reads that and then the old , which no causal order allows, but both registers settle at 1 in the end.
Some data need no agreement on order at all. A counter of page views can be kept by each replica as its own count of the increments it received, and two replicas can merge their states by taking the larger count for each replica: the merges can happen in any order, any number of times, and all the replicas end up with the same total.
Definition 26.3 (Conflict-free replicated data type)
A conflict-free replicated data type (CRDT) is a data type whose replicas accept updates without coordination and exchange their states, merged by an operation that is commutative, associative and idempotent, so that replicas that have received the same updates hold the same state, whatever the order of the merges.
The name and a systematic study are due to Shapiro, Preguiça, Baquero and Zawirski in 2011. Exercise 26.12 shows what goes wrong when the counter is kept instead as one value with the latest writer winning.
26.2 Quorums
Definition 26.4 (Quorum, read quorum, write quorum)
In a system of replicas, each value stored with a version number, a write is sent to all the replicas and succeeds once of them have stored it; a read asks all of them and returns, among the first answers, the value with the highest version. The sets of replicas are the write quorums, the sets of replicas the read quorums; a quorum is either.
Gifford described such a scheme in 1979, with a number of votes for each replica in place of one replica, one vote.
Theorem 26.5 (Quorum intersection)
Every read quorum meets every write quorum if and only if .
Proof. If , a read quorum and a write quorum together have elements counted with repetition, chosen among replicas, so some replica is in both. If , take the write quorum of the first replicas and the read quorum of the last : they are disjoint. ∎
So when , a read that starts after a write has succeeded reaches at least one replica holding that write, and with it the highest version. Some reads never see a write that is still in progress: overlapping quorums alone do not make a history linearisable.
The price of a quorum is availability. If each replica is down with probability , independently, a write fails when fewer than replicas are up, that is when at least are down:
and the same with for a read. The program computes it both by this formula and by adding the probabilities of the up-and-down states.
def overlap(n, r, w):
nodes = range(n)
return all(
set(a) & set(b) for a in combinations(nodes, r) for b in combinations(nodes, w)
)
def unavailable_exact(n, k, p):
"""Sum over all 2^n up/down states of those with fewer than k replicas up."""
total = 0.0
for state in product((True, False), repeat=n):
up = sum(state)
if up < k:
total += (1 - p) ** up * p ** (n - up)
return total
def unavailable_formula(n, k, p):
"""At least n - k + 1 replicas down: a binomial tail."""
return sum(comb(n, d) * p**d * (1 - p) ** (n - d) for d in range(n - k + 1, n + 1))
$ python quorum.py
p = 0.01
N R W R+W>N overlap read unavailable write unavailable
3 2 2 True True 2.980e-04 2.980e-04
5 3 3 True True 9.851e-06 9.851e-06
5 2 4 True True 4.960e-08 9.801e-04
5 1 5 True True 1.000e-10 4.901e-02
5 2 3 False False 4.960e-08 9.851e-06
5 2 2 False False 4.960e-08 4.960e-08
N=5, W=3: exact 9.850600e-06, 10p^3 = 1.000000e-05
N=5, W=5: exact 4.900995e-02, 5p = 5.000000e-02
Raising makes reads cheaper and writes fragile, and the reverse: with , and , a read needs any one replica, and a write fails as soon as one is down.
26.3 Consensus
Definition 26.6 (Consensus problem, partial synchrony)
In the consensus problem, each of processes proposes a value, and each must decide on a value so that: no two processes decide differently (agreement); the decided value was proposed by some process (validity); and every process that does not crash eventually decides (termination). A system has partial synchrony if bounds on message delays and processing speeds exist but are not known, or hold only after some unknown time.
Consensus is what state-machine replication needs, once for each position of the command sequence. Without failures it is easy: every process sends its value to all and decides the smallest it receives. With one crash, it is impossible in an asynchronous system.
Theorem 26.7 (FLP impossibility)
In an asynchronous system in which at most one process may crash, no deterministic protocol solves the consensus problem in every run.
Proof. Admitted at this level. ∎
The theorem is due to Fischer, Lynch and Paterson in 1985. Its proof shows that every protocol has an initial state from which both decisions are still possible, and that from any such state the network can always deliver some message whose arrival leaves both still possible, so an adversarial schedule postpones the decision forever. The theorem forbids guaranteed termination, not agreement. Real systems escape it in two ways. They keep agreement and validity always, and guarantee termination only when the system behaves synchronously for long enough, which partial synchrony promises; or they use randomness, which makes non-termination happen with probability 0. Lamport’s Paxos, published in 1998, and Raft, below, take the first way.
26.4 Raft
Ongaro and Ousterhout designed Raft as an alternative to Paxos meant to be easier to understand; their paper appeared at a conference in 2014. It solves consensus on a whole sequence of commands, a log, by electing one leader that decides the order alone.
Definition 26.8 (Raft, election term, leader election, replicated log, log matching property, commit index)
Raft is a protocol for state-machine replication among servers, each a follower, a candidate or a leader. Time is divided into election terms, numbered ; every message carries its sender’s election term, and a server that sees a larger one adopts it and becomes a follower. In a leader election, a follower that has heard from no leader for a random timeout starts a new election term, votes for itself and asks the others for their votes; each server votes at most once per election term, only for a candidate whose log is at least as up to date as its own (larger last election term, or the same and at least as long), and a candidate with votes from a majority becomes leader. The replicated log is each server’s sequence of entries, each a command with the election term in which a leader created it. The leader appends client commands to its log and sends each follower the entries it lacks, with the index and election term of the entry just before them; a follower accepts only if its own log has that entry, and replaces any conflicting entries. The commit index is the largest index known to be committed: the leader commits an entry of its own election term once a majority store it, and with it every entry before it. The log matching property states that if two logs have an entry with the same index and election term, they are identical up to that index.
The random timeouts make it likely that one server times out alone and wins before the others start, without making it certain. Five servers start as followers:
$ python raft_election.py
t= 36 S3 times out: candidate for term 1
t= 36 S5 times out: candidate for term 1
t= 41 S5 leader of term 1, votes S1,S4,S5
t= 45 S3 hears leader S5: follower in term 1
terms: S1:1 S2:1 S3:1 S4:1 S5:1
def on_vote_q(self, src, term, last_index, last_term):
my_index, my_term = self.last()
# the election restriction: the candidate's log is at least as up to date
up_to_date = (last_term, last_index) >= (my_term, my_index)
grant = term == self.term and self.voted_for in (None, src) and up_to_date
if grant:
self.voted_for = src
self.wait_election()
self.send(src, ("vote", self.term, grant))
def on_append(self, src, term, prev, prev_term, entries, leader_commit):
if term < self.term:
self.send(src, ("appended", self.term, False, 0))
return
if self.role == "candidate":
self.say(f"hears leader {src}: follower in term {self.term}")
self.role, self.leader = "follower", src
self.wait_election()
if prev > len(self.log) or self.term_at(prev) != prev_term:
# no entry at prev with the leader's term there: refuse
self.send(src, ("appended", self.term, False, 0))
return
for k, entry in enumerate(entries, start=prev + 1):
if k <= len(self.log) and self.log[k - 1][0] != entry[0]:
del self.log[k - 1 :] # a conflicting suffix is removed
if k > len(self.log):
self.log.append(entry)
self.advance(min(leader_commit, prev + len(entries)))
self.send(src, ("appended", self.term, True, prev + len(entries)))
def on_appended(self, src, term, success, match):
if self.role != "leader" or term != self.term:
return
if not success:
self.next[src] = max(1, self.next[src] - 1) # back up one entry and retry
return
self.match[src] = max(self.match[src], match)
self.next[src] = self.match[src] + 1
for i in range(len(self.log), self.commit, -1):
copies = 1 + sum(m >= i for m in self.match.values())
current = self.term_at(i) == self.term or self.buggy_commit
if copies > len(self.names) // 2 and current: # the commitment rule
self.advance(i)
break
Theorem 26.9 (Log matching)
In every run of Raft, if two logs contain an entry with the same index and the same election term, the two logs are identical in all entries up to that index.
Proof. Facts used: at most one leader per election term (exercise 26.10); a leader never deletes or changes entries of its own log. Same entry. An entry with election term is created only by the leader of , which creates at most one entry at each index, and followers only copy entries. So two entries with the same index and election term carry the same command. Same prefix, by induction on the number of accepted append messages in the run. The property holds for the empty logs. A follower’s log changes only by accepting entries after index , sent with the election term of the leader’s entry at ; it accepts only if its own entry at has election term , so by the induction hypothesis its log equals the leader’s up to ; it then cuts what conflicts and copies the leader’s entries after , so its log up to the last copied entry is a prefix of the leader’s, and every pair of logs still satisfies the property. A leader’s log changes only by appending an entry with a new index, which no other log has with this election term yet. ∎
The commitment rule’s condition, an entry of the leader’s own election term, is not a detail. A leader that committed an older entry merely because a majority stores it could see that entry replaced later by a leader elected with the votes of servers that never stored it; exercise 26.5 replays such a run. With the rule, a committed entry is in the log of every later leader, a property called leader completeness: no server missing it can collect a majority of votes, since every majority contains a server that stores it and refuses. Exercise 26.9 proves the first step, for the next election term.
The next run shows the logs at work. The leader S5 replicates five commands while S2 is down, then is cut off from the others, appends a sixth command that reaches nobody, and crashes.
$ python raft_replicate.py
t= 36 S3 times out: candidate for term 1
t= 36 S5 times out: candidate for term 1
t= 41 S5 leader of term 1, votes S1,S4,S5
t= 45 S3 hears leader S5: follower in term 1
t= 60 S5 appends x=1 at index 1
t= 70 S5 appends y=2 at index 2
t= 75 S2 crashes
t= 80 S5 appends x=3 at index 3
t= 90 S5 appends z=4 at index 4
t=100 S5 appends y=5 at index 5
t=105 S2 recovers in term 1 with 2 entries
t=108 S5 is cut off from the others
t=110 S5 appends x=6 at index 6
t=112 S5 crashes; the cut is healed
t=132 S1 times out: candidate for term 2
t=133 S4 times out: candidate for term 2
t=136 S3 times out: candidate for term 2
t=173 S3 times out: candidate for term 3
t=174 S1 becomes follower in term 3
t=176 S4 becomes follower in term 3
t=179 S3 leader of term 3, votes S1,S2,S3
t=180 S3 appends z=7 at index 6
t=180 S3 appends y=8 at index 7
t=220 S5 recovers in term 1 with 6 entries
logs at t=113
S1 follower term=1 commit=4 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5
S2 follower term=1 commit=0 1:x=1 1:y=2
S3 follower term=1 commit=4 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5
S4 follower term=1 commit=4 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5
S5 down term=1 commit=5 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5 1:x=6
logs at t=300
S1 follower term=3 commit=7 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5 3:z=7 3:y=8
S2 follower term=3 commit=7 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5 3:z=7 3:y=8
S3 leader term=3 commit=7 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5 3:z=7 3:y=8
S4 follower term=3 commit=7 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5 3:z=7 3:y=8
S5 follower term=3 commit=7 1:x=1 1:y=2 1:x=3 1:z=4 1:y=5 3:z=7 3:y=8
S2 could not have won: its log ends at index 2 with election term 1, behind the logs of S1, S3 and S4, which would all refuse it their vote. When the cut-off server is a leader that keeps running, its new entries are never committed, because it cannot reach a majority:
$ python raft_partition.py
t= 36 S3 times out: candidate for term 1
t= 36 S5 times out: candidate for term 1
t= 41 S5 leader of term 1, votes S1,S4,S5
t= 45 S3 hears leader S5: follower in term 1
t= 60 S5 appends x=1 at index 1
t= 60 client sends x=1 to S5: accepted=True
t= 70 cut: {S1, S5} | {S2, S3, S4}
t= 80 S5 appends y=2 at index 2
t= 80 client sends y=2 to S5: accepted=True
t= 90 S5 appends z=3 at index 3
t= 90 client sends z=3 to S5: accepted=True
t= 94 S2 times out: candidate for term 2
t= 99 S2 leader of term 2, votes S2,S3,S4
t=160 S2 appends y=9 at index 2
t=160 client sends y=9 to S2: accepted=True
t=200 the cut is healed
t=205 S5 becomes follower in term 2
logs at t=199
S1 follower term=1 commit=1 1:x=1 1:y=2 1:z=3
S2 leader term=2 commit=2 1:x=1 2:y=9
S3 follower term=2 commit=2 1:x=1 2:y=9
S4 follower term=2 commit=2 1:x=1 2:y=9
S5 leader term=1 commit=1 1:x=1 1:y=2 1:z=3
logs at t=260
S1 follower term=2 commit=2 1:x=1 2:y=9
S2 leader term=2 commit=2 1:x=1 2:y=9
S3 follower term=2 commit=2 1:x=1 2:y=9
S4 follower term=2 commit=2 1:x=1 2:y=9
S5 follower term=2 commit=2 1:x=1 2:y=9
The clients of S5 had their two commands accepted but never confirmed as committed; a client waits for the commit before reporting success, and retries elsewhere after a timeout, with the request identifiers of the previous chapter. The last program runs Raft 1,000 times, with random crashes and restarts and 5 % of messages lost, and checks three safety properties in each run.
$ python raft_check.py
1000 runs: 88779 entries committed, 2012 leaders elected
election safety broken in 0 runs
log matching broken in 0 runs
state machine safety broken in 0 runs
A thousand random runs prove nothing, but they find bugs: the same check finds the broken commitment rule of exercise 26.5 when the crashes are placed by hand. Raft also changes its set of servers while it runs, by committing the new configuration as a log entry, in a way that must avoid two majorities, of the old and the new configuration, deciding at once; the details are in the Raft paper.
26.5 Atomic commit and the trade-offs
Raft copies one log to several servers. A transaction that changes data held by different servers, a transfer between two banks for instance, needs another kind of agreement: every server commits its part, or none does.
Definition 26.10 (Two-phase commit, coordinator, blocking protocol)
In two-phase commit (2PC), a coordinator asks every participant whether it can commit its part of a transaction. A participant that can writes its part and its vote to its log and answers yes; from then on it may neither commit nor abort on its own. If every vote is yes, the coordinator logs the decision commit, otherwise abort, and sends the decision to all. A blocking protocol is one in which the failure of one process can leave other, correct processes unable to finish until it recovers.
def on_message(self, src, msg):
kind, value = msg
if kind == "prepare?":
self.since = self.net.now # the vote is logged, then sent
self.send("C", ("vote", self.vote))
if self.vote:
self.set_timer(20, "ask")
else:
self.finish("abort") # a no can abort at once
elif kind == "decision" and self.decision is None:
self.finish(value)
elif kind == "decision?" and self.decision:
self.send(src, ("decision", self.decision))
def finish(self, decision):
self.decision = decision
held = self.net.now - self.since
self.net.notes.append(
f"t={self.net.now:>3} {self.name}: {decision}, "
f"locks held {held}, asked {self.asked} times"
)
def on_timer(self, what):
if self.decision is None: # voted yes: may neither commit nor abort alone
self.asked += 1
for p in ["C"] + [q for q in PARTS if q != self.name]:
self.send(p, ("decision?", None))
self.set_timer(20, "ask")
$ python twopc.py
-- all vote yes
t= 0 C: prepare?
t= 9 C: logs commit
t= 11 P3: commit, locks held 6, asked 0 times
t= 13 P1: commit, locks held 8, asked 0 times
t= 14 P2: commit, locks held 9, asked 0 times
-- P2 votes no
t= 0 C: prepare?
t= 5 P2: abort, locks held 0, asked 0 times
t= 9 C: logs abort
t= 11 P3: abort, locks held 6, asked 0 times
t= 13 P1: abort, locks held 8, asked 0 times
-- the coordinator crashes
t= 0 C: prepare?
t= 9 C: logs commit
t= 9 C crashes
t=300 C restarts, reads commit
t=301 P1: commit, locks held 296, asked 14 times
t=301 P3: commit, locks held 296, asked 14 times
t=302 P2: commit, locks held 297, asked 14 times
Two-phase commit is a blocking protocol: a participant that has voted yes waits for the decision, and if the coordinator fails for good, some participants never resolve their transactions. The participants could ask each other, as here; it helps only if one of them has received the decision, or voted no. Exercise 26.11 proves that no ask can help when all voted yes and none heard the decision. Running the coordinator’s decision through a consensus protocol replicated on several machines removes the single point of failure.
The last trade-off concerns the network itself.
Definition 26.11 (Network partition)
A network partition is a failure of the network that splits the servers into groups that can communicate inside each group but not between groups; every message between groups is lost.
Theorem 26.12 (CAP theorem)
No replicated register in an asynchronous network can be linearisable and also available, every request to a non-crashed server receiving a response, in every run where network partitions occur.
Proof sketch. Suppose a register replicated on servers split into two non-empty groups and by a partition from the start, with value . A client writes at a server of ; by availability the write completes, although no message reaches . Then a client reads at a server of ; by availability the read returns, and since has received nothing, its state, and hence its answer, is what it would be had the write never happened: . The write completed before the read began, so linearisability required . ∎
Brewer stated the trade-off as a conjecture in a keynote of 2000, and Gilbert and Lynch proved it in 2002. During a partition, a service must choose. Raft chooses consistency: the minority side stops accepting commands. A store that lets each side accept writes and merges them afterwards chooses availability, and gives up linearisability. Abadi’s PACELC adds that even without a partition, a replicated system trades consistency against latency, since waiting for other replicas takes time. The town’s bank needs consistency for its balances, whatever the waiting; a page-view counter on its website can be a CRDT and stay available; the library’s catalogue, in the weekend problem, lies between.
26.6 Exercises
Exercise 26.1 ★
Client A writes 1 to , from time 0 to 1, and then reads from time 2 to 3, getting 0. Which of the four models of Output 26.1 does this history satisfy? What does a store that allows it fail to give its clients?
Solution
Solution of Exercise 26.1.
Only eventual consistency: the single read is the last one, so convergence holds trivially. It is not causal, since the write precedes the read in A’s program order and A’s read must then return 1; not sequential nor linearisable, for the same reason. A store that allows it does not let a client read its own writes: a reader who reserved a book and reloads the page may not see the reservation. A test runs the four checkers on it.
Exercise 26.2 ★
For each of , , , and , say whether every read quorum meets every write quorum, and how many replicas may be down while reads and writes both still work.
Solution
Solution of Exercise 26.2.
By Theorem 26.5: overlaps (), but a write needs all three, so no replica may be down for writes. does not overlap (): replicas 1, 2 and 3, 4 are disjoint quorums. overlaps, and works with one replica down. overlaps and works with three down. does not overlap. In general reads and writes both work with replicas down: 0, 2, 1, 3 and 3.
Exercise 26.3 ★
Five servers have these logs, written as the election terms of their entries: S1: 1 1 2; S2: 1 1 3 3; S3: 1 1; S4: 1 1 2 2; S5: 1 1 3. All are in election term 3 and none has voted in election term 4. Which servers can win an election for election term 4 if all five are up, and from whom can each get votes?
Solution
Solution of Exercise 26.3.
Compare (last election term, length): S1 (2, 3), S2 (3, 4), S3 (1, 2), S4 (2, 4), S5 (3, 3). A server grants its vote to a candidate whose pair is at least its own. S2’s pair is the largest: all five can vote for it. S5 can get S1, S3, S4 and itself. S4 can get S1, S3 and itself: three, a majority. S1 gets only S3 and itself, S3 only itself. So S2, S4 or S5 can win. S4 can win although it lacks the entries of election term 3: they are on S2 and S5 only, two servers out of five, so they were never committed, and losing them is allowed.
Exercise 26.4 ★
In Output 26.5, what is the commit index of each server at , and why is S5’s not 3? What does it become at ?
Solution
Solution of Exercise 26.4.
At : S2, S3 and S4 have commit index 2 (x=1 and y=9 are on three servers, a majority, and y=9 is of S2’s election term); S1 and S5 have 1. S5’s entries y=2 and z=3 are stored on S5 and S1 only, two of five, so S5 cannot commit them. At , after the cut heals, S5 and S1 adopt election term 2, their entries 2 and 3 are replaced by y=9, and every server has commit index 2.
Exercise 26.5 ★★
exercises/ex5_figure8.py scripts a run with buggy_commit=True, where a leader commits any entry that a majority stores, whatever its election term. Run it, follow the logs step by step, and explain why an entry is committed twice with different commands at index 2. Show that the run with the correct rule commits nothing at index 2 before election term 4.
Solution
Solution of Exercise 26.5.
S1, leader of election term 1, commits a everywhere, then, cut off with S2, appends b at index 2, which reaches S2 only; S1 crashes. S5 is elected for election term 2 by S3, S4 and itself, appends c at index 2, keeps it, and crashes. S1 restarts; its first candidacy, for election term 2, fails since S3 and S4 have voted in it; the second wins election term 3 with S2 and S3, whose logs end at index 2 or 1 with election term 1. S1 sends b to S3 and S4. Now b is on S1, S2, S3, S4: with the buggy rule, S1 commits index 2 = b. S1 crashes. S5 restarts and wins election term 4: its last entry, c of election term 2, is more up to date than everyone’s last entry of election term 1, so S2, S3 and S4 vote for it. S5 overwrites index 2 with c and commits it with d: index 2 was committed with b and then with c, and check reports state machine safety broken. With the correct rule, S1 in election term 3 may not commit b, of election term 1, by counting; it has no entry of election term 3, so it commits nothing at index 2, and when S5 replaces b nothing committed is lost. Index 2 is first committed in election term 4, as c, together with d.
Exercise 26.6 ★★
A log that only grows fills the disk. Write a class CompactLog that replaces the entries up to a committed index by the state they produced, a dictionary, and the election term of the last of them: last(), term_at(i) for every index from the snapshot on, append, matches(prev, prev_term) for the follower’s check, compact(upto), and install(base, base_term, state) for a follower that receives a leader’s snapshot. Test it against an uncompacted log.
Solution
Solution of Exercise 26.6.
exercises/ex6_compaction.py keeps base, base_term, the state and the entries after base; index base is entries[i - base - 1]. term_at(base) returns base_term, so the follower’s check still works for an append that starts right after the snapshot. matches(prev, prev_term) accepts any prev below the snapshot, since those entries are committed and agree with every leader’s log by leader completeness. compact(upto) applies the commands up to upto to the state and drops them. install keeps the follower’s entries after the snapshot only if its log has an entry at base with base_term, by log matching then identical up to there; otherwise it discards its log. The test compares 200 random sequences of appends, new election terms and compactions with an uncompacted log: last index and election term, every term_at, every matches, and the state.
Exercise 26.7 ★★
In weighted voting, replica has votes, , a read must collect votes and a write . Prove that if , every read quorum meets every write quorum, and that if , any two write quorums meet. Show by an example that, unlike Theorem 26.5, the converse can fail. Give weights for three replicas, one of them on a much faster machine, so that it alone can serve reads.
Solution
Solution of Exercise 26.7.
Facts used: votes are non-negative integers. If a read quorum and a write quorum were disjoint, their votes would add up to at least , more than all the votes there are. In the same way two disjoint write quorums would hold at least votes. The converse fails: one replica with 3 votes, , ; then , yet every quorum contains the only replica. Weights: the fast replica 3 votes, the two others 1 each, , . The fast replica alone is a read quorum, and , . The price: the two slow replicas have only 2 votes together, so no write, and no read, can succeed without the fast one.
Exercise 26.8 ★★
With and , compute the probability that a read and that a write are unavailable for , and compare with . Which choice suits a catalogue that is read a thousand times for each write?
Solution
Solution of Exercise 26.8.
With : for , a read is unavailable only if 4 or 5 replicas are down, ; for , a write is unavailable if 2 or more are down, . With both are . For a thousand reads per write, refuses on average of the operations against , and each read asks fewer replicas; but one write in about a thousand is refused and must be retried. For a catalogue, where a librarian can retry an addition, suits better. A test checks the probabilities.
Exercise 26.9 ★★
A leader of election term commits an entry of election term at index , stored by a majority. Prove that no server whose log lacks can be elected leader of election term . Where does the proof use that has ’s election term?
Solution
Solution of Exercise 26.9.
Facts used: log matching (Theorem 26.9); election safety (exercise 26.10); two majorities meet. Let be the majority storing , and a server lacking that asks for votes in election term . Its votes form a majority, which meets in some server . Since ’s election is the first of election term to succeed, no log holds an entry of election term , and ’s last entry has election term , since stores . If ’s last entry has an election term below , ’s log is more up to date and refuses. If ’s last entry has election term , it was created by , the only leader of , at some index ; by log matching ’s log equals ’s up to , and since lacks , ; ’s log has length at least with the same last election term, so it is more up to date and refuses. Either way cannot gather a majority. The proof uses ’s election term to know that ’s last entry has election term , at least that of ’s: an entry of an older election term stored by a majority gives no such guarantee, which is exercise 26.5.
Exercise 26.10 ★★★
Prove election safety: in every run of Raft, at most one server becomes leader in each election term, even when servers crash and restart. Which piece of state must survive a crash for the proof to hold?
Solution
Solution of Exercise 26.10.
Facts used: two majorities of servers meet. A server becomes leader of election term only with the votes of a majority for , its own included. Each server records, with its current election term, the candidate it voted for, and grants a vote for only if it has not voted for another candidate in : it votes at most once per election term. If two servers became leaders of , their majorities would share a server that voted for both in , a contradiction. The current election term and the vote must survive a crash, written to disk before the vote is sent: a server that forgot its vote after restarting could vote again in the same election term. In raft.py they are the persistent fields that reset does not touch.
Exercise 26.11 ★★★
Prove that in two-phase commit, if the coordinator crashes after every participant has voted yes and before any receives the decision, no participant can decide without risking a decision that contradicts the coordinator’s, whatever messages the participants exchange. Three-phase commit adds a round in which the participants learn the decision before anyone acts on it; say why it relies on a bound on message delays.
Solution
Solution of Exercise 26.11.
Facts used: a participant’s decision depends only on what it has received. Consider two runs. In the first, the coordinator logs commit and crashes before sending it. In the second, the coordinator crashes before logging anything, and on restart, finding no decision, aborts, which it is allowed to do, since no participant has been told anything. Until the coordinator restarts, every participant receives exactly the same messages in both runs: the prepare request, and whatever the other participants send, which by induction on the messages is the same in both runs, since they all voted yes and none heard a decision. So any rule that lets a participant decide gives the same decision in both runs, and it contradicts the coordinator’s commit in the first or its abort in the second. The participants must wait: two-phase commit blocks. Three-phase commit inserts a round in which the coordinator tells everyone it is about to commit and collects acknowledgements, so that no participant commits while another could still abort; a participant that times out decides from what the others know. A timeout means “the coordinator has crashed” only if message delays are bounded: in an asynchronous network a slow coordinator is mistaken for a crashed one, and the two sides of a network partition can decide differently.
Exercise 26.12 ★★★
Three replicas of a page-view counter accept increments alone and merge their states now and then. Run exercises/ex12_crdt.py: with a last-writer-wins register, each replica writes its value plus 1 with a timestamp, and a merge keeps the later timestamp. Explain why 207 increments show as 85. Prove that the grow-only counter’s merge is commutative, associative and idempotent, and that after every replica has merged with every other, each shows the number of increments made.
Solution
Solution of Exercise 26.12.
With the register, two replicas that increment between merges both write their old value plus 1; the merge keeps only the one with the later timestamp, and the other increment is lost. Each such pair loses one, and over the 300 steps 122 of the 207 increments are lost: all three replicas end at 85. Grow-only counter. Facts used: is commutative, associative and idempotent. The merged state is the entrywise maximum, and an entrywise operation inherits these three properties from . Replica ’s own entry counts its increments, and every copy of that entry elsewhere is a value it held earlier, so at most its current value; increments never decrease it. After every replica has merged with every other, entry everywhere is the maximum of its copies, replica ’s own count, and the value, the sum of the entries, is the total number of increments. exercises/ex12_crdt.py prints 207 three times; a test checks 50 seeds and the three properties.
26.7 Weekend problem
Problem 26.1
Weekend problem — A store in three towns
The library of Brenmoor shares its catalogue with the libraries of Kelsford and Wenmouth, two neighbouring towns. The catalogue lists every book and whether it is on the shelf; readers search it and reserve books in all three towns. It is kept on five replicas: two in Brenmoor, two in Kelsford, one in Wenmouth. Each replica is down with probability , independently of the others.
Part I — What the catalogue needs.
- A reader searches for a title. Which consistency model is enough for a search, and why?
- Two readers in two towns reserve the last copy of a book at the same time. Which model must the reservation have so that only one succeeds?
- A reader reserves a book and reloads the page. What must the store guarantee for the reader to see the reservation, at the least?
- A librarian adds a book and then a note about it. Which model guarantees that nobody sees the note without the book?
- Could the number of reservations of a book be a CRDT counter? What about the reservation itself?
- Sum up the catalogue’s needs in one sentence for each of searching and reserving.
Part II — Quorums.
- With , which pairs make every read quorum meet every write quorum?
- Take . Can a reservation be read stale right after it is confirmed?
- Why do overlapping quorums alone not prevent two readers from both reserving the last copy?
- Where should the replicas a Brenmoor reader’s read reaches be, for a fast read, and is that enough for overlap?
- What does , give for searches and for reservations?
- Which choice would you make for the catalogue, and why?
Part III — Availability.
- Write the probability that a write is unavailable for , , as a sum.
- Compute it, and compare with .
- Compute it for , and compare with .
- The link between Kelsford and the other towns fails, and Kelsford’s two replicas are cut off. Which side can still write with ?
- A failure of the Brenmoor building takes both its replicas down at once. Why does the formula of question 13 no longer apply?
- How should five replicas be spread among the three towns so that one town’s loss leaves a majority?
Part IV — Raft or quorums.
- With the catalogue on Raft, how many servers must be up for reservations to continue?
- Under Raft, what happens to reservations made at a cut-off leader, as S5’s commands in Output 26.5?
- What do Raft’s reservations give that quorum writes with version numbers do not?
- What does Raft cost in messages and in waiting for each reservation?
- During a partition, which of searching and reserving should stay available, and which should stop? Name the theorem that forces the choice.
- Sum up: give the probability that a reservation is refused because too few replicas are up with , and with .
Solution
Solution of Problem 26.1.
1. Eventual consistency, or causal: a search that misses a book added a second ago does no harm, and the next search finds it.
2. Linearisability: the check “on the shelf?” and the reservation must happen in one order that every replica agrees on, so that the second reader sees the first reservation. This needs consensus, for instance Raft.
3. That a client reads its own writes; causal consistency gives it, since the reservation precedes the reload in the reader’s program order.
4. Causal consistency: the note’s write follows the book’s in the librarian’s program order, so whoever sees the note sees the book.
5. A count of reservations goes down when one is cancelled, so it would need a counter with decrements, a pair of grow-only counters. The reservation itself cannot: it is a choice between two readers that every replica must make alike, and a merge cannot undo a reservation already confirmed to a reader.
6. Searching: available and eventually consistent, from the nearest replica. Reserving: linearisable, through a consensus protocol, and unavailable when no majority is reachable.
7. Those with : , , , , , and any with larger values.
8. No: a read that starts after the reservation’s write succeeded reaches one of the three replicas that stored it, by Theorem 26.5, and returns its higher version.
9. Both readers can read “on the shelf” before either writes, then both write their reservations: the quorums overlap, but nothing orders the two check-then-write sequences.
10. Brenmoor’s two replicas and one more, from another town: three replicas are needed, wherever they are, and any three meet any write quorum of three.
11. Searches read one replica, the nearest, and fail only if all five are down, . Every reservation must reach all five and fails about 4.9 % of the time, at every failure of any town.
12. Searches with and no ordering; reservations through Raft, which orders them, or quorums with at the least.
13. .
14. (Output 26.2), close to : three replicas down dominates.
15. , close to : any one replica down dominates.
16. The Brenmoor and Wenmouth side, with three replicas; Kelsford’s two cannot form a write quorum.
17. The two Brenmoor replicas fail together: the failures are not independent, and the probability of losing two at once is that of the building’s failure, far above .
18. At most two in any town, as now: 2, 2 and 1. The loss of any one town leaves at least three, a majority.
19. Three of the five, a majority.
20. They are appended but never committed, since the cut-off leader cannot reach a majority; after the cut heals they are replaced, and the readers, never told that their reservations were committed, retry.
21. One order of all the reservations, the order of the log, in which each check sees every earlier reservation: two readers can no longer both get the last copy.
22. For each reservation, the leader sends the entry to the four followers and waits for two of them to answer, a round trip, and the client waits for the commit; on top of that, heartbeats every 10 time units.
23. Searches should stay available on both sides, from the local replicas; reservations should stop on the side without a majority. The CAP theorem (Theorem 26.12) forces the choice.
24. With , a reservation finds too few replicas with probability , about one in 100,000; with , , about one in 20: three replicas out of five are five thousand times more available than five.
本章定义的术语
- Conflict-free replicated data type
- Consensus problem, partial synchrony
- Consistency model, causal consistency, eventual consistency
- Network partition
- Quorum, read quorum, write quorum
- Raft, election term, leader election, replicated log, log matching property, commit index
- Replication, primary–backup replication, state-machine replication
- Two-phase commit, coordinator, blocking protocol