计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本: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 xx and yy, 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)
Listing 26.1. An order is legal if every read returns the last write before it; a model asks for a legal order that respects real time, or program order, or, for each client separately, causal order. code/bachelor-3/26-replication-and-consensus/listings/consistency.py
$ 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
Output 26.1. Each history separates two models: H2 is sequential but not linearisable, H3 causal but not sequential, H4 eventually consistent but not causal.

In H2, A’s write of 1 to xx 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 xx and B writes yy at the same time; C reads x=1x = 1 and then y=0y = 0, while D reads y=1y = 1 and then x=0x = 0. C saw xx first and D saw yy 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 xx and then writes yy; C reads that yy and then the old xx, which no causal order allows, but both registers settle at 1 in the end.

The four models and the histories of , each in the smallest model that contains it. The outer box counts only histories that converge: a causal history in which two clients never agree lies outside it.
The four models and the histories of Output 26.1, each in the smallest model that contains it. The outer box counts only histories that converge: a causal history in which two clients never agree lies outside it.

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 NN replicas, each value stored with a version number, a write is sent to all the replicas and succeeds once WW of them have stored it; a read asks all of them and returns, among the first RR answers, the value with the highest version. The sets of WW replicas are the write quorums, the sets of RR 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 R+W>NR + W > N.

Proof. If R+W>NR + W > N, a read quorum and a write quorum together have R+W>NR + W > N elements counted with repetition, chosen among NN replicas, so some replica is in both. If R+W≤NR + W \le N, take the write quorum of the first WW replicas and the read quorum of the last RR: they are disjoint. ∎

So when R+W>NR + W > N, 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.

Five replicas with R = W = 3. The write reached replicas 1, 2 and 3; any three replicas a read reaches include one of them, here replica 3.
Five replicas with R=W=3R = W = 3. The write reached replicas 1, 2 and 3; any three replicas a read reaches include one of them, here replica 3.

The price of a quorum is availability. If each replica is down with probability pp, independently, a write fails when fewer than WW replicas are up, that is when at least N−W+1N - W + 1 are down:

P(write unavailable)=∑d=N−W+1N(Nd)pd(1−p)N−d,P(\text{write unavailable}) = \sum_{d = N - W + 1}^{N} \binom{N}{d} p^d (1 - p)^{N - d},

and the same with RR for a read. The program computes it both by this formula and by adding the probabilities of the 2N2^N 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))
Listing 26.2. Intersection checked on every pair of quorums, and unavailability computed by enumeration and by the binomial tail. code/bachelor-3/26-replication-and-consensus/listings/quorum.py
$ 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
Output 26.2. Overlap holds exactly when R+W>NR + W > N. With p=0.01p = 0.01, writing to all five replicas fails about 5 % of the time; writing to three, about one time in 100,000.

Raising WW makes reads cheaper and writes fragile, and the reverse: with N=5N = 5, R=1R = 1 and W=5W = 5, 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 nn 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 NN servers, each a follower, a candidate or a leader. Time is divided into election terms, numbered 1,2,…1, 2, \ldots; 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 three roles of a Raft server. Only a follower or a candidate moves on its own, at a timeout; every other move, and every move of the leader, is caused by a message.
The three roles of a Raft server. Only a follower or a candidate moves on its own, at a timeout; every other move, and every move of the leader, is caused by a message.

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
Output 26.3. S3 and S5 time out in the same tick, and S5 collects three votes first: a majority of five. S3 yields when S5’s first heartbeat reaches it.
    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))
Listing 26.3. A vote: granted at most once per election term, and only to a candidate whose log is at least as up to date. code/bachelor-3/26-replication-and-consensus/listings/raft.py
    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)))
Listing 26.4. A follower receiving entries: refuse unless its log has the entry before them with the right election term; cut a conflicting suffix; copy the rest; learn the commit index. code/bachelor-3/26-replication-and-consensus/listings/raft.py
    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
