目录
正在加载目录…
正在阅读专栏 分布式共识系统专栏 第 2 篇 · 共 59 篇 · 3%

分布式共识与复制状态机

发布于 2026-09-21 10:04 · 最后编辑于 2026-09-21 10:04 · 版本 v1 · 字数 8,516 · 预计阅读 18 分钟 👁 38 次阅读

分布式共识与复制状态机

共识不是让所有节点“同时写入”,而是让它们对同一串命令达成一致,并按相同顺序执行这串命令。

TL;DR

  • 共识解决的问题:多个节点可能崩溃、丢包或暂时无法通信,但仍要对已提交的命令保持一致。
  • Raft 的核心产物:一个由多数节点确认的 replicated log,而不是某个单独的数据库表。
  • 复制状态机的关键:所有副本看到相同日志、按相同顺序执行相同命令,因此得到相同状态。
  • 多数派边界:多数节点可通信时可以继续推进;没有多数派时必须停止提交,但不能返回错误结果。
  • 本篇实现目标:定义 Raft 与上层服务之间的接口,为后续 3A–3D 实现建立状态模型。

名词解释

名词含义本文中的具体对象
Replica保存服务副本的节点一个 Raft server
Replicated Log在多个副本间复制的命令序列Raft 的 log entries
State Machine执行命令并产生状态的程序KV 表或计数器
Majority / Quorum超过半数的节点集合3 节点集群中的至少 2 节点
Linearizability每个操作看起来像在某个单一时刻原子发生Lab 4 KV 的一致性目标

目录

章节内容
原文逐行翻译Lab 3 简介、准备工作与接口的完整译文
问题:为什么需要共识单副本和多副本的故障差异
复制状态机模型日志、状态机和客户端的关系
Raft 的系统边界Raft 做什么、不做什么
多数派与进度故障下的安全性和活性
MIT Lab 3 的接口后续实现使用的最小 API
第一阶段实践建立 Go 实验环境和验收目标

原文逐行翻译

来源:本地 source/lab-raft1.html。HTML 的排版换行合并成完整句子,每句英文后紧跟中文;源码行号与块编号供核对。命令、代码和终端输出原样保留。下面的 PASS/FAIL 输出均为原文示例,不代表本机测试结果。

<!-- source: lab-raft1.html:27 block=0 -->

简介

Introduction

<!-- source: lab-raft1.html:29 block=1 -->

This is the first in a series of labs in which you'll build a fault-tolerant key/value storage system.

这是构建容错键值存储系统系列实验中的第一个。

In this lab you'll implement Raft, a replicated state machine protocol.

在本实验中,你将实现复制状态机协议 Raft。

In the next lab you'll build a key/value service on top of Raft.

下一个实验将基于 Raft 构建键值服务。

Then you will “shard” your service over multiple replicated state machines for higher performance.

随后,你会把服务分片到多个复制状态机上,以获得更高性能。

<!-- source: lab-raft1.html:37 block=2 -->

A replicated service achieves fault tolerance by storing complete copies of its state (i.e., data) on multiple replica servers.

复制服务通过在多个副本服务器上保存完整的状态副本(也就是数据副本),获得容错能力。

Replication allows the service to continue operating even if some of its servers experience failures (crashes or a broken or flaky network).

即使某些服务器出现故障,例如崩溃、网络中断或网络不稳定,复制仍使服务能够继续运行。

The challenge is that failures may cause the replicas to hold differing copies of the data.

难点在于,故障可能导致不同副本保存的数据不一致。

<!-- source: lab-raft1.html:47 block=3 -->

Raft organizes client requests into a sequence, called the log, and ensures that all the replica servers see the same log.

Raft 把客户端请求组织成一个称为日志的序列,并保证所有副本服务器看到相同的日志。

Each replica executes client requests in log order, applying them to its local copy of the service's state.

每个副本按照日志顺序执行客户端请求,将操作应用到本地服务状态副本。

Since all the live replicas see the same log contents, they all execute the same requests in the same order, and thus continue to have identical service state.

由于所有存活副本看到相同的日志内容,它们以相同顺序执行相同请求,因此继续保持相同的服务状态。

If a server fails but later recovers, Raft takes care of bringing its log up to date.

如果服务器发生故障后恢复,Raft 负责让它的日志追上最新状态。

Raft will continue to operate as long as at least a majority of the servers are alive and can talk to each other.

只要至少多数服务器存活并能互相通信,Raft 就能继续工作。

If there is no such majority, Raft will make no progress, but will pick up where it left off as soon as a majority can communicate again.

如果不存在这样的多数派,Raft 就不会取得进展;但一旦多数派重新能够通信,它就会从中断处继续。

<!-- source: lab-raft1.html:62 block=4 -->

