13 Distributed Consensus (分布式共识)
看清 Raft 用”强 leader”把共识拆成三个可以分别推理的子问题(选举、复制、安全),并理解为什么提交规则里那个 term 检查不能省——省掉之后系统在绝大多数时间里看起来完全正常,只在特定故障序列下丢数据。最后用一个真实的分区实验把这条安全性跑出来。
English: See how a strong leader splits consensus into three separately-reasoned problems, and why the term check in the commit rule cannot be dropped: omit it and the system looks correct in almost every run, losing data only under a specific failure sequence. Then watch a real partition experiment exercise that guarantee.
13.1 共识承诺了什么 / What consensus actually promises
一个共识协议要让一组节点对”日志里第 n 条是什么”达成一致,同时满足三条:
| 性质 | 含义 | 违反的后果 |
|---|---|---|
| 一致性(agreement) | 没有两个节点在同一位置提交不同的命令 | 数据分叉 |
| 有效性(validity) | 被提交的命令必须是某个客户端真实提出过的 | 凭空产生数据 |
| 终止性(termination) | 只要多数节点存活且能通信,就一定能推进 | 系统卡死 |
前两条是安全性(safety),任何时候都不能违反;第三条是活性(liveness),只在”多数派可用”的前提下承诺。这个区分是理解整个协议的关键:安全性没有”大多数时候”,一次违反就是永久的数据损坏。
13.2 强 leader:把问题拆开 / Strong leadership decomposes the problem
Paxos 允许任何节点提议,正确性证明因此要在”提议并发交错”的空间里展开。Raft 的选择是同一时刻只有一个 leader 接受客户端命令,日志只能从 leader 流向 follower。
这一条约束换来的是推理上的简化:
- 日志的唯一写入点是 leader,所以”两个节点在同一位置有不同条目”只可能由 leader 更替引起。
- 由这一点出发,全部安全性归结为一个问题:新 leader 必须拥有所有已提交的条目。
整个协议的设计——任期、投票限制、提交规则——都是为这一条服务。
English: One writer means the only way logs can disagree is a leader change, so all of safety reduces to: a new leader must already hold every committed entry.
13.3 任期:一个逻辑时钟 / Terms as a logical clock
每个任期(term)是一个单调递增的整数,一次选举对应一个新任期。任期的作用不是排序事件,而是让节点能判断”这条消息是否过时”:
- 收到更大 term 的请求 → 立刻退位,更新自己的 term
- 收到更小 term 的请求 → 拒绝,并告知对方自己的 term
- 同一 term 内每个节点最多投一票(
votedFor持久化)
第二条容易被忽略:拒绝旧 leader 的 AppendEntries 是防止”僵尸 leader”写入的唯一手段。分区恢复后,旧 leader 会继续发心跳,follower 必须靠 term 比较把它挡掉。
13.4 选举:随机化是必需的 / Randomization is not a nicety
如果所有 follower 的超时时间相同,一次 leader 失效会让它们同时发起选举,全部平票,然后同时超时、同时再选——这个循环可能持续很久(理论上无界)。
Raft 的解法是给每个节点的选举超时加随机抖动(典型 150–300 ms)。抖动让某个节点先超时、先拉到票、先成为 leader。
实测(4 次 RPC 完成一次选举):
[TestElection] 选出 leader=node 1, term=1, RPC 总数=4
3 个节点的集群,4 次 RPC 就完成了选举:1 次 RequestVote 广播给两个 follower(2 次 RPC),2 次返回,加上心跳。这个数字说明选举在最顺利的情况下代价很低——它不是瓶颈。
13.5 日志复制:两条必须记住的性质 / Two properties of replication
日志匹配性质:如果两个日志在某个 index 上的条目有相同的 term,那么该 index 之前的所有条目都相同。
这条性质靠 AppendEntries 的一致性检查维持:leader 在请求里带上”前一条的 index 和 term”,follower 只有在自己对应位置匹配时才接受。
这条检查是递归的:一次匹配保证了整段前缀匹配,所以”修日志”只需要从后往前找到第一个匹配点,然后覆盖其后全部内容。这就是新 leader 上台后要做的全部工作。
13.6 提交规则:那个不能省的 term 检查 / The commit rule
直觉版本的提交规则是:“条目被多数派复制,就可以提交。”
这个直觉是错的。 Raft 论文 §5.4.2 把理由写得很直接:
As described in Section 5.3, a leader knows that an entry from its current term is committed once that entry is stored on a majority of the servers. If a leader crashes before committing an entry, future leaders will attempt to finish replicating the entry. However, a leader cannot immediately conclude that an entry from a previous term is committed once it is stored on a majority of servers. Figure 8 illustrates a situation where an old log entry is stored on a majority of servers, yet can still be overwritten by a future leader.
解决办法同样是加条件,而不是加机制:
To eliminate problems like the one in Figure 8, Raft never commits log entries from previous terms by counting replicas. Only log entries from the leader’s current term are committed by counting replicas; once an entry from the current term has been committed in this way, then all prior entries are committed indirectly because of the Log Matching Property.
Figure 8 的图注给出了完整的五个阶段,值得逐字读——它是本章唯一需要”按时间顺序”理解的论证:
A time sequence showing why a leader cannot determine commitment using log entries from older terms. In (a) S1 is leader and partially replicates the log entry at index 2. In (b) S1 crashes; S5 is elected leader for term 3 with votes from S3, S4, and itself, and accepts a different entry at log index 2. In (c) S5 crashes; S1 restarts, is elected leader, and continues replication. At this point, the log entry from term 2 has been replicated on a majority of the servers, but it is not committed. If S1 crashes as in (d), S5 could be elected leader (with votes from S2, S3, and S4) and overwrite the entry with its own entry from term 3. However, if S1 replicates an entry from its current term on a majority of the servers before crashing, as in (e), then this entry is committed (S5 cannot win an election). At this point all preceding entries in the log are committed as well.
注意 (c) 与 (d) 之间的那句话:“replicated on a majority of the servers, but it is not committed”——多数派持有与已提交是两个不同的状态,这正是整节的论点。(e) 则给出出路:只要当前任期的条目被多数派复制,它连同之前的所有条目一起提交。
把图注翻译成我们的场景(对应上面那张任期图):
- (a) S1 在 term 2 当选 leader,把条目 X 复制到 S2——只有两个副本,还没到多数派,更没提交。
- (b) S1 崩溃。S5 拿到 S3、S4 和自己的票,在 term 3 当选;它的日志里没有 X,于是在 index 2 写了自己的一条。
- (c) S5 崩溃,S1 重启并重新当选(论文只说”重新当选”,没有给任期号——这一点常被转述成”term 4”,但原文不承担这个细节),继续复制。此时 X 已经复制到多数派,但未提交。
- (d) 如果 S1 此时崩溃,S5 可以靠 S2、S3、S4 的票当选——因为它的最后一条来自 term 3,比 S1 的 term 2 更新——然后用自己的条目覆盖 index 2 上的 X。
第 4 步是全部要害:X 在多数派上,却仍然可以被覆盖。如果实现按”多数派即可提交”处理,X 就成了一个”已提交却被覆盖”的条目,一致性直接破裂。
论文在图注末尾给了出路——(e):如果 S1 在崩溃前把当前任期的条目复制到多数派,那么这条被提交,同时它之前的所有条目也一并提交(因为日志匹配性质保证前缀一致)。这就是”当前任期的条目提交后,旧条目被顺带提交”的由来。
一个”已提交”的条目被覆盖,一致性直接破裂。
正确的规则因此多一个条件:
提交 index = N 当且仅当:
存在多数派已复制 log[N]
且 log[N].term == currentTerm
旧 term 的条目不能靠”被复制”直接提交,只能在当前 term 的某个条目被提交时被顺带提交(因为日志匹配性质保证前缀一致)。
English: A majority copy is not enough: Figure 8 shows an old-term entry that a majority holds and a later leader can still overwrite. Commit only current-term entries, and let the prefix follow.
13.7 分区实验:把安全性跑出来 / Partition, measured
一个 5 节点集群,把 leader 隔离到只剩 2 个节点的少数派:
[TestPartitionSafety] 分区前 leader=node 1
[TestPartitionSafety] 小分区=[1 2] 大分区=[0 3 4]
[TestPartitionSafety] 少数派 leader Start=true index=1 commitIndex=0
[TestPartitionSafety] 多数派新 leader=node 0
[TestPartitionSafety] 多数派 node 0 applied=[majority-write]
[TestPartitionSafety] 多数派 node 3 applied=[majority-write]
[TestPartitionSafety] 多数派 node 4 applied=[majority-write]
[TestPartitionSafety] 网络恢复,等待日志收敛…
[TestPartitionSafety] 日志已收敛:[{2 majority-write}]
逐行读:
少数派 leader Start=true index=1 commitIndex=0—— 这一行是整章最重要的数据。旧 leader 并没有立刻意识到自己已经失去多数派,它照常接受写入、分配了 index 1,但commitIndex停在 0。接受 ≠ 提交,这个区分在代码里体现为两个独立的字段。- 多数派选出新 leader(node 0),并在 term 2 提交了
majority-write。 - 网络恢复后日志收敛到
[{2 majority-write}]—— 少数派那条 index 1 的未提交条目被丢弃了。没有人”合并”它,也没有人报错:它从未被提交,因此从未被承诺。
第四行 {2 majority-write} 里的 2 是新 leader 的任期。旧条目 term 更小,在一致性检查中被覆盖。
这就是共识协议的真实语义:承诺只对已提交的内容生效,未提交的写入可能消失。客户端要拿到”已提交”的确认,必须等 leader 返回成功;仅”leader 接受了”不等于任何保证。
English: The isolated leader accepted a write and assigned it index 1 while commitIndex stayed 0. After healing, that entry vanished — never committed, never promised.
13.8 崩溃恢复靠持久化三件事 / Crash recovery needs exactly three fields
Raft 要求三个字段在响应 RPC 之前落盘:
| 字段 | 为什么必须持久化 |
|---|---|
currentTerm |
重启后若”忘记”自己已经投过票,可能在同一 term 投两次 → 双 leader |
votedFor |
同上,与 term 配对保证”一 term 一票” |
log[] |
已提交的条目不能丢;未提交的条目也必须保留(可能被新 leader 采用) |
最容易漏的是 votedFor:它看起来只是选举期的临时状态,但投票承诺必须跨越崩溃。一个重启后忘记投票记录的节点,会破坏整个选举的安全性。
commitIndex 反而不需要持久化——它可以从”多数派已复制到哪里”重新推导出来。
13.9 教学版与真实 Raft 的差距 / What this implementation leaves out
001 的实现通过了 MIT 6.824 的测试,但它的日志只在内存里、集群规模写死、读操作也走日志。生产系统必须补上这些:
| 机制 | 这里的实现 | 生产级 Raft | 真实系统为什么需要 |
|---|---|---|---|
| 日志增长 | 全量保留在内存 | 快照 + 日志截断(论文 §7) | 日志无限增长,重启时重放会慢到不可用 |
| 成员变更 | 固定 5 节点 | 联合共识(论文 §6) | 扩容、缩容、换机器是常态 |
| 线性一致读 | 读也走一次日志复制 | ReadIndex 或 lease read(论文 §8) | 每次读都写日志,读吞吐被写路径卡死 |
| 选举干扰 | 超时 + 随机抖动 | PreVote(Ongaro 博士论文) | 分区节点回归时 term 暴涨,打断健康的 leader |
| 批处理 | 一次一条 AppendEntries |
批量 + pipeline | 单条 RPC 的固定开销压住吞吐 |
| 客户端重试 | 无去重 | 会话 + 幂等键 | 网络重试会让同一条命令执行两次 |
这张表里最容易被低估的是快照。它看起来只是”清理磁盘”,实际上改变了协议的一部分:InstallSnapshot 是一个独立的 RPC,follower 收到它时要丢弃整个日志,而领导者在发送快照期间无法判断 follower 的实际进度。论文 §7 花了整整一节处理这个边界,因为”日志被截断后,一致性检查的 prevLogIndex 指向哪里”没有显然的答案。
第二容易被低估的是 PreVote。它不在 USENIX 论文里,是后来在实践中补的:一个被分区很久的节点,term 会不断自增;网络恢复时它带着巨大的 term 发起选举,健康 leader 被迫退位,集群抖动一次。PreVote 的做法是”先问一圈有没有人愿意选我,再真正增加 term”——用一次额外的 RPC 换掉一次不必要的 leader 更替。
English: The two omissions that bite hardest are snapshots and PreVote. Snapshots are not just disk cleanup:
InstallSnapshotis a separate RPC that discards the follower’s log, and the leader cannot tell how far along the follower really is. PreVote is not in the paper at all — it was added in practice so a long-partitioned node cannot derail a healthy leader by returning with an inflated term.
13.10 Fallacies and Pitfalls (常见误解)
这正是 Figure 8 的陷阱。旧 term 的条目即使被多数派持有,也可能被后续 leader 覆盖——因为新 leader 的选举资格只看”日志是否足够新”,不看”条目是否曾被多数派复制”。必须加 log[N].term == currentTerm。
English: A majority copy is not a commit. Old-term entries can still be overwritten; only current-term entries may be committed directly.
分区实验里旧 leader 的 Start 返回了 true、分配了 index,但 commitIndex 是 0。客户端如果拿”leader 接受了”当成功,就会以为数据已落定,而这条数据后来消失了。只有 commit 之后的响应才是承诺。
English: Accepted is not committed; a partitioned leader keeps accepting writes it can never commit.
分区恢复后,旧 leader 仍在按自己的节奏发心跳。follower 若不比较 term 就接受,会把日志回退到旧版本。每次 RPC 都要先比较 term,这是唯一能挡住僵尸 leader 的地方。
English: Zombie leaders keep sending heartbeats; only a term comparison stops them.
所有节点同时超时、同时竞选、全部平票,然后同时再次超时。这个循环在理论上没有上界。Raft 用 150–300 ms 的随机区间把”同时”打散——没有抖动,协议不会崩溃,但可能长时间无法推进。
English: Without jitter, split votes can repeat indefinitely; the protocol stays safe but stops making progress.
commitIndex 也持久化,却漏掉 votedFor
两者刚好相反:commitIndex 可以安全地重新推导,votedFor 必须落盘。持久化错字段,会在崩溃恢复后产生双投票。
English: Persist term, vote and log; commitIndex can be recomputed. Getting this backwards breaks election safety after a crash.
13.11 Self-Check (自测题)
- 为什么 Raft 的安全性可以归结为”新 leader 拥有所有已提交条目”这一条?
- 任期(term)解决了什么问题?如果去掉 term,只用心跳超时会怎样?
- Figure 8 的场景里,X 在哪里”看起来”已经被提交了?为什么实际没有?
- 分区实验中,少数派 leader 为什么没有立即停止服务?
- 哪些状态必须持久化?为什么
commitIndex不必?
答案
- 因为日志唯一的写入点是 leader。任意两个日志若在同一 index 有不同条目,一定发生在 leader 更替前后;若新 leader 拥有所有已提交条目,它就不会覆盖它们,于是不一致不可能出现。
- term 提供”消息新旧”的判据,让节点能拒绝过期 leader 与过期请求。去掉 term 后,分区恢复时旧 leader 的心跳无法与现任 leader 的心跳区分,日志可能被回退,一致性破裂。
- 在第 4 步,X 已被多数派复制,从”副本数量”看已经满足提交条件。但它属于旧 term,而按正确规则只有当前 term 的条目才能直接提交;S5 的日志更长,可以在下一次选举中胜出并覆盖 X。
- 因为 leader 只根据”自己是否能联系到多数派”来判断,而这需要等待一次心跳超时。在超时之前它仍认为自己是合法 leader,于是继续接受写入——但无法推进
commitIndex。 - 必须持久化
currentTerm、votedFor、log[](以及快照)。commitIndex可以从日志与多数派状态重新推导,持久化它反而可能在恢复后与真实状态不一致。
13.12 Summary (本章小结)
Raft 用”同一时刻一个 leader”把共识拆成选举、复制、安全三块,从而让全部安全性归结为一条:新 leader 必须拥有所有已提交条目。任期提供消息新旧判据,随机超时提供活性,日志匹配性质让”修日志”只需找第一个匹配点。提交规则必须带 term 检查——多数派复制不足以保证安全,Figure 8 是反例。分区实验给出了最实用的结论:接受不等于提交,未提交的写入在 leader 更替后可能消失。
English: One leader at a time reduces safety to “the new leader holds every committed entry”. Terms judge staleness, jitter provides liveness, log matching localizes repair. Commit needs the term check because a majority copy can still be overwritten — and accepted is not committed.
13.13 参考来源 / Sources
- Diego Ongaro, John Ousterhout · In Search of an Understandable Consensus Algorithm (Extended Version) — USENIX ATC 2014。§5.4.2 是本章引用的原文出处,Figure 8 给出五个阶段的反例。 https://raft.github.io/raft.pdf
- Diego Ongaro · Consensus: Bridging Theory and Practice(博士论文)— PreVote 的完整论证,USENIX 论文中未收录。 https://web.stanford.edu/~ouster/cgi-bin/papers/OngaroPhD.pdf
- etcd-io/raft · Go 实现,生产环境的参考读法:快照、PreVote、ReadIndex 都有可对照的代码。 https://github.com/etcd-io/raft
正文中的节号与图号均按上列第一份文档(USENIX 扩展版)标注。转述与原文有出入,是一个应当被报告的缺陷。
English: Section and figure numbers follow the USENIX extended version above. A transcription error here is a bug worth reporting.