Listing 26.5. The leader counts the copies of each entry and commits the highest one of its own election term stored by a majority. code/bachelor-3/26-replication-and-consensus/listings/raft.py

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 tt is created only by the leader of tt, 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 kk, sent with the election term tkt_k of the leader’s entry at kk; it accepts only if its own entry at kk has election term tkt_k, so by the induction hypothesis its log equals the leader’s up to kk; it then cuts what conflicts and copies the leader’s entries after kk, 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
Output 26.4. The transcript of the run. In election term 2 three candidates split the votes; S3 wins election term 3 and receives the two waiting commands. The run ends by printing every log, as they were at t=113t = 113 and at t=300t = 300.
The logs of , each entry written as election term:command. Before the change, S5’s sixth entry exists only in its own log, and S2 missed three entries while down. After it, S3’s entries of election term 3 have replaced S5’s uncommitted entry, and S2 has caught up.
The logs of Output 26.4, each entry written as election term:command. Before the change, S5’s sixth entry exists only in its own log, and S2 missed three entries while down. After it, S3’s entries of election term 3 have replaced S5’s uncommitted entry, and S2 has caught up.

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
Output 26.5. S5 and S1 are cut off from S2, S3 and S4. S5 accepts two commands and cannot commit them; the majority elects S2, which commits y=9. When the cut heals, S5 steps down and its two entries are replaced.

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
Output 26.6. A thousand seeded runs: no election term had two leaders, no two logs broke log matching, and no index was ever committed with two different entries.

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")
Listing 26.6. A participant: vote, and if the vote is yes, wait for the decision, asking the coordinator and the other participants every 20 time units. code/bachelor-3/26-replication-and-consensus/listings/twopc.py
$ 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
Output 26.7. Three runs. When the coordinator crashes after logging its decision and before sending it, the participants hold their locks for nearly 300 time units and ask fourteen times each, until it restarts.

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 G1G_1 and G2G_2 by a partition from the start, with value v0v_0. A client writes v1v_1 at a server of G1G_1; by availability the write completes, although no message reaches G2G_2. Then a client reads at a server of G2G_2; by availability the read returns, and since G2G_2 has received nothing, its state, and hence its answer, is what it would be had the write never happened: v0v_0. The write completed before the read began, so linearisability required v1v_1. ∎

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 xx, from time 0 to 1, and then reads xx 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 (N,R,W)=(3,1,3)(N, R, W) = (3, 1, 3), (4,2,2)(4, 2, 2), (4,2,3)(4, 2, 3), (7,4,4)(7, 4, 4) and (6,3,3)(6, 3, 3), 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: (3,1,3)(3, 1, 3) overlaps (4>34 > 3), but a write needs all three, so no replica may be down for writes. (4,2,2)(4, 2, 2) does not overlap (4=44 = 4): replicas 1, 2 and 3, 4 are disjoint quorums. (4,2,3)(4, 2, 3) overlaps, and works with one replica down. (7,4,4)(7, 4, 4) overlaps and works with three down. (6,3,3)(6, 3, 3) does not overlap. In general reads and writes both work with min⁡(N−R,N−W)\min(N - R, N - W) 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 t=199t = 199, and why is S5’s not 3? What does it become at t=260t = 260?

Solution

Solution of Exercise 26.4.

At t=199t = 199: 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 t=260t = 260, 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 i>i > 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 ii has viv_i votes, V=∑viV = \sum v_i, a read must collect rr votes and a write ww. Prove that if r+w>Vr + w > V, every read quorum meets every write quorum, and that if 2w>V2w > V, 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 AA and a write quorum BB were disjoint, their votes would add up to at least r+w>Vr + w > V, more than all the votes there are. In the same way two disjoint write quorums would hold at least 2w>V2w > V votes. The converse fails: one replica with 3 votes, V=3V = 3, r=w=1r = w = 1; then r+w≤Vr + w \le V, yet every quorum contains the only replica. Weights: the fast replica 3 votes, the two others 1 each, V=5V = 5, r=w=3r = w = 3. The fast replica alone is a read quorum, and r+w=6>5r + w = 6 > 5, 2w>52w > 5. 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 N=5N = 5 and p=0.01p = 0.01, compute the probability that a read and that a write are unavailable for R=2,W=4R = 2, W = 4, and compare with R=W=3R = W = 3. Which choice suits a catalogue that is read a thousand times for each write?

Solution

Solution of Exercise 26.8.

With p=0.01p = 0.01: for R=2R = 2, a read is unavailable only if 4 or 5 replicas are down, 5p4(1−p)+p5≈4.96×10−85p^4(1 - p) + p^5 \approx 4.96 \times 10^{-8}; for W=4W = 4, a write is unavailable if 2 or more are down, 1−(1−p)5−5p(1−p)4≈9.80×10−41 - (1 - p)^5 - 5p(1 - p)^4 \approx 9.80 \times 10^{-4}. With R=W=3R = W = 3 both are ≈9.85×10−6\approx 9.85 \times 10^{-6}. For a thousand reads per write, R=2,W=4R = 2, W = 4 refuses on average (1,000×4.96×10−8+9.80×10−4)/1,001≈1.0×10−6(1{,}000 \times 4.96 \times 10^{-8} + 9.80 \times 10^{-4})/1{,}001 \approx 1.0 \times 10^{-6} of the operations against 9.85×10−69.85 \times 10^{-6}, 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, R=2,W=4R = 2, W = 4 suits better. A test checks the probabilities.

Exercise 26.9 ★★