In this lab you'll implement Raft as a Go object type with associated methods, meant to be used as a module in a larger service.

在本实验中,你将把 Raft 实现为一个带有相关方法的 Go 对象类型,用作更大服务中的模块。

A set of Raft instances talk to each other with RPC to maintain replicated logs.

一组 Raft 实例通过 RPC 相互通信,维护复制日志。

Your Raft interface will support an indefinite sequence of numbered commands, also called log entries.

Raft 接口要支持一个可以无限延伸的带编号命令序列,这些命令也称为日志条目。

The entries are numbered with index numbers.

条目使用索引编号。

The log entry with a given index will eventually be committed.

给定索引的日志条目最终会被提交。

At that point, your Raft should send the log entry to the larger service for it to execute.

届时,Raft 应把日志条目交给上层服务执行。

<!-- source: lab-raft1.html:73 block=5 -->

You should follow the design in the extended Raft paper, with particular attention to Figure 2.

你应该遵循 Raft 扩展论文中的设计,尤其要注意 Figure 2。

You'll implement most of what's in the paper, including saving persistent state and reading it after a node fails and then restarts.

你将实现论文中的大多数内容,包括保存持久化状态,以及节点故障重启后读取这些状态。

You will not implement cluster membership changes (Section 6).

本实验不实现第 6 节的集群成员变更。

<!-- source: lab-raft1.html:82 block=6 -->

This lab is due in four parts.

本实验分四部分提交。

You must submit each part on the corresponding due date.

每部分都必须在相应截止日期前提交。

<!-- source: lab-raft1.html:86 block=7 -->

开始实验

Getting Started

<!-- source: lab-raft1.html:88 block=8 -->

If you have done Lab 1, you already have a copy of the lab source code.

如果完成了 Lab 1,你已经拥有实验源码。

If not, you can find directions for obtaining the source via git in the Lab 1 instructions.

否则,可以在 Lab 1 的说明中找到使用 git 获取源码的方法。

<!-- source: lab-raft1.html:95 block=9 -->

We supply you with skeleton code src/raft1/raft.go.

我们提供了骨架代码 src/raft1/raft.go。

We also supply a set of tests, which you should use to drive your implementation efforts, and which we'll use to grade your submitted lab.

我们还提供一组测试,你应以这些测试推动实现;我们也会用它们为提交的实验评分。

The tests are in src/raft1/raft_test.go.

测试位于 src/raft1/raft_test.go。

<!-- source: lab-raft1.html:101 block=10 -->

When we grade your submissions, we will run the tests without the -race flag.

评分时,我们运行测试不会使用 -race 参数。

However, you should test with -race.

不过,你自己测试时应该启用 -race。

<!-- source: lab-raft1.html:105 block=11 -->

To get up and running, execute the following commands.

执行下面的命令开始实验。

Don't forget the git pull to get the latest software.

别忘了运行 git pull 获取最新代码。

<!-- source: lab-raft1.html:108 block=12 -->
text
$ cd ~/6.5840
$ git pull
...
$ cd src
$ make raft1
go build -race -o main/raft1d main/raft1d.go
cd raft1 && go test -v -race  
=== RUN   TestInitialElection3A
Test (3A): initial election (reliable network)...
Fatal: expected one leader, got none
        /Users/rtm/824-process-raft/src/raft1/test.go:151
        /Users/rtm/824-process-raft/src/raft1/raft_test.go:36
info: wrote visualization to /var/folders/x_/vk0xmxwn1sj91m89wsn5b1yh0000gr/T/porcupine-2242138501.html
--- FAIL: TestInitialElection3A (5.51s)
...
$
<!-- source: lab-raft1.html:127 block=13 -->

代码

The code

<!-- source: lab-raft1.html:127 block=14 -->

Implement Raft by adding code to raft1/raft.go.

通过向 raft1/raft.go 添加代码来实现 Raft。

In that file you'll find skeleton code, plus examples of how to send and receive RPCs.

该文件包含骨架代码,以及发送和接收 RPC 的示例。

<!-- source: lab-raft1.html:134 block=15 -->

Your implementation must support the following interface, which the tester and (eventually) your key/value server will use.

你的实现必须支持下面的接口,测试器以及之后实现的键值服务器会使用它。

You'll find more details in comments in raft.go and in raftapi/raftapi.go.

更多细节见 raft.go 和 raftapi/raftapi.go 中的注释。

<!-- source: lab-raft1.html:140 block=16 -->
go
// create a new Raft server instance:
rf := Make(peers, me, persister, applyCh)

// start agreement on a new log entry:
rf.Start(command interface{}) (index, term, isleader)

// ask a Raft for its current term, and whether it thinks it is leader
rf.GetState() (term, isLeader)

// each time a new entry is committed to the log, each Raft peer
// should send an ApplyMsg to the service (or tester).
type ApplyMsg

