MIT 6.5840:Lecture 07 Raft (2)
本篇逐行译注 MIT 6.5840 Spring 2026 Lecture 7,覆盖日志 divergence 修复、election restriction、persistence、snapshot、log compaction 与 read-only operations。
MIT 6.5840:Lecture 07 Raft (2)
TL;DR
- 日志收敛:新 leader 通过
AppendEntries的前置日志检查,让 follower 删除冲突尾部,再接受 leader 的后续 entries。 - Election Restriction:candidate 的最后一条日志必须至少与投票者一样新,从而保证新 leader 包含所有可能已经 committed 的 entries。
- 持久化边界:
log[]、currentTerm和votedFor必须持久化;commitIndex、lastApplied和next/matchIndex[]可以重建,因此是 volatile state。 - Snapshot:service state 可以替代已经执行过的日志前缀;落后到 leader 日志起点之前的 follower,需要通过
InstallSnapshot追赶。 - 只读请求:Figure 2 与 Labs 中的
Get()也要进入 log 才能保证 linearizability;lease 是一种更快但更复杂的生产实现方案。
名词解释
| 名词 | 含义 | 本讲对应物 |
|---|---|---|
| Log divergence | replicas 的日志在同一 index 上出现不同 entries | leader 通过 AppendEntries 修复 |
| Election Restriction | 只给至少同样新的 candidate 投票 | 防止新 leader 丢失 committed entries |
| Persistent state | crash 后仍必须保留的 Raft state | log[]、currentTerm、votedFor |
| Snapshot | 某个 log index 执行完成时的 service state 副本 | 删除已执行日志前缀 |
| Log compaction | 用 snapshot 替代旧日志,缩短日志 | follower 落后时改用 InstallSnapshot |
| Linearizability | 每个 operation 看起来像在某个单一时刻原子发生 | stale read 不满足该性质 |
目录
| 章节 | 内容 |
|---|---|
| 版本与来源 | 固定 Lecture 7 源文件 |
| 原文逐行翻译 | 按 l-raft2.txt 顺序译注 |
| 机制小结 | divergence、persistence、snapshot 和 read-only request |
| 本篇验收 | 源行、图示和边界记录 |
版本与来源
- 课程版本:MIT 6.5840 Spring 2026。
- Lecture 源文件:l-raft2.txt,363 行,非空源行 314 行,SHA-256:
7ce04209e2215957af34137dc2d5fc507781a74f4ea44e2b89c428cbf52e3566。 - 配套论文:In Search of an Understandable Consensus Algorithm(Extended Version)。
- 课程日程:MIT 6.5840 Spring 2026 Schedule。
- 翻译边界:英文源行按原顺序保留,随后给出中文译文;Raft RPC、函数、字段、term、index、entry、command 和 URL 原样保留。
- 图片结论:本 Lecture 源文件没有独立图片文件;原文的
[diagram: ...]文字占位和日志 case 示意均按原位置保留。
原文逐行翻译
课程目标与日志 divergence
6.5840 2026 Lecture 7: Raft (2)
6.5840 2026 年 Lecture 7:Raft(2)。
Raft
Raft。
library to build replicated state machines
用于构建 replicated state machines 的 library。
tolerant to network partition
能够容忍 network partition。
automatic fail-over to a new leader/primary
能够自动 fail-over 到新的 leader/primary。
key idea: quorum
核心思想:quorum。
building block for large-scale distributed systems; examples:
它是 large-scale distributed systems 的 building block;例如:
Raft library is used in Etcd, a configuration service
Raft library 被用于 Etcd,一个 configuration service。
etcd in turn is used to build services (e.g., Kubernetes)
而 etcd 又被用来构建 services(例如 Kubernetes)。
Raft is used in CockroadDB, a sharded distributed database
Raft 被用于 CockroadDB,一个 sharded distributed database。
...and many others
……以及许多其他系统。
what do we want to ensure?
我们想确保什么?
if any server executes a given command in a log entry,
如果任意 server 执行了某个 log entry 中的给定 command,
then no server executes something else for that log entry
那么就不能有任何 server 针对这个 log entry 执行其他内容。
(Figure 3's State Machine Safety)
(Figure 3 的 State Machine Safety。)
why? if the servers disagree on the operations, then a
为什么?如果 servers 对 operations 意见不一致,那么一次
change of leader might change the client-visible state,
leader change 可能改变 client-visible state,
which violates our goal of mimicing a single server.
这就违反了“模拟单个 server”的目标。
example:
例子:
S0: 101 | 102
S0:101 | 102。
S1: 101 | 103
S1:101 | 103。
can't allow both to execute their 2nd log entries!
不能允许两者都执行各自的第 2 个 log entry!
Last lecture: election safety
上一讲:election safety。
a single leader per term
每个 term 只有一个 leader。
as long as the leader stays up:
只要 leader 仍然存活:
clients only interact with the leader
clients 只与 leader 交互。
clients don't see follower states or logs
clients 不会看到 follower 的 states 或 logs。
but, logs of replicas may diverge
但是,replicas 的 logs 可能 divergence。
made-up example in last lecture
上一讲中的虚构例子。
Today: repair log divergence, persistence, and compacting log
今天:修复 log divergence,讨论 persistence,并 compacting log。
*** topic: the Raft log (Lab 2B)
*** 主题:Raft log(Lab 2B)。
Rejoin3B 测试与日志覆盖
TestRejoin3B: one test that test log divergence
TestRejoin3B:一个测试 log divergence 的 test。
make RUN="-run Rejoin3B" raft1
make RUN="-run Rejoin3B" raft1。
what does the test do?
这个 test 做什么?
commits one entry
提交一个 entry。
disconnects old leader
断开 old leader。
old leader appends to its log (102 at index 2)
old leader 向自己的 log 追加内容(index 2 上是 102)。
new leader commits 103 at index 2
new leader 在 index 2 提交 103。
new leader disconnects and old leader connects
new leader 断开,old leader 连接回来。
the remaining follower becomes leader!
剩下的 follower 成为 leader!
old leader's log overwritten with new leader's log!
old leader 的 log 被 new leader 的 log 覆盖!
here is a trace for a correct implementation
下面是一份正确实现的 trace。
other traces are possible too
也可能出现其他 traces。
=== RUN TestRejoin3B
=== RUN TestRejoin3B。
Test (3B): rejoin of partitioned leader (reliable network)...
Test (3B): rejoin of partitioned leader (reliable network)...。
1 0: Start log {[{0 <nil>} {1 101}] 0}
1 0: Start log {[{0 <nil>} {1 101}] 0}。
2 1: append args Term 1 Leader 0 PrvLogIndex 0 PrvLogTerm 0 Entries [{T 1}] LeaderCommit 0
2 1: append args Term 1 Leader 0 PrvLogIndex 0 PrvLogTerm 0 Entries [{T 1}] LeaderCommit 0。
3 1: append log {[{0 <nil>} {1 101}] 0}
3 1: append log {[{0 <nil>} {1 101}] 0}。
4 2: append args Term 1 Leader 0 PrvLogIndex 0 PrvLogTerm 0 Entries [{T 1}] LeaderCommit 0
4 2: append args Term 1 Leader 0 PrvLogIndex 0 PrvLogTerm 0 Entries [{T 1}] LeaderCommit 0。
5 2: append log {[{0 <nil>} {1 101}] 0}
5 2: append log {[{0 <nil>} {1 101}] 0}。
test: leader 0 disconnect
test:leader 0 disconnect。
6 0: Start log {[{0 <nil>} {1 101} {1 102}] 0}
6 0: Start log {[{0 <nil>} {1 101} {1 102}] 0}。
7 0: Start log {[{0 <nil>} {1 101} {1 102} {1 103}] 0}
7 0: Start log {[{0 <nil>} {1 101} {1 102} {1 103}] 0}。
8 0: Start log {[{0 <nil>} {1 101} {1 102} {1 103} {1 104}] 0}
8 0: Start log {[{0 <nil>} {1 101} {1 102} {1 103} {1 104}] 0}。
9 2: Start log {[{0 <nil>} {1 101} {2 103}] 0}
9 2: Start log {[{0 <nil>} {1 101} {2 103}] 0}。
10 1: append args Term 2 Leader 2 PrvLogIndex 1 PrvLogTerm 1 Entries [{T 2}] LeaderCommit 1
10 1: append args Term 2 Leader 2 PrvLogIndex 1 PrvLogTerm 1 Entries [{T 2}] LeaderCommit 1。
11 1: append log {[{0 <nil>} {1 101} {2 103}] 0}
11 1: append log {[{0 <nil>} {1 101} {2 103}] 0}。
12 1: append args Term 2 Leader 2 PrvLogIndex 1 PrvLogTerm 1 Entries [{T 2}] LeaderCommit 1
12 1: append args Term 2 Leader 2 PrvLogIndex 1 PrvLogTerm 1 Entries [{T 2}] LeaderCommit 1。
13 1: append log {[{0 <nil>} {1 101} {2 103}] 0}
13 1: append log {[{0 <nil>} {1 101} {2 103}] 0}。
test: disconnect new leader and connect old leader
test:断开 new leader,连接 old leader。
14 0: Start log {[{0 <nil>} {1 101} {1 102} {1 103} {1 104} {1 104}] 0}
14 0: Start log {[{0 <nil>} {1 101} {1 102} {1 103} {1 104} {1 104}] 0}。
15 0: append args Term 3 Leader 1 PrvLogIndex 0 PrvLogTerm 0 Entries [{T 1} {T 2}] LeaderCommit 2
15 0: append args Term 3 Leader 1 PrvLogIndex 0 PrvLogTerm 0 Entries [{T 1} {T 2}] LeaderCommit 2。
16 0: append log {[{0 <nil>} {1 101} {2 103}] 0}
16 0: append log {[{0 <nil>} {1 101} {2 103}] 0}。
17 1: Start log {[{0 <nil>} {1 101} {2 103} {3 104}] 0}
17 1: Start log {[{0 <nil>} {1 101} {2 103} {3 104}] 0}。
18 0: append args Term 3 Leader 1 PrvLogIndex 2 PrvLogTerm 2 Entries [{T 3}] LeaderCommit 2
18 0: append args Term 3 Leader 1 PrvLogIndex 2 PrvLogTerm 2 Entries [{T 3}] LeaderCommit 2。
19 0: append log {[{0 <nil>} {1 101} {2 103} {3 104}] 0}
19 0: append log {[{0 <nil>} {1 101} {2 103} {3 104}] 0}。
test: connect all
test:connect all。
20 1: Start log {[{0 <nil>} {1 101} {2 103} {3 104} {3 105}] 0}
20 1: Start log {[{0 <nil>} {1 101} {2 103} {3 104} {3 105}] 0}。
21 0: append args Term 3 Leader 1 PrvLogIndex 3 PrvLogTerm 3 Entries [{T 3}] LeaderCommit 3
21 0: append args Term 3 Leader 1 PrvLogIndex 3 PrvLogTerm 3 Entries [{T 3}] LeaderCommit 3。
22 2: append args Term 3 Leader 1 PrvLogIndex 2 PrvLogTerm 2 Entries [{T 3} {T 3}] LeaderCommit 3
22 2: append args Term 3 Leader 1 PrvLogIndex 2 PrvLogTerm 2 Entries [{T 3} {T 3}] LeaderCommit 3。
23 0: append log {[{0 <nil>} {1 101} {2 103} {3 104} {3 105}] 0}
23 0: append log {[{0 <nil>} {1 101} {2 103} {3 104} {3 105}] 0}。
24 2: append log {[{0 <nil>} {1 101} {2 103} {3 104} {3 105}] 0}
24 2: append log {[{0 <nil>} {1 101} {2 103} {3 104} {3 105}] 0}。
draw timing diagram on board
在黑板上画出 timing diagram。
trace high lights
trace 的重点。
print statement in
print statement 位于:
Start:
Start:
when leader appends to log (Start log)
leader 向 log 追加时(Start log)。
AppendEntries handler:
AppendEntries handler:
request received (append args)
收到 request(append args)。
handler appends to log (append log)
handler 向 log 追加(append log)。
at line 1-5:
在第 1–5 行:
server 0 is leader and appends 101 to all servers
server 0 是 leader,并把 101 追加到所有 servers。
server 0 may deliver 101 to application, assuming it received the reply from 1 and 2
假设 server 0 收到了来自 1 和 2 的 reply,那么它可能把 101 交给 application。
at line 6 leader 0 is disconnected but append to its own log
第 6 行:leader 0 已断开,但仍向自己的 log 追加。
results in an election because other servers don't receive heartbeats
这会导致 election,因为其他 servers 收不到 heartbeats。
at line 9 server 2 becomes leader and appends 103 in index 2
第 9 行:server 2 成为 leader,并在 index 2 追加 103。
server 0 and server 1 have different logs
server 0 和 server 1 的 logs 不同。
at line 11 server 1 appends 103 in index 2
第 11 行:server 1 在 index 2 追加 103。
server 1 and 2 may send 103 to the app
server 1 和 2 可能把 103 发送给 app。
103 might commit
103 可能 commit。
so, leader 0 should definitely not deliver 102 to application in index 2
因此,leader 0 绝不能把 index 2 上的 102 交给 application。
it won't because it isn't on a majority of servers yet
它不会这样做,因为 102 还没有出现在 majority of servers 上。
at line 14 tester asks old leader 0 to start another attempt for 104
第 14 行:tester 要求 old leader 0 再次尝试以 104 开始。
doesn't work; 1 and 2 will reject the append request
这不会成功;1 和 2 会拒绝 append request。
at line 15, new leader for term 3 (server 1)
第 15 行:term 3 的 new leader(server 1)。
why new term? leader for term 2 is disconnected
为什么是 new term?因为 term 2 的 leader 已断开。
new leader forces 0 to agree on its log
new leader 强制 0 同意自己的 log。
server 0 forgets about some log entries
server 0 忘记了一些 log entries。
ok because they didn't commit
这是可以的,因为它们没有 commit。
why didn't server 0 become leader---it has a longer log
为什么 server 0 没有成为 leader——它的 log 明明更长。
line 20 and up
第 20 行及之后:
add 105 with all servers online
所有 servers online 时加入 105。
leader 1 in term 3 forces logs to be identical
term 3 中的 leader 1 强制所有 logs 相同。
each live follower deletes tail of log that differs from leader
每个存活的 follower 都删除与 leader 不同的 log 尾部。
then each live follower accepts leader's entries after that point
然后每个存活的 follower 接受 leader 在该位置之后的 entries。
now followers' logs are identical to leader's log
此时 followers 的 logs 与 leader 的 log 相同。
Election Restriction 与 committed entries
could new leader roll back committed entries from end of previous term?
new leader 会不会回滚前一个 term 末尾的 committed entries?
i.e. could a committed entry be missing from the new leader's log?
也就是说,一个 committed entry 会不会缺失于 new leader 的 log?
this would be a disaster -- old leader might have already said "yes" to a client
这将是一场灾难——old leader 可能已经对 client 说过“yes”。
so: Raft needs to ensure elected leader has all committed log entries
因此:Raft 必须确保当选的 leader 拥有所有 committed log entries。
why not elect the server with the longest log as leader?
为什么不选择 log 最长的 server 作为 leader?
it would overwrite 103 at 2, which could be committed by 1 and 2
因为它会覆盖 index 2 上的 103,而 103 可能已经被 1 和 2 commit。
who should be next leader?
谁应该成为 next leader?
end of 5.4.1 explains the "election restriction"
第 5.4.1 节末尾解释了“election restriction”。
RequestVote handler only votes for candidate who is "at least as up to date":
RequestVote handler 只会投票给“至少同样新”的 candidate:
candidate has higher term in last log entry, or
candidate 的最后一个 log entry 拥有更高的 term,或者
candidate has same last term and same length or longer log
candidate 的最后一个 term 相同,且 log 长度相同或更长。
so:
因此:
S1 and S2 won't vote for P0
S1 和 S2 不会投票给 P0。
S1 and S2 will vote for each other
S1 和 S2 会互相投票。
so only S1 or S2 can be leader, will force S0 to discard 102, 103, 104
所以只有 S1 或 S2 能成为 leader,并会迫使 S0 丢弃 102、103、104。
ok since those are not on majority -> not committed -> reply never sent to clients
这是可以的,因为它们不在 majority 上 → 没有 commit → reply 从未发送给 clients。
-> clients will resend the discarded commands
→ clients 会重新发送被丢弃的 commands。
the point:
要点:
"at least as up to date" rule ensures new leader's log contains
“至少同样新”规则确保 new leader 的 log 包含
all potentially committed entries
所有可能已经 committed 的 entries。
so new leader won't roll back any committed operation
因此 new leader 不会回滚任何 committed operation。
"a committed operation" has two meanings in 6.5840:
在 6.5840 中,“a committed operation” 有两种含义:
- the op cannot be lost, even due to (allowable) failures.
1)即使发生(允许的)failures,这个 op 也不能丢失。
in Raft: when a majority of servers persist it in their logs.
在 Raft 中:当 majority of servers 将它持久化到自己的 logs 中时。
this is the "commit point" (though see Figure 8).
这就是“commit point”(不过请参见 Figure 8)。
- the system knows the op is committed.
2)系统知道这个 op 已 committed。
in Raft: leader saw a majority in *current* term
在 Raft 中:leader 在 current term 看到了 majority。
again:
再强调一次:
we cannot reply "yes" to client before commit.
在 commit 之前,我们不能向 client 回复“yes”。
we cannot forget an operation that may have been committed.
我们不能忘记一个可能已经 committed 的 operation。
Figure 7 的选举问题
The Question (from last lecture)
问题(来自上一讲)。
figure 7, top server is dead; which can be elected?
Figure 7 中顶部的 server 已死;谁可以当选?
who could become leader in figure 7? (with top server dead)
Figure 7 中谁可能成为 leader?(顶部 server 已死。)
need 4 votes to become leader
成为 leader 需要 4 张 votes。
a: yes -- a, b, e, f
a:可以——a、b、e、f。
b: no -- b, f
b:不可以——b、f。
e has same last term, but its log is longer
e 拥有相同的 last term,但它的 log 更长。
c: yes -- a, b, c, e, f
c:可以——a、b、c、e、f。
d: yes -- a, b, c, d, e, f
d:可以——a、b、c、d、e、f。
e: no -- b, f
e:不可以——b、f。
f: no -- f
f:不可以——f。
why won't d prevent a from becoming leader?
为什么 d 不会阻止 a 成为 leader?
after all, d's log has higher term than a's log
毕竟,d 的 log 拥有比 a 的 log 更高的 term。
a does not need d's vote in order to get a majority
a 不需要 d 的 vote 就能获得 majority。
a does not even need to wait for d's vote
a 甚至不需要等待 d 的 vote。
why is Figure 7 analysis important?
为什么 Figure 7 的分析重要?
choice of leader determines which entries are preserved vs discarded
leader 的选择决定哪些 entries 被保留、哪些被丢弃。
critical: if service responded positively to a client,
关键在于:如果 service 对 client 作出了肯定响应,
it is promising not to forget!
它就承诺不会忘记!
must be conservative: if client could have seen a "yes",
必须采取保守策略:如果 client 可能 看到了“yes”,
leader change *must* preserve that log entry.
leader change 必须 保留该 log entry。
Election Restriction does this via majority intersection.
Election Restriction 通过 majority intersection 做到这一点。
why OK to discard e's last 4,4?
为什么可以丢弃 e 最后的 4、4?
why OK to (perhaps) preserve c's last 6?
为什么可以(或许)保留 c 最后的 6?
could client have seen a "yes" for them?
client 可能已经针对它们看到过“yes”吗?
更快地 rollback 日志
how to roll back quickly
如何快速 rollback。
the Figure 2 design backs up one entry per RPC -- slow!
Figure 2 的设计每次 RPC 只回退一个 entry——很慢!
lab tester may require faster roll-back
lab tester 可能要求更快的 roll-back。
paper outlines a scheme towards end of Section 5.3
论文在第 5.3 节末尾附近概述了一种方案。
no details; here's my guess; better schemes are possible
没有具体细节;下面是我的猜想;还可以有更好的 schemes。
Case 1 Case 2 Case 3
Case 1 Case 2 Case 3
S1: 4 5 5 4 4 4 4
S1:4 5 5 4 4 4 4。
S2: 4 6 6 6 or 4 6 6 6 or 4 6 6 6
S2:4 6 6 6 或 4 6 6 6 或 4 6 6 6。
S2 is leader for term 6, S1 comes back to life, S2 sends AE for last 6
S2 是 term 6 的 leader,S1 恢复运行,S2 针对最后一个 6 发送 AE。
AE has prevLogTerm=6
AE 的 prevLogTerm=6。
rejection from S1 includes:
S1 的 rejection 包含:
XTerm: term in the conflicting entry (if any)
XTerm:冲突 entry 中的 term(如果存在)。
XIndex: index of first entry with that term (if any)
XIndex:拥有该 term 的第一条 entry 的 index(如果存在)。
XLen: log length
XLen:log length。
Case 1 (leader doesn't have XTerm):
Case 1(leader 没有 XTerm):
nextIndex = XIndex
nextIndex = XIndex。
Case 2 (leader has XTerm):
Case 2(leader 拥有 XTerm):
nextIndex = leader's last entry for XTerm
nextIndex = leader 中 XTerm 对应的最后一个 entry。
Case 3 (follower's log is too short):
Case 3(follower 的 log 太短):
nextIndex = XLen
nextIndex = XLen。
Persistence
*** topic: persistence (Lab 2C)
*** 主题:persistence(Lab 2C)。
what would we like to happen after a server crashes?
我们希望 server crash 之后发生什么?
Raft can continue with one missing server
Raft 可以在缺少一个 server 的情况下继续运行。
but failed server must be repaired soon to avoid dipping below a majority
但必须尽快 repair failed server,避免可用节点数跌破 majority。
two repair strategies:
有两种 repair strategies:
- replace with a fresh (empty) server
- 用一个新的(空的)server 替换。
requires transfer of entire log (or snapshot) to new server (slow)
这要求把整个 log(或 snapshot)传输给 new server(很慢)。
we must support this, in case failure is permanent
我们必须支持这种方式,以应对永久性 failure。
- or reboot crashed server, re-join with state intact, catch up
- 或 reboot crashed server,在 state 完整的情况下重新加入并追赶进度。
requires state that persists across crashes
这要求 state 能够跨 crash 持久存在。
we must support this, for simultaneous power failure
我们必须支持这种方式,以应对 simultaneous power failure。
let's talk about the second strategy -- persistence
下面讨论第二种 strategy——persistence。
if a server crashes and restarts, what must Raft remember?
如果 server crash 后 restart,Raft 必须记住什么?
Figure 2 lists "persistent state":
Figure 2 列出了“persistent state”:
log[], currentTerm, votedFor
log[]、currentTerm、votedFor。
a Raft server can only re-join after restart if these are intact
Raft server 只有在这些 state 完整的情况下,才能在 restart 后重新加入。
thus it must save them to non-volatile storage
因此必须把它们保存到 non-volatile storage。
non-volatile = disk, SSD, battery-backed RAM, &c
non-volatile = disk、SSD、battery-backed RAM 等。
save after each point in code that changes non-volatile state
在代码中每个改变 non-volatile state 的位置之后保存,
or before sending any RPC or RPC reply
或者在发送任何 RPC 或 RPC reply 之前保存。
why log[]?
为什么是 log[]?
if a server was in leader's majority for committing an entry,
如果一个 server 属于 leader 用来 commit 某个 entry 的 majority,
must remember entry despite reboot, so next leader's
那么即使 reboot,它也必须记住该 entry,这样 next leader 的
vote majority includes the entry, so Election Restriction ensures
vote majority 才会包含该 entry,而 Election Restriction 会确保
new leader also has the entry.
new leader 也拥有该 entry。
why votedFor?
为什么是 votedFor?
to prevent a client from voting for one candidate, then reboot,
为了防止一个 client 投票给某个 candidate,随后 reboot,
then vote for a different candidate in the same term
然后又在同一个 term 中投票给另一个 candidate。
could lead to two leaders for the same term
否则可能导致同一个 term 中出现两个 leaders。
why currentTerm?
为什么是 currentTerm?
avoid following a superseded leader.
避免跟随一个已经被 superseded 的 leader。
avoid voting in a superseded election.
避免在已经被 superseded 的 election 中投票。
some Raft state is volatile
Raft 的一些 state 是 volatile 的。
commitIndex, lastApplied, next/matchIndex[]
commitIndex、lastApplied、next/matchIndex[]。
why is it OK not to save these?
为什么不保存这些也可以?
persistence is often the bottleneck for performance
persistence 经常是 performance 的 bottleneck。
a hard disk write takes 10 ms, SSD write takes 0.1 ms
一次 hard disk write 需要 10 ms,SSD write 需要 0.1 ms。
so persistence limits us to 100 to 10,000 ops/second
因此 persistence 把吞吐限制在每秒 100 到 10,000 个 ops。
(the other potential bottleneck is RPC, which takes << 1 ms on a LAN)
(另一个潜在 bottleneck 是 RPC,在 LAN 上需要的时间远小于 1 ms。)
lots of tricks to cope with slowness of persistence:
有许多 tricks 可以应对 persistence 的缓慢:
batch many new log entries per disk write
每次 disk write 批量写入许多新的 log entries。
persist to battery-backed RAM, not disk
持久化到 battery-backed RAM,而不是 disk。
be lazy and risk loss of last few committed updates
采取 lazy 策略,并承担丢失最近少数 committed updates 的风险。
how does the service (e.g. k/v server) recover its state after a crash+reboot?
service(例如 k/v server)如何在 crash+reboot 后恢复 state?
easy approach: start with empty state, re-play Raft's entire persisted log
简单方法:从空 state 开始,re-play Raft 整个 persisted log。
lastApplied is volatile and starts at zero, so you may need no extra code!
lastApplied 是 volatile 的,并从 zero 开始,所以可能不需要额外代码!
this is what Figure 2 does
Figure 2 就是这样做的。
but re-play will be too slow for a long-lived system
但对一个长期运行的 system 来说,re-play 会太慢。
faster: use Raft snapshot and replay just the tail of the log
更快的方法:使用 Raft snapshot,只 replay log 的尾部。
Log compaction 与 Snapshots
*** topic: log compaction and Snapshots (Lab 2D)
*** 主题:log compaction 和 Snapshots(Lab 2D)。
problem:
问题:
log will get to be huge -- much larger than state-machine state!
log 会变得巨大——远大于 state-machine state!
will take a long time to re-play on reboot or send to a new server
在 reboot 时 re-play,或把它发送给 new server,都需要很长时间。
luckily:
幸运的是:
a server doesn't need both the complete log and the service state
server 不需要同时拥有完整 log 和 service state。
the executed part of the log is captured in the state
log 中已经执行的部分被 state 捕获。
clients only see the state, not the log
clients 只能看到 state,看不到 log。
service state usually much smaller, so let's keep just that
service state 通常小得多,所以只保留它。
what log entries can't a server discard?
哪些 log entries 是 server 不能 discard 的?
committed but not yet executed
已经 committed 但尚未 executed 的。
not yet known if committed
尚不知道是否 committed 的。
solution: service periodically creates persistent "snapshot"
解决方案:service 定期创建 persistent “snapshot”。
[diagram: service state, snapshot on disk, raft log (in mem, on disk)]
[diagram:service state、disk 上的 snapshot、raft log(in mem、on disk)。]
copy of service state as of execution of a specific log entry.
它是执行到某个特定 log entry 时的 service state 副本。
e.g. k/v table.
例如 k/v table。
service hands snapshot to Raft, with last included log index.
service 把 snapshot 和其中包含的最后一个 log index 一起交给 Raft。
Raft persists its state and the snapshot.
Raft 持久化自己的 state 和 snapshot。
Raft then discards log before snapshot index.
然后 Raft 丢弃 snapshot index 之前的 log。
every server snapshots (not just the leader).
每个 server 都创建 snapshot(不只是 leader)。
what happens on crash+restart?
crash+restart 时会发生什么?
service reads snapshot from disk
service 从 disk 读取 snapshot。
Raft reads persisted log from disk
Raft 从 disk 读取 persisted log。
Raft sets lastApplied to snapshot's last included index
Raft 把 lastApplied 设置为 snapshot 的 last included index。
to avoid re-applying already-applied log entries
以避免重新 apply 已经 apply 过的 log entries。
problem: what if follower's log ends before leader's log starts?
问题:如果 follower 的 log 在 leader 的 log 开始之前就结束了,怎么办?
because follower was offline and leader discarded early part of log
这是因为 follower 曾经 offline,而 leader 丢弃了 log 的早期部分。
nextIndex[i] will back up to start of leader's log
nextIndex[i] 会回退到 leader 的 log 起点。
so leader can't repair that follower with AppendEntries RPCs
因此 leader 无法使用 AppendEntries RPCs 修复该 follower。
thus the InstallSnapshot RPC
所以需要 InstallSnapshot RPC。
philosophical note:
哲学层面的说明:
state is often equivalent to operation history
state 往往等价于 operation history。
one or the other may be better to store or communicate
存储或传输其中一种,可能比另一种更合适。
we'll see examples of this duality later in the course
课程后面会看到这种 duality 的例子。
practical notes:
实践层面的说明:
Raft's snapshot scheme is reasonable if the state is small
如果 state 很小,Raft 的 snapshot scheme 是合理的。
for a big DB, e.g. if replicating gigabytes of data, not so good
但对于 big DB,例如复制 gigabytes 的数据,就不太好了。
slow to create and write entire DB to disk
创建整个 DB 并将其写入 disk 很慢。
perhaps service data should live on disk in a B-Tree
也许 service data 应该以 B-Tree 的形式直接位于 disk 上。
no need to explicitly snapshot, since on disk already
因为数据已经在 disk 上,所以不需要显式创建 snapshot。
dealing with lagging replicas is hard, though
不过,处理 lagging replicas 很困难。
leader should save the log for a while
leader 应该暂时保存 log,
or remember which parts of state have been updated
或者记录 state 的哪些部分被更新过。
Read-only operations
*** read-only operations (end of Section 8)
*** read-only operations(第 8 节末尾)。
Q: does the Raft leader have to commit read-only operations in
问:Raft leader 是否必须把 read-only operations commit 到
the log before replying? e.g. Get(key)?
log 中,然后才能 reply?例如 Get(key)?
that is, could the leader respond immediately to a Get() using
也就是说,leader 能否利用
the current content of its key/value table?
当前 key/value table 的内容立即响应 Get()?
A: no, not with the scheme in Figure 2 or in the labs.
答:不能,使用 Figure 2 或 Labs 中的 scheme 都不行。
suppose S1 thinks it is the leader, and receives a Get(k).
假设 S1 认为自己是 leader,并收到一个 Get(k)。
it might have recently lost an election, but not realize,
它可能刚刚输掉一次 election,却没有意识到这一点,
due to lost network packets.
因为 network packets 丢失了。
the new leader, say S2, might have processed Put()s for the key,
new leader,比如 S2,可能已经处理了针对该 key 的 Put()s,
so that the value in S1's key/value table is stale.
因此 S1 的 key/value table 中的 value 已经 stale。
serving stale data is not linearizable; it's split-brain.
提供 stale data 不满足 linearizable;这就是 split-brain。
so: Figure 2 requires Get()s to be committed into the log.
所以:Figure 2 要求把 Get()s commit 到 log 中。
if the leader is able to commit a Get(), then (at that point
如果 leader 能够 commit 一个 Get(),那么(在 log 中的那个时刻,
in the log) it is still the leader. in the case of S1
)它仍然是 leader。对于上面的 S1 情况,
above, which unknowingly lost leadership, it won't be
它在不知情地失去 leadership 后,不会
able to get the majority of positive AppendEntries replies
获得 commit 所需的 majority positive AppendEntries replies,
required to commit the Get(), so it won't reply to the client.
因此无法 commit 这个 Get(),也就不会 reply 给 client。
but: many applications are read-heavy. committing Get()s
但是:许多 applications 是 read-heavy 的。commit Get()s
takes time. is there any way to avoid commit
需要时间。有没有办法避免为
for read-only operations? this is a huge consideration in
read-only operations 执行 commit?这是
practical systems.
practical systems 中一个非常重要的考虑因素。
idea: leases
思路:leases。
modify the Raft protocol as follows
按如下方式修改 Raft protocol:
define a lease period, e.g. 5 seconds
定义一个 lease period,例如 5 秒。
after each time the leader gets an AppendEntries majority,
每次 leader 获得 AppendEntries majority 后,
it is entitled to respond to read-only requests for
它都有权在一个 lease period 内响应 read-only requests,
a lease period without adding read-only requests
而无需把 read-only requests 加入
to the log, i.e. without sending AppendEntries.
log,也就是无需发送 AppendEntries。
a new leader cannot execute Put()s until previous lease period
new leader 不能执行 Put()s,直到前一个 lease period
has expired
过期为止。
so followers keep track of the last time they responded
因此 followers 记录自己上次响应
to an AppendEntries, and tell the new leader (in the
AppendEntries 的时间,并将其告知 new leader(在
RequestVote reply).
RequestVote reply 中)。
result: faster read-only operations, still linearizable.
结果:更快的 read-only operations,同时仍然 linearizable。
note: for the Labs, you should commit Get()s into the log;
注意:对于 Labs,应当把 Get()s commit 到 log 中;
don't implement leases.
不要实现 leases。
in practice, people are often (but not always) willing to live with stale
实践中,人们经常(但并不总是)愿意接受 stale
data in return for higher performance
data,以换取更高的 performance。
https://decentralizedthoughts.github.io/2020-12-12-raft-liveness-full-omission/
https://decentralizedthoughts.github.io/2020-12-12-raft-liveness-full-omission/
机制小结
1. 日志如何收敛
AppendEntries 同时承担 heartbeat、日志一致性检查和日志复制三种职责。leader 通过 prevLogIndex / prevLogTerm 找到双方日志重新一致的位置;follower 删除冲突尾部后,接受 leader 的后续 entries。论文中的 election restriction 又保证新 leader 不会把已经可能 commit 的 entry 覆盖掉。
2. 两个“committed”的语义
“日志已经被多数节点持久化”是不会丢失的 commit point;“leader 已经在 current term 看到 majority”是系统可以安全知道该 operation committed 的条件。实现中不能在前者成立前向 client 回复成功,也不能因为后者尚未被 leader 观察到就错误地忘记一个潜在 committed entry。
3. Persistence、replay 与 snapshot
log[]、currentTerm、votedFor 决定 crash 后能否安全重返协议,因此必须持久化。状态机可以从完整日志 replay,但长期系统需要 snapshot 来替代已执行日志前缀;如果 follower 已经落后到 leader 当前日志起点之前,就必须使用 InstallSnapshot。
4. Read-only request 的一致性边界
一个失去 leadership 但尚未察觉的 server 可能仍然持有 stale state。直接从它的 key/value table 返回 Get() 会违反 linearizability。因此教学版本把 Get() 也提交到 log;生产系统可以使用 lease 等协议优化,但需要额外处理时间、选举和时钟假设。
本篇验收
- [x] 官方
l-raft2.txt已固定:363 行、308 个非空源行,SHA-256 与来源记录一致。 - [x] 源文本的非空行按原顺序逐行保留,中文译文紧随对应英文源行。
- [x]
TestRejoin3B的命令、trace、日志 entries、term/index 和关键时序均保留。 - [x]
[diagram: service state, snapshot on disk, raft log (in mem, on disk)]原位置保留;源文件没有独立图片可嵌入。 - [x]
AppendEntries、RequestVote、InstallSnapshot、字段名、代码命令和 URL 保留原样。 - [ ] Lecture 7 的中文译文仍建议进行一次人工术语审校;自动审计只验证源文覆盖与顺序,不证明翻译语义正确。
评论 (0)