A leader LL of election term tt commits an entry ee of election term tt at index ii, stored by a majority. Prove that no server whose log lacks ee can be elected leader of election term t+1t + 1. Where does the proof use that ee has LL’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 MM be the majority storing ee, and CC a server lacking ee that asks for votes in election term t+1t + 1. Its votes form a majority, which meets MM in some server vv. Since CC’s election is the first of election term t+1t + 1 to succeed, no log holds an entry of election term t+1t + 1, and vv’s last entry has election term tt, since vv stores ee. If CC’s last entry has an election term below tt, vv’s log is more up to date and vv refuses. If CC’s last entry has election term tt, it was created by LL, the only leader of tt, at some index jj; by log matching CC’s log equals LL’s up to jj, and since CC lacks ee, j<ij < i; vv’s log has length at least i>ji > j with the same last election term, so it is more up to date and vv refuses. Either way CC cannot gather a majority. The proof uses ee’s election term to know that vv’s last entry has election term tt, at least that of CC’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 NN servers meet. A server becomes leader of election term tt only with the votes of a majority for tt, its own included. Each server records, with its current election term, the candidate it voted for, and grants a vote for tt only if it has not voted for another candidate in tt: it votes at most once per election term. If two servers became leaders of tt, their majorities would share a server that voted for both in tt, 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: max⁡\max is commutative, associative and idempotent. The merged state is the entrywise maximum, and an entrywise operation inherits these three properties from max⁡\max. Replica rr’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 rr everywhere is the maximum of its copies, replica rr’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 p=0.01p = 0.01, independently of the others.

Part I — What the catalogue needs.

  1. A reader searches for a title. Which consistency model is enough for a search, and why?
  2. 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?
  3. A reader reserves a book and reloads the page. What must the store guarantee for the reader to see the reservation, at the least?
  4. A librarian adds a book and then a note about it. Which model guarantees that nobody sees the note without the book?
  5. Could the number of reservations of a book be a CRDT counter? What about the reservation itself?
  6. Sum up the catalogue’s needs in one sentence for each of searching and reserving.

Part II — Quorums.

  1. With N=5N = 5, which pairs (R,W)(R, W) make every read quorum meet every write quorum?
  2. Take R=W=3R = W = 3. Can a reservation be read stale right after it is confirmed?
  3. Why do overlapping quorums alone not prevent two readers from both reserving the last copy?
  4. Where should the replicas a Brenmoor reader’s read reaches be, for a fast read, and is that enough for overlap?
  5. What does R=1R = 1, W=5W = 5 give for searches and for reservations?
  6. Which choice would you make for the catalogue, and why?

Part III — Availability.

  1. Write the probability that a write is unavailable for N=5N = 5, W=3W = 3, as a sum.
  2. Compute it, and compare with 10p310p^3.
  3. Compute it for W=5W = 5, and compare with 5p5p.
  4. The link between Kelsford and the other towns fails, and Kelsford’s two replicas are cut off. Which side can still write with W=3W = 3?
  5. A failure of the Brenmoor building takes both its replicas down at once. Why does the formula of question 13 no longer apply?
  6. How should five replicas be spread among the three towns so that one town’s loss leaves a majority?

Part IV — Raft or quorums.

  1. With the catalogue on Raft, how many servers must be up for reservations to continue?
  2. Under Raft, what happens to reservations made at a cut-off leader, as S5’s commands in Output 26.5?
  3. What do Raft’s reservations give that quorum writes with version numbers do not?
  4. What does Raft cost in messages and in waiting for each reservation?
  5. During a partition, which of searching and reserving should stay available, and which should stop? Name the theorem that forces the choice.
  6. Sum up: give the probability that a reservation is refused because too few replicas are up with W=3W = 3, and with W=5W = 5.
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 R+W≥6R + W \ge 6: (1,5)(1, 5), (2,4)(2, 4), (3,3)(3, 3), (4,2)(4, 2), (5,1)(5, 1), 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, 10−1010^{-10}. Every reservation must reach all five and fails about 4.9 % of the time, at every failure of any town.

12. Searches with R=1R = 1 and no ordering; reservations through Raft, which orders them, or quorums with R=W=3R = W = 3 at the least.

13. ∑d=35(5d)pd(1−p)5−d=10p3(1−p)2+5p4(1−p)+p5\sum_{d=3}^{5} \binom{5}{d} p^d (1 - p)^{5 - d} = 10p^3(1 - p)^2 + 5p^4(1 - p) + p^5.

14. 9.8506×10−69.8506 \times 10^{-6} (Output 26.2), close to 10p3=10−510p^3 = 10^{-5}: three replicas down dominates.

15. 1−0.995≈0.049011 - 0.99^5 \approx 0.04901, close to 5p=0.055p = 0.05: 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 p2p^2.

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 W=3W = 3, a reservation finds too few replicas with probability 9.85×10−69.85 \times 10^{-6}, about one in 100,000; with W=5W = 5, 0.0490.049, about one in 20: three replicas out of five are five thousand times more available than five.

本章定义的术语

在术语表中查看全部 1050 个术语