注释逐行译文:创建新的 Raft 服务器实例;开始对新日志条目达成一致;查询当前任期以及是否自认为 leader;每次新条目提交后,每个 Raft 节点都应向服务或测试器发送 ApplyMsg。

<!-- source: lab-raft1.html:154 block=17 -->

A service calls Make(peers,me,…) to create a Raft peer.

服务调用 Make(peers,me,…) 创建 Raft 节点。

The peers argument is an array of network identifiers of the Raft peers (including this one), for use with RPC.

peers 参数是所有 Raft 节点(包含当前节点)的网络标识符数组,用于 RPC 通信。

The me argument is the index of this peer in the peers array.

me 参数是当前节点在 peers 数组中的索引。

Start(command) asks Raft to start the processing to append the command to the replicated log.

Start(command) 请求 Raft 开始将命令追加到复制日志的流程。

Start() should return immediately, without waiting for the log appends to complete.

Start() 应立即返回,不能等待日志追加完成。

The service expects your implementation to send an ApplyMsg for each newly committed log entry to the applyCh channel argument to Make().

服务期望你的实现为每个新提交的日志条目发送一条 ApplyMsg,发送目标是传给 Make() 的 applyCh 通道。

<!-- source: lab-raft1.html:166 block=18 -->

raft.go contains example code that sends an RPC (sendRequestVote()) and that handles an incoming RPC (RequestVote()).

raft.go 包含发送 RPC 的示例 sendRequestVote(),以及处理收到的 RPC 的示例 RequestVote()。

Your Raft peers should exchange RPCs using the labrpc Go package (source in src/labrpc).

Raft 节点应使用 Go 的 labrpc 包交换 RPC,源码位于 src/labrpc。

The tester can tell labrpc to delay RPCs, re-order them, and discard them to simulate various network failures.

测试器可以让 labrpc 延迟、重排或丢弃 RPC,模拟各种网络故障。

While you can temporarily modify labrpc, make sure your Raft works with the original labrpc, since that's what we'll use to test and grade your lab.

虽然你可以临时修改 labrpc,但必须确保 Raft 能与原始 labrpc 配合工作,因为测试和评分使用的是原始版本。

Your Raft instances must interact only through RPC; for example, they are not allowed to communicate using shared Go variables or files.

Raft 实例之间只能通过 RPC 交互,例如不能使用共享 Go 变量或共享文件通信。

<!-- source: lab-raft1.html:181 block=19 -->

Subsequent labs build on this lab, so it is important to give yourself enough time to write solid code.

后续实验都建立在本实验之上,因此要留出足够时间,编写可靠的代码。

问题:为什么需要共识

MIT 6.5840 Lab 3 是一系列容错 Key/Value 存储实验的第一步。本实验实现 Raft,一个 replicated state machine protocol(复制状态机协议)。下一篇实验会在 Raft 之上构建 Key/Value 服务,再下一阶段会把服务切分到多个 replicated state machine 上,以提高性能。

一个 replicated service 通过在多个 replica server 上保存完整的状态副本来获得容错能力。即使部分服务器崩溃,或者网络变得不稳定、丢包,复制仍然可以让服务继续运行;真正困难的是,故障可能导致不同副本暂时保存不同的数据。

Raft 把客户端请求组织成一个叫作 log 的序列,并确保所有副本看到相同的 log。每个副本按照 log 顺序执行客户端请求,把请求应用到自己的本地状态机。由于所有仍然存活的副本看到的 log 内容和顺序都相同,它们最终会执行相同请求并得到相同状态。

如果某台服务器失败后恢复,Raft 会负责把它的 log 补齐。只要至少多数服务器存活且能够互相通信,Raft 就可以继续工作;如果不存在这样的多数派,Raft 不会推进,但多数派恢复通信后可以从之前的位置继续。

复制状态机模型

mermaid
sequenceDiagram
    participant C as Client
    participant L as Leader
    participant F1 as Follower 1
    participant F2 as Follower 2
    participant S as State Machine
    C->>L: command
    L->>F1: replicate log entry
    L->>F2: replicate log entry
    F1-->>L: acknowledge
    F2-->>L: acknowledge
    L->>S: apply committed entry
    S-->>C: result

上图表达的是实现上的分层:客户端提交的是 command,Raft 负责把 command 变成所有节点都认可的 log entry;只有 entry 被提交后,状态机才执行它。Raft 不直接理解 SET x=3 的业务含义,它只复制字节序列或命令对象。

最小的状态机可以是一个整数计数器:收到 INC 就加一。更接近数据库的状态机是 KV 表:收到 Put(k,v) 就更新键值,收到 Get(k) 则读取本地状态。对于写入命令,所有副本必须从同一条提交日志中执行;对于读取命令,还需要额外处理 Leader 是否拥有最新提交状态的问题。

Raft 的系统边界

Raft 负责什么

  • 通过选举产生 Leader。
  • 把 Leader 接收的命令复制到 Follower。
  • 判断某条日志是否已经被多数节点确认。
  • 将已提交日志按顺序交给上层状态机。
  • 在节点重启或落后时恢复、补齐和压缩日志。

Raft 不负责什么

  • 不定义 KV、表或 SQL 的业务语义。
  • 不替上层服务持久化业务状态;Raft 只处理自己的日志状态和快照接口。
  • 不自动提供客户端会话、请求去重和错误重试语义。
  • 不等于完整数据库;事务、索引、分片和查询执行属于上层服务。

这个边界很重要。若把数据库操作直接写进 Raft 核心,Raft 会同时承担协议、存储和业务逻辑,测试故障时很难判断错误来自协议还是状态机。MIT Lab 4 的设计就是让 KV 服务通过 raft.Start() 提交命令,再从 applyCh 接收已经提交的命令。

多数派与进度

设集群有 3 个节点:A、B、C。多数派大小是 2。

场景是否能提交新命令原因
A、B、C 都在线可以有 3 个节点可通信
A 故障,B、C 在线可以B、C 构成多数派
A、B 故障,C 单独在线不可以单节点不是多数派
A、B 与 C 网络分区只有 A、B 一侧可以A、B 仍有多数派

不能让没有多数派的一侧继续提交,是因为两个分区可能分别接受不同命令。例如 A、B 接受 set x=1,C 接受 set x=2;如果两侧都把命令当作已提交,恢复连接后就无法保证同一个日志位置只有一个值。

因此 Raft 的安全性和活性需要分开理解:

  • 安全性:不能让两个不同命令在同一个日志位置都被提交。
  • 活性:在多数派可通信时,新的命令最终能够被提交。
  • 没有多数派时牺牲活性,但不能牺牲安全性。

MIT Lab 3 的接口

在 Lab 3 中,Raft 作为 Go 对象嵌入更大的服务。每组 Raft 实例通过 RPC 维护复制日志,接口支持无限序列的带编号命令。某条日志最终提交后,Raft 通过 applyCh 把它交给上层服务执行。

原文给出的最小接口如下:

go
// create a new Raft server instance:
rf := Make(peers, me, persister, applyCh)

// start agreement on a new log entry:
rf.Start(command interface{}) (index, term, isleader)

// ask a Raft for its current term, and whether it thinks it is leader
rf.GetState() (term, isLeader)

// each time a new entry is committed to the log, each Raft peer
// should send an ApplyMsg to the service (or tester).
type ApplyMsg

接口语义是:

  • Make 创建一个 Raft peer;peers 是所有节点的网络标识,me 是当前节点下标。
  • Start(command) 请求 Raft 开始复制一条命令。它应立即返回,不应等待复制完成。
  • GetState() 返回当前 term 以及当前节点是否认为自己是 Leader。
  • 每当日志条目提交,Raft 都要向 applyCh 发送 ApplyMsg,由上层服务执行。

Raft 节点只能通过 RPC 互相通信,不能通过共享 Go 变量或共享文件绕过网络。实验中的 labrpc 会延迟、重排或丢弃 RPC,用来模拟故障;因此实现不能依赖可靠网络。

第一阶段实践

环境和代码入口

官方实验提供 src/raft1/raft.go 骨架代码和 src/raft1/raft_test.go 测试。官方建议使用 Go 的 race detector 测试,因为分布式节点和同一节点内的 goroutine 会并发访问状态。

bash
cd ~/6.5840
git pull
cd src
make raft1
go build -race -o main/raft1d main/raft1d.go
cd raft1 && go test -v -race

第一个可验证目标

第一阶段不要一开始就实现 KV、持久化和快照。先完成 3A:

  1. 定义 Raft 节点状态:Follower、Candidate、Leader。
  2. 增加 current term、投票对象和选举计时器。
  3. 实现 RequestVote RPC。
  4. 实现没有日志条目的 AppendEntries 心跳。
  5. 在没有故障时保持一个 Leader。
  6. 让旧 Leader 失效后,剩余多数派选出新 Leader。

3A 通过的证据不是“程序启动了”,而是选举测试在可靠网络、Leader 故障和多次选举场景下都通过,并且 race detector 没有报告数据竞争。目前 implementation/6.5840/src/raft1/raft.go 已完成这一步;下一篇会把 Raft 论文 Figure 2 拆开,明确每个字段、RPC 和状态转换,然后进入 3B 日志复制。

参考资料

← 返回列表
← 上一篇 分布式共识系统:从 Raft 到分布式 KV 下一篇 → Raft Figure 2 与 3A/3B 日志复制

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论