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

论文:Raft 可理解的共识算法(扩展版)

发布于 2026-09-21 10:07 · 最后编辑于 2026-09-21 18:15 · 版本 v2 · 字数 117,118 · 预计阅读 235 分钟 👁 29 次阅读

本篇逐段翻译 Diego Ongaro 与 John Ousterhout 的《In Search of an Understandable Consensus Algorithm(Extended Version)》;保留 2014 年扩展版 PDF 的页面图、公式、Figure、表格、脚注和参考文献,并把 Raft 论文与前面的课程讲义、Lab 实现对齐。

论文:Raft 可理解的共识算法(扩展版)

相关文章:分布式共识与复制状态机 · Raft Figure 2 与 3A-3B 日志复制 · TLA+ 与正确性验证 · 6.5840:Lecture 06 RSM and Raft 1

TL;DR

  • 论文解决的问题:为 replicated log 设计一个既实用又容易理解的 consensus algorithm,并以此替代 Paxos 作为系统构建和教学基础。
  • 核心拆分:Raft 将 consensus 拆成 leader election、log replication 和 safety,并用 stronger leader、randomized timers 与 joint consensus 减少需要考虑的状态。
  • 阅读边界:本文固定的是 2014 年 5 月 20 日发布的 Extended Version;它比会议版包含更多扩展材料。
  • 本篇状态:PDF 共 18 页;原始页面会以 2× 渲染图保留,译文已完成第 1–18 页,包含正文、Figure 图注、公式边界、Acknowledgments 和 References。
  • 术语原则:Raft、Paxos、consensus、replicated log、leader、follower、candidate、term、RPC、quorum、snapshot 和 joint consensus 等术语保留英文,不强行翻译。

名词解释

名词含义本文对应物
Consensus多个节点对一系列值达成一致的协议问题Raft
Replicated log多个 server 以相同顺序保存的 command 序列Raft log
State machine按 log 顺序执行 command 的确定性状态机课程 Lab 4 的 KV service
Strong leaderlog entry 主要从 leader 流向其他 server 的领导结构Raft 的 leader-based design
TermRaft 中用于区分任期和过期消息的逻辑时间Figure 2 的 currentTerm
Joint consensus成员变更期间同时要求两套 configuration 的 majoritySection 6

目录

章节内容
版本与来源固定 PDF、页数、尺寸和渲染附件
原文页面与逐段翻译按 PDF 页面顺序保留原页并翻译
论文机制索引读完全文后用于回连课程和实验
本篇验收当前页数、图件和翻译覆盖状态

版本与来源

  • 论文标题:In Search of an Understandable Consensus Algorithm (Extended Version)。
  • 作者与机构:Diego Ongaro、John Ousterhout,Stanford University。
  • 官方来源:Raft extended paper PDF;本地固定文件为 source/raft.pdf。
  • PDF 固定信息:18 页,每页 612×792 points;本地文件 SHA-256:5a5c679b6a7c88007faeff8c3eef19a77e9e5caa8bd7390922584fe8ecf0ce1f。
  • 发布日期:PDF 页脚注明 Published May 20, 2014。
  • 附件处理:每页渲染为 1224×1584 PNG,存放于 assets/31 Raft:可理解的共识算法(扩展版)/,在正文中以 600 宽度嵌入;PDF 中的 Figure、公式、灰色扩展标记、脚注和页面排版因此保留。
  • 翻译边界:PDF 的双栏排版换行不当作语义断句;以标题、段落、列表和图注为最小翻译单元。原始页面图是格式与图件的权威副本,文字译注是可检索的中文阅读层。

原文页面与逐段翻译

第 1 页:摘要、Introduction 与 Replicated state machines 开始

raft p01

标题与摘要

In Search of an Understandable Consensus Algorithm

寻找一种易于理解的共识算法。

(Extended Version)

(扩展版)

Diego Ongaro and John Ousterhout

Diego Ongaro 与 John Ousterhout。

Stanford University

Stanford University。

Abstract

摘要。

Raft is a consensus algorithm for managing a replicated log. It produces a result equivalent to (multi-)Paxos, and it is as efficient as Paxos, but its structure is different from Paxos; this makes Raft more understandable than Paxos and also provides a better foundation for building practical systems.

Raft 是一种用于管理 replicated log 的 consensus algorithm。它产生的结果与(multi-)Paxos 等价,效率也与 Paxos 相当,但结构不同于 Paxos;这使 Raft 比 Paxos 更容易理解,也为构建实际系统提供了更好的基础。

In order to enhance understandability, Raft separates the key elements of consensus, such as leader election, log replication, and safety, and it enforces a stronger degree of coherency to reduce the number of states that must be considered.

为了提升可理解性,Raft 将 consensus 的关键要素分开处理,例如 leader election、log replication 和 safety;同时它施加更强的 coherence 约束,以减少必须考虑的状态数量。

Results from a user study demonstrate that Raft is easier for students to learn than Paxos.

用户研究结果表明,学生学习 Raft 比学习 Paxos 更容易。

Raft also includes a new mechanism for changing the cluster membership, which uses overlapping majorities to guarantee safety.

Raft 还包含一种新的 cluster membership 变更机制:在变更期间使用相互重叠的 majorities 来保证 safety。

1 Introduction

Consensus algorithms allow a collection of machines to work as a coherent group that can survive the failures of some of its members.

Consensus algorithms 允许一组机器作为一个协调一致的群体工作,即使其中一部分成员发生故障,群体仍能继续存活。

Because of this, they play a key role in building reliable large-scale software systems.

因此,它们在构建可靠的大规模软件系统时发挥着关键作用。

Paxos [15, 16] has dominated the discussion of consensus algorithms over the last decade: most implementations of consensus are based on Paxos or influenced by it, and Paxos has become the primary vehicle used to teach students about consensus.

过去十年间,Paxos 一直主导着人们对 consensus algorithms 的讨论:大多数 consensus 实现都基于 Paxos 或受到它的影响,而 Paxos 也成为教授学生 consensus 的主要工具。

Unfortunately, Paxos is quite difficult to understand, in spite of numerous attempts to make it more approachable.

遗憾的是,尽管人们多次尝试让 Paxos 更容易接近,它仍然相当难以理解。

Furthermore, its architecture requires complex changes to support practical systems.

此外,为了支持实际系统,Paxos 的架构还需要进行复杂的改动。

As a result, both system builders and students struggle with Paxos.

结果是,系统构建者和学生都在 Paxos 面前遇到困难。

After struggling with Paxos ourselves, we set out to find a new consensus algorithm that could provide a better foundation for system building and education.

在亲自与 Paxos 周旋并经历困难之后,我们开始寻找一种新的 consensus algorithm,希望它能为系统构建和教学提供更好的基础。

Our approach was unusual in that our primary goal was understandability: could we define a consensus algorithm for practical systems and describe it in a way that is significantly easier to learn than Paxos?

我们的做法不同寻常,因为首要目标是 understandability:我们能否为实际系统定义一种 consensus algorithm,并用一种比 Paxos 容易得多的方式描述它?

Furthermore, we wanted the algorithm to facilitate the development of intuitions that are essential for system builders.

此外,我们希望这种 algorithm 能帮助系统构建者形成必不可少的直觉。

It was important not just for the algorithm to work, but for it to be obvious why it works.

重要的不只是 algorithm 能工作,还要让人一眼看出它为什么能工作。

The result of this work is a consensus algorithm called Raft.

这项工作的结果就是名为 Raft 的 consensus algorithm。

In designing Raft we applied specific techniques to improve understandability, including decomposition (Raft separates leader election, log replication, and safety) and state space reduction (relative to Paxos, Raft reduces the degree of nondeterminism and the ways servers can be inconsistent with each other).

在设计 Raft 时,我们采用了多种提升可理解性的具体技术,包括 decomposition(Raft 将 leader election、log replication 和 safety 分开)以及 state space reduction(相对于 Paxos,Raft 减少了 nondeterminism 的程度,也减少了 server 之间可能出现不一致的方式)。

A user study with 43 students at two universities shows that Raft is significantly easier to understand than Paxos: after learning both algorithms, 33 of these students were able to answer questions about Raft better than questions about Paxos.

一项在两所大学、由 43 名学生参加的用户研究显示,Raft 明显比 Paxos 更容易理解:学习过两种 algorithm 后,其中 33 名学生回答 Raft 相关问题的表现优于回答 Paxos 相关问题。

Raft is similar in many ways to existing consensus algorithms (most notably, Oki and Liskov’s Viewstamped Replication [29, 22]), but it has several novel features:

Raft 在许多方面与已有的 consensus algorithms 相似,尤其是 Oki 和 Liskov 的 Viewstamped Replication [29, 22];但它也有若干新颖特性:

Strong leader: Raft uses a stronger form of leadership than other consensus algorithms. For example, log entries only flow from the leader to other servers. This simplifies the management of the replicated log and makes Raft easier to understand.

Strong leader:Raft 使用了比其他 consensus algorithms 更强的 leadership 形式。例如,log entries 只从 leader 流向其他 server。这简化了 replicated log 的管理,也让 Raft 更容易理解。

Leader election: Raft uses randomized timers to elect leaders. This adds only a small amount of mechanism to the heartbeats already required for any consensus algorithm, while resolving conflicts simply and rapidly.

Leader election:Raft 使用 randomized timers 选出 leader。它只需在任何 consensus algorithm 都需要的 heartbeats 机制上增加少量内容,同时能够简单而快速地解决冲突。

Membership changes: Raft’s mechanism for changing the set of servers in the cluster uses a new joint consensus approach where the majorities of two different configurations overlap during transitions. This allows the cluster to continue operating normally during configuration changes.

Membership changes:Raft 改变 cluster 中 server 集合的机制采用了一种新的 joint consensus 方法:在 transition 期间,两套不同 configuration 的 majorities 相互重叠。这样,cluster 在 configuration changes 期间仍能正常运行。

We believe that Raft is superior to Paxos and other consensus algorithms, both for educational purposes and as a foundation for implementation.

我们认为,无论是用于教学,还是作为实现基础,Raft 都优于 Paxos 和其他 consensus algorithms。

It is simpler and more understandable than other algorithms; it is described completely enough to meet the needs of a practical system; it has several open-source implementations and is used by several companies; its safety properties have been formally specified and proven; and its efficiency is comparable to other algorithms.

它比其他 algorithms 更简单、更容易理解;论文对它的描述足够完整,能够满足实际系统的需要;它已有多个 open-source implementations,也被多家公司采用;它的 safety properties 已被形式化描述并证明;同时它的效率与其他 algorithms 相当。

The remainder of the paper introduces the replicated state machine problem (Section 2), discusses the strengths and weaknesses of Paxos (Section 3), describes our general approach to understandability (Section 4), presents the Raft consensus algorithm (Sections 5–8), evaluates Raft (Section 9), and discusses related work (Section 10).

本文其余部分将介绍 replicated state machine problem(第 2 节),讨论 Paxos 的优点和缺点(第 3 节),描述我们对 understandability 的一般方法(第 4 节),介绍 Raft consensus algorithm(第 5~8 节),评估 Raft(第 9 节),并讨论 related work(第 10 节)。

第 2 页:Replicated state machines 与 Paxos 问题

raft p02

Figure 1: Replicated state machine architecture. The consensus algorithm manages a replicated log containing state machine commands from clients. The state machines process identical sequences of commands from the logs, so they produce the same outputs.

图 1:replicated state machine 架构。Consensus algorithm 管理一个由客户端 state machine commands 组成的 replicated log。各个 state machine 按照 log 中相同的 command 序列进行处理,因此产生相同的输出。

2 Replicated state machines

2 Replicated state machines。

Consensus algorithms typically arise in the context of replicated state machines [37].

Consensus algorithms 通常出现在 replicated state machines 的场景中 [37]。

In this approach, state machines on a collection of servers compute identical copies of the same state and can continue operating even if some of the servers are down.

在这种方法中,一组 server 上的 state machines 计算同一状态的相同副本,即使部分 server 停机,它们仍可以继续运行。

Replicated state machines are used to solve a variety of fault tolerance problems in distributed systems.

Replicated state machines 被用于解决 distributed systems 中各种 fault tolerance 问题。

For example, large-scale systems that have a single cluster leader, such as GFS [8], HDFS [38], and RAMCloud [33], typically use a separate replicated state machine to manage leader election and store configuration information that must survive leader crashes.

例如,拥有单一 cluster leader 的大规模系统——如 GFS [8]、HDFS [38] 和 RAMCloud [33]——通常会使用一个独立的 replicated state machine 来管理 leader election,并存储必须在 leader crashes 后仍然存在的 configuration information。

Examples of replicated state machines include Chubby [2] and ZooKeeper [11].

Replicated state machines 的例子包括 Chubby [2] 和 ZooKeeper [11]。

Replicated state machines are typically implemented using a replicated log, as shown in Figure 1.

如图 1 所示,replicated state machines 通常使用 replicated log 实现。

Each server stores a log containing a series of commands, which its state machine executes in order.

每个 server 都存储一个包含一系列 commands 的 log,并由它的 state machine 按顺序执行这些 commands。

Each log contains the same commands in the same order, so each state machine processes the same sequence of commands.

每个 log 都以相同顺序包含相同的 commands,因此每个 state machine 处理相同的 command 序列。

Since the state machines are deterministic, each computes the same state and the same sequence of outputs.

由于这些 state machines 是 deterministic 的,每一个都会计算出相同的 state 和相同的输出序列。

Keeping the replicated log consistent is the job of the consensus algorithm.

保持 replicated log 一致,是 consensus algorithm 的职责。

The consensus module on a server receives commands from clients and adds them to its log.

server 上的 consensus module 接收客户端 commands,并将它们加入自己的 log。

It communicates with the consensus modules on other servers to ensure that every log eventually contains the same requests in the same order, even if some servers fail.

它与其他 server 上的 consensus modules 通信,以确保即使部分 server 发生故障,最终每个 log 仍包含相同顺序的相同 requests。

Once commands are properly replicated, each server’s state machine processes them in log order, and the outputs are returned to clients.

commands 被正确复制后,每个 server 的 state machine 按 log 顺序处理它们,并将输出返回给客户端。

As a result, the servers appear to form a single, highly reliable state machine.

因此,这些 server 看起来就像组成了一个高度可靠的单一 state machine。

Consensus algorithms for practical systems typically have the following properties:

面向实际系统的 consensus algorithms 通常具有以下性质:

They ensure safety (never returning an incorrect result) under all non-Byzantine conditions, including network delays, partitions, and packet loss, duplication, and reordering.

它们在所有 non-Byzantine 条件下保证 safety(绝不返回错误结果),其中包括 network delays、partitions,以及 packet loss、duplication 和 reordering。

They are fully functional (available) as long as any majority of the servers are operational and can communicate with each other and with clients.

只要任意 majority 的 server 仍在运行,并且它们彼此之间以及与客户端之间能够通信,系统就是 fully functional(available)的。

Thus, a typical cluster of five servers can tolerate the failure of any two servers.

因此,一个典型的五节点 cluster 可以容忍任意两个 server 发生故障。

Servers are assumed to fail by stopping; they may later recover from state on stable storage and rejoin the cluster.

假设 server 通过停止运行的方式故障;之后它们可以从 stable storage 上的 state 恢复,并重新加入 cluster。

They do not depend on timing to ensure the consistency of the logs: faulty clocks and extreme message delays can, at worst, cause availability problems.

它们不依赖 timing 来保证 log 的 consistency:faulty clocks 和极端的 message delays 最坏只会造成 availability 问题。

In the common case, a command can complete as soon as a majority of the cluster has responded to a single round of remote procedure calls; a minority of slow servers need not impact overall system performance.

在常见情况下,只要 cluster 的 majority 对一轮 remote procedure calls 做出响应,command 就可以完成;少数速度较慢的 server 不必影响整个系统的性能。

3 What’s wrong with Paxos?

3 What’s wrong with Paxos?

3 Paxos 有什么问题?

Over the last ten years, Leslie Lamport’s Paxos protocol [15] has become almost synonymous with consensus: it is the protocol most commonly taught in courses, and most implementations of consensus use it as a starting point.

过去十年间,Leslie Lamport 的 Paxos protocol [15] 几乎已经成为 consensus 的同义词:它是课程中最常教授的 protocol,而大多数 consensus implementations 都以它为起点。

Paxos first defines a protocol capable of reaching agreement on a single decision, such as a single replicated log entry.

Paxos 首先定义了一个能够让参与者就单个 decision 达成 agreement 的 protocol,例如针对单个 replicated log entry 达成一致。

We refer to this subset as single-decree Paxos.

我们把这个子集称为 single-decree Paxos。

Paxos then combines multiple instances of this protocol to facilitate a series of decisions such as a log (multi-Paxos).

随后,Paxos 组合这个 protocol 的多个实例,以支持一系列 decisions,例如一个 log(multi-Paxos)。

Paxos ensures both safety and liveness, and it supports changes in cluster membership.

Paxos 同时保证 safety 和 liveness,也支持 cluster membership changes。

Its correctness has been proven, and it is efficient in the normal case.

它的 correctness 已经得到证明,并且在 normal case 下效率很高。

Unfortunately, Paxos has two significant drawbacks.

遗憾的是,Paxos 有两个显著缺点。

The first drawback is that Paxos is exceptionally difficult to understand.

第一个缺点是 Paxos 极其难以理解。

The full explanation [15] is notoriously opaque; few people succeed in understanding it, and only with great effort.

完整解释 [15] 以晦涩难懂而闻名;很少有人能够理解它,而且通常要付出很大努力。

As a result, there have been several attempts to explain Paxos in simpler terms [16, 20, 21].

因此,人们曾多次尝试用更简单的方式解释 Paxos [16, 20, 21]。

These explanations focus on the single-decree subset, yet they are still challenging.

这些解释聚焦于 single-decree 子集,但仍然很有挑战性。

In an informal survey of attendees at NSDI 2012, we found few people who were comfortable with Paxos, even among seasoned researchers.

在对 NSDI 2012 与会者进行的一项非正式调查中,我们发现,即使在经验丰富的研究者中,也很少有人真正熟悉 Paxos。

We struggled with Paxos ourselves; we were not able to understand the complete protocol until after reading several simplified explanations and designing our own alternative protocol, a process that took almost a year.

我们自己也曾在 Paxos 上挣扎;直到阅读了多份简化解释并设计出自己的替代 protocol 后,才理解完整 protocol,而这个过程几乎花了一年。

We hypothesize that Paxos’ opaqueness derives from its choice of the single-decree subset as its foundation.

我们推测,Paxos 的晦涩源于它选择 single-decree 子集作为基础。

Single-decree Paxos is dense and subtle: it is divided into two stages that do not have simple intuitive explanations and cannot be understood independently.

Single-decree Paxos 密集而微妙:它被分成两个阶段,但这两个阶段既没有简单直观的解释,也不能彼此独立地理解。

Because of this, it is difficult to develop intuitions about why the single-decree protocol works.

因此,人们很难形成关于 single-decree protocol 为什么有效的直觉。

The composition rules for multi-Paxos add significant additional complexity and subtlety.

multi-Paxos 的组合规则又增加了大量复杂性和微妙之处。

We believe that the overall problem of reaching consensus on multiple decisions (i.e., a log instead of a single entry) can be decomposed in other ways that are more direct and obvious.

我们认为,对多个 decisions 达成 consensus 的总体问题(也就是处理一个 log,而不是单个 entry)可以用其他更直接、更明显的方式分解。

第 3 页:Paxos 的工程问题与可理解性设计

raft p03

The second problem with Paxos is that it does not provide a good foundation for building practical implementations.

Paxos 的第二个问题是:它没有为构建实际实现提供良好的基础。

One reason is that there is no widely agreed-upon algorithm for multi-Paxos.

原因之一是,人们并没有一个广泛认可的 multi-Paxos algorithm。

Lamport’s descriptions are mostly about single-decree Paxos; he sketched possible approaches to multi-Paxos, but many details are missing.

Lamport 的描述主要针对 single-decree Paxos;他勾勒过 multi-Paxos 的一些可能做法,但仍缺少许多细节。

There have been several attempts to flesh out and optimize Paxos, such as [26], [39], and [13], but these differ from each other and from Lamport’s sketches.

人们曾多次尝试补全并优化 Paxos,例如 [26]、[39] 和 [13];但这些方案彼此不同,也不同于 Lamport 勾勒的方案。

Systems such as Chubby [4] have implemented Paxos-like algorithms, but in most cases their details have not been published.

Chubby [4] 等系统实现了类似 Paxos 的 algorithms,但在大多数情况下,它们的具体细节并没有公开发表。

Furthermore, the Paxos architecture is a poor one for building practical systems; this is another consequence of the single-decree decomposition.

此外,Paxos 的架构并不适合构建实际系统;这同样是 single-decree decomposition 带来的后果。

For example, there is little benefit to choosing a collection of log entries independently and then melding them into a sequential log; this just adds complexity.

例如,先独立选择一组 log entries,再把它们熔合成一个 sequential log,几乎没有什么好处;这样做只会增加复杂性。

It is simpler and more efficient to design a system around a log, where new entries are appended sequentially in a constrained order.

围绕一个 log 来设计系统更简单、更高效:新 entries 按受约束的顺序依次追加。

Another problem is that Paxos uses a symmetric peer-to-peer approach at its core (though it eventually suggests a weak form of leadership as a performance optimization).

另一个问题是,Paxos 的核心采用 symmetric peer-to-peer approach(尽管它最终把一种弱形式的 leadership 作为性能优化提出)。

This makes sense in a simplified world where only one decision will be made, but few practical systems use this approach.

在只需要做出一个 decision 的简化世界里,这种方法是合理的;但很少有实际系统会采用它。

If a series of decisions must be made, it is simpler and faster to first elect a leader, then have the leader coordinate the decisions.

如果必须做出一系列 decisions,那么先选出一个 leader,再由 leader 协调这些 decisions,会更简单、更快。

As a result, practical systems bear little resemblance to Paxos.

因此,实际系统与 Paxos 几乎没有多少相似之处。

Each implementation begins with Paxos, discovers the difficulties in implementing it, and then develops a significantly different architecture.

每个实现都从 Paxos 开始,发现实现它的困难,然后发展出一种明显不同的架构。

This is time-consuming and error-prone, and the difficulties of understanding Paxos exacerbate the problem.

这既耗时又容易出错,而理解 Paxos 的困难又进一步加重了问题。

Paxos’ formulation may be a good one for proving theorems about its correctness, but real implementations are so different from Paxos that the proofs have little value.

Paxos 的表述也许适合用于证明关于其 correctness 的定理,但真实实现与 Paxos 差异如此之大,以至于这些证明几乎没有实际价值。

The following comment from the Chubby implementers is typical:

Chubby 实现者的下面这段评论很有代表性:

There are significant gaps between the description of the Paxos algorithm and the needs of a real-world system. . . . the final system will be based on an unproven protocol [4].

“Paxos algorithm 的描述与现实系统的需求之间存在显著差距……最终系统将建立在一个未经证明的 protocol 之上。”[4]

Because of these problems, we concluded that Paxos does not provide a good foundation either for system building or for education.

基于这些问题,我们得出结论:Paxos 既不能为系统构建提供良好基础,也不能为教学提供良好基础。

Given the importance of consensus in large-scale software systems, we decided to see if we could design an alternative consensus algorithm with better properties than Paxos.

考虑到 consensus 对大规模软件系统的重要性,我们决定尝试设计一种性质优于 Paxos 的替代 consensus algorithm。

Raft is the result of that experiment.

Raft 就是这次尝试的结果。

4 Designing for understandability

4 Designing for understandability

4 面向可理解性进行设计。

We had several goals in designing Raft: it must provide a complete and practical foundation for system building, so that it significantly reduces the amount of design work required of developers; it must be safe under all conditions and available under typical operating conditions; and it must be efficient for common operations.

在设计 Raft 时,我们有几个目标:它必须为系统构建提供完整且实际的基础,从而显著减少开发者需要完成的设计工作;它必须在所有条件下都保持 safe,并在典型运行条件下保持 available;同时,它必须对常见操作足够高效。

But our most important goal—and most difficult challenge—was understandability.

但最重要、也最困难的目标是 understandability。

It must be possible for a large audience to understand the algorithm comfortably.

必须让广泛的读者群体能够轻松理解这个 algorithm。

In addition, it must be possible to develop intuitions about the algorithm, so that system builders can make the extensions that are inevitable in real-world implementations.

此外,还必须能够形成关于 algorithm 的直觉,这样系统构建者才能完成现实实现中不可避免的扩展。

There were numerous points in the design of Raft where we had to choose among alternative approaches.

在 Raft 的设计中,有很多地方需要我们从多种替代方案中做出选择。

In these situations we evaluated the alternatives based on understandability: how hard is it to explain each alternative (for example, how complex is its state space, and does it have subtle implications?), and how easy will it be for a reader to completely understand the approach and its implications?

在这些情况下,我们依据 understandability 评估各个方案:每种方案有多难解释(例如,它的 state space 有多复杂,是否存在微妙的含义),以及读者要完全理解这种方法及其含义有多容易?

We recognize that there is a high degree of subjectivity in such analysis; nonetheless, we used two techniques that are generally applicable.

我们承认,这种分析具有很强的主观性;不过,我们采用了两种通常适用的技术。

The first technique is the well-known approach of problem decomposition: wherever possible, we divided problems into separate pieces that could be solved, explained, and understood relatively independently.

第一种技术是众所周知的 problem decomposition:只要可能,我们就把问题拆成可以相对独立地解决、解释和理解的不同部分。

For example, in Raft we separated leader election, log replication, safety, and membership changes.

例如,在 Raft 中,我们把 leader election、log replication、safety 和 membership changes 分开。

Our second approach was to simplify the state space by reducing the number of states to consider, making the system more coherent and eliminating nondeterminism where possible.

第二种方法是通过减少需要考虑的状态数量来简化 state space,使系统更加 coherent,并在可能的地方消除 nondeterminism。

Specifically, logs are not allowed to have holes, and Raft limits the ways in which logs can become inconsistent with each other.

具体来说,logs 不允许出现 holes,而 Raft 限制了 logs 之间产生不一致的方式。

Although in most cases we tried to eliminate nondeterminism, there are some situations where nondeterminism actually improves understandability.

虽然我们在大多数情况下都试图消除 nondeterminism,但在某些情况下,nondeterminism 反而能够提升 understandability。

In particular, randomized approaches introduce nondeterminism, but they tend to reduce the state space by handling all possible choices in a similar fashion (“choose any; it doesn’t matter”).

特别是,randomized approaches 会引入 nondeterminism,但它们往往通过以相似方式处理所有可能的选择来减少 state space(“任选一个;无所谓”)。

We used randomization to simplify the Raft leader election algorithm.

我们使用 randomization 来简化 Raft leader election algorithm。

5 The Raft consensus algorithm

5 The Raft consensus algorithm

5 Raft consensus algorithm。

Raft is an algorithm for managing a replicated log of the form described in Section 2.

Raft 是一种管理第 2 节所述形式的 replicated log 的 algorithm。

Figure 2 summarizes the algorithm in condensed form for reference, and Figure 3 lists key properties of the algorithm; the elements of these figures are discussed piecewise over the rest of this section.

图 2 以压缩形式总结了该 algorithm,供读者查阅;图 3 列出了该 algorithm 的关键性质;后文将分部分讨论这些图中的元素。

Raft implements consensus by first electing a distinguished leader, then giving the leader complete responsibility for managing the replicated log.

Raft 先选出一个 distinguished leader,再将管理 replicated log 的全部责任交给这个 leader,以此实现 consensus。

The leader accepts log entries from clients, replicates them on other servers, and tells servers when it is safe to apply log entries to their state machines.

leader 接收客户端的 log entries,将它们复制到其他 servers,并告知 servers 何时可以安全地把 log entries 应用到各自的 state machines。

Having a leader simplifies the management of the replicated log.

拥有一个 leader 会简化 replicated log 的管理。

For example, the leader can decide where to place new entries in the log without consulting other servers, and data flows in a simple fashion from the leader to other servers.

例如,leader 无需咨询其他 servers 就能决定新 entries 在 log 中的位置,而且 data 以简单的方式从 leader 流向其他 servers。

A leader can fail or become disconnected from the other servers, in which case a new leader is elected.

leader 可能发生故障,或与其他 servers 断开连接;此时系统会选出一个 new leader。

Given the leader approach, Raft decomposes the consensus problem into three relatively independent subproblems, which are discussed in the subsections that follow:

基于 leader approach,Raft 将 consensus problem 分解成三个相对独立的 subproblems,下面的小节将分别讨论它们:

Leader election: a new leader must be chosen when an existing leader fails (Section 5.2).

Leader election:现有 leader 发生故障时,必须选出 new leader(第 5.2 节)。

Log replication: the leader must accept log entries from clients and replicate them across the cluster, forcing the other logs to agree with its own (Section 5.3).

Log replication:leader 必须接收客户端的 log entries,并将它们复制到整个 cluster,迫使其他 logs 与自己的 log 达成一致(第 5.3 节)。

Safety: the key safety property for Raft is the State Machine Safety Property in Figure 3: if any server has applied a particular log entry to its state machine, then no other server may apply a different command for the same log index.

Safety:Raft 的关键 safety property 是图 3 中的 State Machine Safety Property:如果某个 server 已经将某个 log entry 应用到自己的 state machine,那么其他 server 都不能对同一个 log index 应用不同的 command。

Section 5.4 describes how Raft ensures this property; the solution involves an additional restriction on the election mechanism described in Section 5.2.

第 5.4 节描述 Raft 如何保证这一性质;解决方案包括对第 5.2 节所述 election mechanism 增加一项额外限制。

After presenting the consensus algorithm, this section discusses the issue of availability and the role of timing in the system.

介绍完 consensus algorithm 后,本节还会讨论 availability 问题以及 timing 在系统中的作用。

第 4 页:Figure 2 的 RPC、状态和服务器规则

raft p04

RequestVote RPC

RequestVote RPC。

Invoked by candidates to gather votes (§5.2).

由 candidates 调用,用于收集 votes(第 5.2 节)。

Arguments: term: candidate’s term; candidateId: candidate requesting vote; lastLogIndex: index of candidate’s last log entry (§5.4); lastLogTerm: term of candidate’s last log entry (§5.4)

Arguments:term:candidate 的 term;candidateId:请求投票的 candidate;lastLogIndex:candidate 最后一个 log entry 的 index(第 5.4 节);lastLogTerm:candidate 最后一个 log entry 的 term(第 5.4 节)。

Results: term: currentTerm, for candidate to update itself; voteGranted: true means candidate received vote

Results:term:currentTerm,供 candidate 更新自身;voteGranted:true 表示 candidate 获得了 vote。

Receiver implementation: 1. Reply false if term < currentTerm (§5.1) 2. If votedFor is null or candidateId, and candidate’s log is at least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)

Receiver implementation:1. 如果 term < currentTerm,则回复 false(第 5.1 节);2. 如果 votedFor 为 null 或等于 candidateId,并且 candidate 的 log 至少与 receiver 的 log 一样新,则授予 vote(第 5.2、5.4 节)。

AppendEntries RPC

AppendEntries RPC。

Invoked by leader to replicate log entries (§5.3); also used as heartbeat (§5.2).

由 leader 调用,用于复制 log entries(第 5.3 节);也用作 heartbeat(第 5.2 节)。

Arguments: term: leader’s term; leaderId: so follower can redirect clients; prevLogIndex: index of log entry immediately preceding new ones; prevLogTerm: term of prevLogIndex entry; entries[]: log entries to store (empty for heartbeat; may send more than one for efficiency); leaderCommit: leader’s commitIndex

Arguments:term:leader 的 term;leaderId:让 follower 能够重定向 clients;prevLogIndex:紧邻新 entries 之前的 log entry index;prevLogTerm:prevLogIndex 对应 entry 的 term;entries[]:要存储的 log entries(heartbeat 时为空;为提高效率时可以一次发送多个);leaderCommit:leader 的 commitIndex。

Results: term: currentTerm, for leader to update itself; success: true if follower contained entry matching prevLogIndex and prevLogTerm

Results:term:currentTerm,供 leader 更新自身;success:如果 follower 包含与 prevLogIndex 和 prevLogTerm 匹配的 entry,则为 true。

Receiver implementation: 1. Reply false if term < currentTerm (§5.1) 2. Reply false if log doesn’t contain an entry at prevLogIndex whose term matches prevLogTerm (§5.3) 3. If an existing entry conflicts with a new one (same index but different terms), delete the existing entry and all that follow it (§5.3) 4. Append any new entries not already in the log 5. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry)

Receiver implementation:1. 如果 term < currentTerm,则回复 false(第 5.1 节);2. 如果 log 在 prevLogIndex 没有 term 与 prevLogTerm 匹配的 entry,则回复 false(第 5.3 节);3. 如果已有 entry 与新 entry 冲突(index 相同但 term 不同),删除已有 entry 以及它后面的所有 entries(第 5.3 节);4. 追加 log 中尚不存在的所有新 entries;5. 如果 leaderCommit > commitIndex,则将 commitIndex 设为 min(leaderCommit, last new entry 的 index)。

Persistent state on all servers: currentTerm: latest term server has seen (initialized to 0 on first boot, increases monotonically); votedFor: candidateId that received vote in current term (or null if none); log[]: log entries; each entry contains command for state machine, and term when entry was received by leader (first index is 1)

所有 servers 上的 persistent state:currentTerm:server 见过的最新 term(首次启动时初始化为 0,并单调递增);votedFor:当前 term 中获得 vote 的 candidateId(如果没有则为 null);log[]:log entries,每个 entry 包含发给 state machine 的 command,以及 leader 接收到该 entry 时的 term(第一个 index 为 1)。

Volatile state on all servers: commitIndex: index of highest log entry known to be committed (initialized to 0, increases monotonically); lastApplied: index of highest log entry applied to state machine (initialized to 0, increases monotonically)

所有 servers 上的 volatile state:commitIndex:已知已 committed 的最高 log entry index(初始化为 0,单调递增);lastApplied:已应用到 state machine 的最高 log entry index(初始化为 0,单调递增)。

Volatile state on leaders: nextIndex[]: for each server, index of the next log entry to send to that server (initialized to leader last log index + 1); matchIndex[]: for each server, index of highest log entry known to be replicated on server (initialized to 0, increases monotonically)

leaders 上的 volatile state:nextIndex[]:对每个 server,要发送给该 server 的下一个 log entry index(初始化为 leader last log index + 1);matchIndex[]:对每个 server,已知该 server 已复制的最高 log entry index(初始化为 0,单调递增)。

All Servers: If commitIndex > lastApplied: increment lastApplied, apply log[lastApplied] to state machine (§5.3). If RPC request or response contains term T > currentTerm: set currentTerm = T, convert to follower (§5.1)

All Servers:如果 commitIndex > lastApplied,则递增 lastApplied,并将 log[lastApplied] 应用到 state machine(第 5.3 节)。如果 RPC request 或 response 包含 term T 且 T > currentTerm,则设置 currentTerm = T,并转换为 follower(第 5.1 节)。

Followers (§5.2): Respond to RPCs from candidates and leaders. If election timeout elapses without receiving AppendEntries RPC from current leader or granting vote to candidate: convert to candidate

Followers(第 5.2 节):响应来自 candidates 和 leaders 的 RPC。如果 election timeout 到期前既没有收到 current leader 的 AppendEntries RPC,也没有给 candidate 授予 vote,则转换为 candidate。

Candidates (§5.2): On conversion to candidate, start election; increment currentTerm; vote for self; reset election timer; send RequestVote RPCs to all other servers. If votes received from majority of servers: become leader. If AppendEntries RPC received from new leader: convert to follower. If election timeout elapses: start new election

Candidates(第 5.2 节):转换为 candidate 时开始 election;递增 currentTerm;投票给自己;重置 election timer;向所有其他 servers 发送 RequestVote RPC。如果从 majority of servers 收到 votes,则成为 leader。如果收到 new leader 的 AppendEntries RPC,则转换为 follower。如果 election timeout 到期,则开始 new election。

Leaders: Upon election, send initial empty AppendEntries RPCs (heartbeat) to each server; repeat during idle periods to prevent election timeouts (§5.2). If command received from client: append entry to local log, respond after entry applied to state machine (§5.3). If last log index ≥ nextIndex for a follower: send AppendEntries RPC with log entries starting at nextIndex. If successful: update nextIndex and matchIndex for follower (§5.3). If AppendEntries fails because of log inconsistency: decrement nextIndex and retry (§5.3). If there exists an N such that N > commitIndex, a majority of matchIndex[i] ≥ N, and log[N].term == currentTerm: set commitIndex = N (§5.3, §5.4).

Leaders:当选后,向每个 server 发送初始的空 AppendEntries RPC(heartbeat);在空闲期间重复发送,以防止 election timeouts(第 5.2 节)。如果收到 client 的 command,则将 entry 追加到本地 log,并在 entry 应用到 state machine 后回复(第 5.3 节)。如果 follower 的 last log index ≥ nextIndex,则发送从 nextIndex 开始的 log entries 组成的 AppendEntries RPC。如果成功,则更新该 follower 对应的 nextIndex 和 matchIndex(第 5.3 节)。如果 AppendEntries 因 log inconsistency 失败,则递减 nextIndex 并重试(第 5.3 节)。如果存在某个 N,满足 N > commitIndex、majority 的 matchIndex[i] ≥ N,且 log[N].term == currentTerm,则将 commitIndex 设为 N(第 5.3、5.4 节)。

Figure 2: A condensed summary of the Raft consensus algorithm (excluding membership changes and log compaction). The server behavior in the upper-left box is described as a set of rules that trigger independently and repeatedly. Section numbers such as §5.2 indicate where particular features are discussed. A formal specification [31] describes the algorithm more precisely.

图 2:Raft consensus algorithm 的压缩摘要(不包括 membership changes 和 log compaction)。左上角框中的 server behavior 被描述成一组可以独立、反复触发的规则。像 §5.2 这样的节号表示特定特性在哪一节讨论。形式化 specification [31] 对该 algorithm 做了更精确的描述。

第 5 页:Safety properties、Raft basics 与 term

raft p05

Election Safety: at most one leader can be elected in a given term. §5.2

Election Safety:在给定 term 中最多只能选出一个 leader。§5.2。

Leader Append-Only: a leader never overwrites or deletes entries in its log; it only appends new entries. §5.3

Leader Append-Only:leader 永远不会覆盖或删除自己 log 中的 entries;它只会追加 new entries。§5.3。

Log Matching: if two logs contain an entry with the same index and term, then the logs are identical in all entries up through the given index. §5.3

Log Matching:如果两个 logs 包含 index 和 term 都相同的 entry,那么截至该 index,两个 logs 的所有 entries 都相同。§5.3。

Leader Completeness: if a log entry is committed in a given term, then that entry will be present in the logs of the leaders for all higher-numbered terms. §5.4

Leader Completeness:如果某个 log entry 在给定 term 中 committed,那么在所有编号更高的 terms 中,该 entry 都会出现在 leader 的 logs 中。§5.4。

State Machine Safety: if a server has applied a log entry at a given index to its state machine, no other server will ever apply a different log entry for the same index. §5.4.3

State Machine Safety:如果某个 server 已经把给定 index 的 log entry 应用到自己的 state machine,那么其他 server 永远不会为同一 index 应用不同的 log entry。§5.4.3。

Figure 3: Raft guarantees that each of these properties is true at all times. The section numbers indicate where each property is discussed.

图 3:Raft 保证这些 properties 始终成立。节号表示每个 property 在哪里讨论。

Safety: the key safety property for Raft is the State Machine Safety Property in Figure 3: if any server has applied a particular log entry to its state machine, then no other server may apply a different command for the same log index.

Safety:Raft 的关键 safety property 是图 3 中的 State Machine Safety Property:如果任何 server 已经将某个 log entry 应用到自己的 state machine,那么其他 server 都不能为同一个 log index 应用不同的 command。

Section 5.4 describes how Raft ensures this property; the solution involves an additional restriction on the election mechanism described in Section 5.2.

第 5.4 节描述 Raft 如何保证这一 property;解决方案包括对第 5.2 节所述 election mechanism 增加额外限制。

After presenting the consensus algorithm, this section discusses the issue of availability and the role of timing in the system.

介绍完 consensus algorithm 后,本节还会讨论 availability 问题以及 timing 在系统中的作用。

5.1 Raft basics

5.1 Raft basics

5.1 Raft basics。

A Raft cluster contains several servers; five is a typical number, which allows the system to tolerate two failures.

一个 Raft cluster 包含若干 servers;五个是典型数量,这使系统能够容忍两次 failures。

At any given time each server is in one of three states: leader, follower, or candidate.

在任意时刻,每个 server 都处于三种状态之一:leader、follower 或 candidate。

In normal operation there is exactly one leader and all of the other servers are followers.

正常运行时,系统恰好有一个 leader,其他所有 servers 都是 followers。

Followers are passive: they issue no requests on their own but simply respond to requests from leaders and candidates.

Followers 是被动的:它们不会自行发出 requests,而只是响应 leaders 和 candidates 发来的 requests。

The leader handles all client requests (if a client contacts a follower, the follower redirects it to the leader).

leader 处理所有 client requests(如果 client 联系的是 follower,follower 会将其重定向到 leader)。

The third state, candidate, is used to elect a new leader as described in Section 5.2.

第三种状态 candidate 用于选出 new leader,具体见第 5.2 节。

Figure 4 shows the states and their transitions; the transitions are discussed below.

图 4 展示了这些 states 及其 transitions;下面将讨论这些 transitions。

Figure 4: Server states. Followers only respond to requests from other servers. If a follower receives no communication, it becomes a candidate and initiates an election. A candidate that receives votes from a majority of the full cluster becomes the new leader. Leaders typically operate until they fail.

图 4:Server states。Followers 只响应来自其他 servers 的 requests。如果 follower 没有收到通信,它会变成 candidate 并发起 election。获得整个 cluster majority votes 的 candidate 会成为 new leader。Leaders 通常会一直运行到发生故障。

Raft divides time into terms of arbitrary length, as shown in Figure 5.

如图 5 所示,Raft 将时间划分成任意长度的 terms。

Terms are numbered with consecutive integers.

Terms 使用连续整数编号。

Each term begins with an election, in which one or more candidates attempt to become leader as described in Section 5.2.

每个 term 都从一次 election 开始;在 election 中,一个或多个 candidates 按照第 5.2 节所述方式尝试成为 leader。

If a candidate wins the election, then it serves as leader for the rest of the term.

如果 candidate 赢得 election,那么它将在该 term 的剩余时间内担任 leader。

In some situations an election will result in a split vote.

在某些情况下,election 会导致 split vote。

In this case the term will end with no leader; a new term (with a new election) will begin shortly.

此时,该 term 会在没有 leader 的情况下结束;不久后会开始一个 new term(伴随 new election)。

Figure 5: Time is divided into terms, and each term begins with an election. After a successful election, a single leader manages the cluster until the end of the term. Some elections fail, in which case the term ends without choosing a leader. The transitions between terms may be observed at different times on different servers.

图 5:时间被划分成 terms,每个 term 都从 election 开始。election 成功后,单个 leader 管理 cluster,直到该 term 结束。有些 elections 会失败,此时 term 在没有选出 leader 的情况下结束。不同 servers 可能在不同时间观察到 terms 之间的 transitions。

Raft ensures that there is at most one leader in a given term.

Raft 保证给定 term 中最多只有一个 leader。

Different servers may observe the transitions between terms at different times, and in some situations a server may not observe an election or even entire terms.

不同 servers 可能在不同时间观察到 terms 之间的 transitions;在某些情况下,某个 server 甚至可能看不到一次 election 或完整的 terms。

Terms act as a logical clock [14] in Raft, and they allow servers to detect obsolete information such as stale leaders.

在 Raft 中,terms 充当 logical clock [14],使 servers 能够检测 stale leaders 等 obsolete information。

Each server stores a current term number, which increases monotonically over time.

每个 server 都存储一个 current term number,并且该数字随时间单调递增。

Current terms are exchanged whenever servers communicate; if one server’s current term is smaller than the other’s, then it updates its current term to the larger value.

servers 每次通信时都会交换 current terms;如果某个 server 的 current term 小于另一个 server 的 current term,它就把自己的 current term 更新为较大值。

If a candidate or leader discovers that its term is out of date, it immediately reverts to follower state.

如果 candidate 或 leader 发现自己的 term 已过期,它会立即退回 follower state。

If a server receives a request with a stale term number, it rejects the request.

如果 server 收到带有 stale term number 的 request,它会拒绝该 request。

Raft servers communicate using remote procedure calls (RPCs), and the basic consensus algorithm requires only two types of RPCs.

Raft servers 使用 remote procedure calls(RPCs)通信,而 basic consensus algorithm 只需要两类 RPCs。

RequestVote RPCs are initiated by candidates during elections (Section 5.2), and AppendEntries RPCs are initiated by leaders to replicate log entries and to provide a form of heartbeat (Section 5.3).

RequestVote RPCs 由 candidates 在 elections 期间发起(第 5.2 节);AppendEntries RPCs 由 leaders 发起,用于复制 log entries 并提供一种 heartbeat(第 5.3 节)。

Section 7 adds a third RPC for transferring snapshots between servers.

第 7 节增加了第三种 RPC,用于在 servers 之间传输 snapshots。

Servers retry RPCs if they do not receive a response in a timely manner, and they issue RPCs in parallel for best performance.

如果没有及时收到 response,servers 会重试 RPCs;为了获得最佳性能,它们会并行发出 RPCs。

5.2 Leader election

5.2 Leader election

5.2 Leader election。

Raft uses a heartbeat mechanism to trigger leader election.

Raft 使用 heartbeat mechanism 触发 leader election。

When servers start up, they begin as followers.

servers 启动时,首先都是 followers。

A server remains in follower state as long as it receives valid

只要 server 能持续收到有效的消息,它就保持 follower state。(本页句子在下一页继续。)

第 6 页:Leader election 与 Log replication 开始

raft p06

A server remains in follower state as long as it receives valid RPCs from a leader or candidate.

只要 server 能持续收到来自 leader 或 candidate 的有效 RPC,它就保持 follower state。

Leaders send periodic heartbeats (AppendEntries RPCs that carry no log entries) to all followers in order to maintain their authority.

Leaders 会定期向所有 followers 发送 heartbeats(不携带 log entries 的 AppendEntries RPCs),以维持自己的 authority。

If a follower receives no communication over a period of time called the election timeout, then it assumes there is no viable leader and begins an election to choose a new leader.

如果 follower 在一段称为 election timeout 的时间内没有收到任何通信,它就认为当前没有可用的 leader,并开始 election 以选出 new leader。

To begin an election, a follower increments its current term and transitions to candidate state.

要开始 election,follower 会递增 current term,并转换为 candidate state。

It then votes for itself and issues RequestVote RPCs in parallel to each of the other servers in the cluster.

随后它给自己投票,并向 cluster 中的其他每个 server 并行发出 RequestVote RPCs。

A candidate continues in this state until one of three things happens: (a) it wins the election, (b) another server establishes itself as leader, or (c) a period of time goes by with no winner.

Candidate 会保持这种状态,直到三件事之一发生:(a)它赢得 election;(b)另一个 server 建立了 leader 身份;(c)一段时间过去了,但没有 winner。

A candidate wins an election if it receives votes from a majority of the servers in the full cluster for the same term.

如果 candidate 在同一个 term 中获得整个 cluster majority servers 的 votes,它就赢得 election。

Each server will vote for at most one candidate in a given term, on a first-come-first-served basis (note: Section 5.4 adds an additional restriction on votes).

每个 server 在给定 term 中最多只会给一个 candidate 投票,遵循先到先得原则(注意:第 5.4 节会为 votes 增加额外限制)。

The majority rule ensures that at most one candidate can win the election for a particular term (the Election Safety Property in Figure 3).

majority rule 保证对于特定 term,最多只有一个 candidate 能赢得 election(即图 3 中的 Election Safety Property)。

Once a candidate wins an election, it becomes leader.

candidate 赢得 election 后,就成为 leader。

It then sends heartbeat messages to all of the other servers to establish its authority and prevent new elections.

随后它向所有其他 servers 发送 heartbeat messages,以建立 authority 并阻止新的 elections。

While waiting for votes, a candidate may receive an AppendEntries RPC from another server claiming to be leader.

在等待 votes 时,candidate 可能会收到另一个声称自己是 leader 的 server 发来的 AppendEntries RPC。

If the leader’s term (included in its RPC) is at least as large as the candidate’s current term, then the candidate recognizes the leader as legitimate and returns to follower state.

如果 leader 的 term(包含在其 RPC 中)至少和 candidate 的 current term 一样大,那么 candidate 会承认该 leader 合法,并返回 follower state。

If the term in the RPC is smaller than the candidate’s current term, then the candidate rejects the RPC and continues in candidate state.

如果 RPC 中的 term 小于 candidate 的 current term,那么 candidate 会拒绝 RPC,并继续保持 candidate state。

The third possible outcome is that a candidate neither wins nor loses the election: if many followers become candidates at the same time, votes could be split so that no candidate obtains a majority.

第三种可能结果是 candidate 既没有赢得也没有输掉 election:如果许多 followers 同时变成 candidates,votes 可能被分散,导致没有 candidate 获得 majority。

When this happens, each candidate will time out and start a new election by incrementing its term and initiating another round of RequestVote RPCs.

发生这种情况时,每个 candidate 都会超时,并通过递增 term、发起新一轮 RequestVote RPC 来开始新的 election。

However, without extra measures split votes could repeat indefinitely.

但是,如果没有额外措施,split votes 可能会无限重复。

Raft uses randomized election timeouts to ensure that split votes are rare and that they are resolved quickly.

Raft 使用 randomized election timeouts,确保 split votes 很少发生,并且能够快速解决。

To prevent split votes in the first place, election timeouts are chosen randomly from a fixed interval (e.g., 150–300ms).

为了从一开始就避免 split votes,election timeouts 会从一个固定区间(例如 150~300ms)中随机选择。

This spreads out the servers so that in most cases only a single server will time out; it wins the election and sends heartbeats before any other servers time out.

这会错开 servers 的 timeout 时间,因此大多数情况下只有单个 server 会先超时;它会在其他 servers 超时之前赢得 election 并发送 heartbeats。

The same mechanism is used to handle split votes.

同样的机制也用于处理 split votes。

Each candidate restarts its randomized election timeout at the start of an election, and it waits for that timeout to elapse before starting the next election; this reduces the likelihood of another split vote in the new election.

每个 candidate 在 election 开始时都会重新启动 randomized election timeout,并等待该 timeout 到期后才开始下一次 election;这降低了新 election 再次出现 split vote 的可能性。

Section 9.3 shows that this approach elects a leader rapidly.

第 9.3 节表明,这种方法能够快速选出 leader。

Elections are an example of how understandability guided our choice between design alternatives.

Election 是一个例子,说明 understandability 如何指导我们在不同设计方案之间做选择。

Initially we planned to use a ranking system: each candidate was assigned a unique rank, which was used to select between competing candidates.

最初,我们计划使用 ranking system:为每个 candidate 分配一个唯一 rank,用它在竞争中的 candidates 之间做选择。

If a candidate discovered another candidate with higher rank, it would return to follower state so that the higher ranking candidate could more easily win the next election.

如果 candidate 发现另一个 candidate 的 rank 更高,它就返回 follower state,以便 rank 更高的 candidate 更容易赢得下一次 election。

We found that this approach created subtle issues around availability (a lower-ranked server might need to time out and become a candidate again if a higher-ranked server fails, but if it does so too soon, it can reset progress towards electing a leader).

我们发现,这种方法会产生与 availability 有关的微妙问题(如果 rank 更高的 server 发生故障,rank 较低的 server 可能需要超时并再次成为 candidate;但如果它过早这样做,就可能重置选出 leader 的进展)。

We made adjustments to the algorithm several times, but after each adjustment new corner cases appeared.

我们多次调整 algorithm,但每次调整后都会出现新的 corner cases。

Eventually we concluded that the randomized retry approach is more obvious and understandable.

最终我们得出结论:randomized retry approach 更直观,也更容易理解。

5.3 Log replication

5.3 Log replication

5.3 Log replication。

Once a leader has been elected, it begins servicing client requests.

leader 选出后,就开始处理 client requests。

Each client request contains a command to be executed by the replicated state machines.

每个 client request 都包含一个要由 replicated state machines 执行的 command。

The leader appends the command to its log as a new entry, then issues AppendEntries RPCs in parallel to each of the other servers to replicate the entry.

leader 将 command 作为 new entry 追加到自己的 log,然后向其他每个 server 并行发出 AppendEntries RPCs,以复制该 entry。

When the entry has been safely replicated (as described below), the leader applies the entry to its state machine and returns the result of that execution to the client.

entry 被安全复制后(如下文所述),leader 将 entry 应用到自己的 state machine,并把执行结果返回给 client。

If followers crash or run slowly, or if network packets are lost, the leader retries AppendEntries RPCs indefinitely (even after it has responded to the client) until all followers eventually store all log entries.

如果 followers crash 或运行缓慢,或者 network packets 丢失,leader 会无限重试 AppendEntries RPCs(即使已经向 client 返回 response),直到最终所有 followers 都存储全部 log entries。

第 7 页:Log Matching、日志冲突与收敛

raft p07

Each log entry also has an integer index identifying its position in the log.

每个 log entry 还有一个 integer index,用于标识它在 log 中的位置。

Figure 6: Logs are composed of entries, which are numbered sequentially. Each entry contains the term in which it was created (the number in each box) and a command for the state machine. An entry is considered committed if it is safe for that entry to be applied to state machines.

图 6:Logs 由 entries 组成,并按顺序编号。每个 entry 包含创建它时所在的 term(每个方框中的数字)以及一个发给 state machine 的 command。如果某个 entry 可以安全地应用到 state machines,就认为它已 committed。

The leader decides when it is safe to apply a log entry to the state machines; such an entry is called committed.

leader 决定何时可以安全地将 log entry 应用到 state machines;这样的 entry 称为 committed。

Raft guarantees that committed entries are durable and will eventually be executed by all of the available state machines.

Raft 保证 committed entries 是 durable 的,并且最终会由所有可用的 state machines 执行。

A log entry is committed once the leader that created the entry has replicated it on a majority of the servers (e.g., entry 7 in Figure 6).

创建该 entry 的 leader 将它复制到 majority servers 后,该 log entry 就 committed 了(例如图 6 中的 entry 7)。

This also commits all preceding entries in the leader’s log, including entries created by previous leaders.

这也会提交 leader log 中此前的所有 entries,包括由 previous leaders 创建的 entries。

Section 5.4 discusses some subtleties when applying this rule after leader changes, and it also shows that this definition of commitment is safe.

第 5.4 节讨论 leader changes 后应用该规则时的一些细节,并说明这种 commitment 定义是 safe 的。

The leader keeps track of the highest index it knows to be committed, and it includes that index in future AppendEntries RPCs (including heartbeats) so that the other servers eventually find out.

leader 会跟踪自己知道已 committed 的最高 index,并在后续 AppendEntries RPCs(包括 heartbeats)中携带该 index,使其他 servers 最终得知这一点。

Once a follower learns that a log entry is committed, it applies the entry to its local state machine (in log order).

follower 得知某个 log entry 已 committed 后,就会按 log order 将该 entry 应用到本地 state machine。

We designed the Raft log mechanism to maintain a high level of coherency between the logs on different servers.

我们设计 Raft log mechanism 的目标,是让不同 servers 上的 logs 保持高度 coherence。

Not only does this simplify the system’s behavior and make it more predictable, but it is an important component of ensuring safety.

这不仅简化了 system behavior、让系统更可预测,也是保证 safety 的重要组成部分。

Raft maintains the following properties, which together constitute the Log Matching Property in Figure 3:

Raft 维护以下 properties;它们共同构成图 3 中的 Log Matching Property:

If two entries in different logs have the same index and term, then they store the same command.

如果不同 logs 中的两个 entries 具有相同的 index 和 term,那么它们存储相同的 command。

If two entries in different logs have the same index and term, then the logs are identical in all preceding entries.

如果不同 logs 中的两个 entries 具有相同的 index 和 term,那么在它们之前的所有 entries 都相同。

The first property follows from the fact that a leader creates at most one entry with a given log index in a given term, and log entries never change their position in the log.

第一条 property 来自以下事实:一个 leader 在给定 term 中至多为某个 log index 创建一个 entry,并且 log entries 永远不会改变自己在 log 中的位置。

The second property is guaranteed by a simple consistency check performed by AppendEntries.

第二条 property 由 AppendEntries 执行的一个简单 consistency check 保证。

When sending an AppendEntries RPC, the leader includes the index and term of the entry in its log that immediately precedes the new entries.

发送 AppendEntries RPC 时,leader 会携带自己 log 中紧邻 new entries 之前那个 entry 的 index 和 term。

If the follower does not find an entry in its log with the same index and term, then it refuses the new entries.

如果 follower 在自己的 log 中找不到 index 和 term 都相同的 entry,就拒绝 new entries。

The consistency check acts as an induction step: the initial empty state of the logs satisfies the Log Matching Property, and the consistency check preserves the Log Matching Property whenever logs are extended.

这个 consistency check 充当 induction step:log 的初始空状态满足 Log Matching Property,而每次扩展 logs 时,consistency check 都会保持 Log Matching Property。

As a result, whenever AppendEntries returns successfully, the leader knows that the follower’s log is identical to its own log up through the new entries.

因此,只要 AppendEntries 成功返回,leader 就知道 follower 的 log 与自己的 log 在 new entries 之前(包括 new entries)完全相同。

During normal operation, the logs of the leader and followers stay consistent, so the AppendEntries consistency check never fails.

正常运行期间,leader 和 followers 的 logs 保持一致,因此 AppendEntries consistency check 不会失败。

However, leader crashes can leave the logs inconsistent (the old leader may not have fully replicated all of the entries in its log).

但是,leader crashes 可能使 logs 变得不一致(old leader 可能还没有完整复制自己 log 中的所有 entries)。

These inconsistencies can compound over a series of leader and follower crashes.

在一系列 leader 和 follower crashes 中,这些不一致可能进一步累积。

Figure 7: When the leader at the top comes to power, it is possible that any of scenarios (a–f) could occur in follower logs.

图 7:顶部的 leader 上台时,follower logs 可能处于场景(a~f)中的任意一种。

Each box represents one log entry; the number in the box is its term.

每个方框代表一个 log entry;方框中的数字是它的 term。

A follower may be missing entries (a–b), may have extra uncommitted entries (c–d), or both (e–f).

follower 可能缺少 entries(a~b),可能多出 extra uncommitted entries(c~d),也可能二者同时存在(e~f)。

Missing and extraneous entries in a log may span multiple terms.

log 中缺失的 entries 和多余的 entries 可能跨越多个 terms。

In Raft, the leader handles inconsistencies by forcing the followers’ logs to duplicate its own.

在 Raft 中,leader 通过强制 followers 的 logs 复制自己的 log 来处理不一致。

This means that conflicting entries in follower logs will be overwritten with entries from the leader’s log.

这意味着,follower logs 中的 conflicting entries 会被 leader log 中的 entries 覆盖。

Section 5.4 will show that this is safe when coupled with one more restriction.

第 5.4 节将说明,在配合另一项 restriction 时,这样做是 safe 的。

To bring a follower’s log into consistency with its own, the leader must find the latest log entry where the two logs agree, delete any entries in the follower’s log after that point, and send the follower all of the leader’s entries after that point.

为了让 follower 的 log 与自己的 log 一致,leader 必须找到两个 logs 最近一个一致的 log entry,删除 follower log 中该位置之后的所有 entries,然后将自己 log 中该位置之后的所有 entries 发送给 follower。

All of these actions happen in response to the consistency check performed by AppendEntries RPCs.

这些操作都作为对 AppendEntries RPCs 执行的 consistency check 的响应发生。

The leader maintains a nextIndex for each follower, which is the index of the next log entry the leader will send to that follower.

leader 为每个 follower 维护一个 nextIndex,它表示 leader 将发送给该 follower 的下一个 log entry 的 index。

When a leader first comes to power, it initializes all nextIndex values to the index just after the last one in its log (11 in Figure 7).

leader 初次上台时,会把所有 nextIndex 初始化为自己 log 中最后一个 entry 之后的 index(图 7 中为 11)。

If a follower’s log is inconsistent with the leader’s, the AppendEntries consistency check will fail in the next AppendEntries RPC.

如果 follower 的 log 与 leader 不一致,那么下一次 AppendEntries RPC 中的 consistency check 就会失败。

After a rejection, the leader decrements nextIndex and retries the AppendEntries RPC.

遭到拒绝后,leader 递减 nextIndex,并重试 AppendEntries RPC。

Eventually nextIndex will reach a point where the leader and follower logs match.

最终,nextIndex 会到达一个位置,使 leader 和 follower 的 logs 匹配。

When this happens, AppendEntries will succeed, which removes any conflicting entries in the follower’s log and appends entries from the leader’s log (if any).

此时 AppendEntries 会成功;它会删除 follower log 中的 conflicting entries,并追加 leader log 中的 entries(如果存在)。

Once AppendEntries succeeds, the follower’s log is consistent with the leader’s, and it will remain that way for the rest of the term.

AppendEntries 成功后,follower 的 log 就与 leader 一致,并会在该 term 的剩余时间里保持一致。

第 8 页:日志复制性质与 Election restriction

raft p08

If desired, the protocol can be optimized to reduce the number of rejected AppendEntries RPCs.

如果需要,可以优化 protocol,以减少被拒绝的 AppendEntries RPCs 数量。

For example, when rejecting an AppendEntries request, the follower can include the term of the conflicting entry and the first index it stores for that term.

例如,拒绝 AppendEntries request 时,follower 可以携带 conflicting entry 的 term,以及自己为该 term 存储的第一个 index。

With this information, the leader can decrement nextIndex to bypass all of the conflicting entries in that term; one AppendEntries RPC will be required for each term with conflicting entries, rather than one RPC per entry.

有了这些信息,leader 就能递减 nextIndex,跳过该 term 中所有 conflicting entries;对于每个包含 conflicting entries 的 term,只需一个 AppendEntries RPC,而不是每个 entry 一个 RPC。

In practice, we doubt this optimization is necessary, since failures happen infrequently and it is unlikely that there will be many inconsistent entries.

在实践中,我们怀疑这种 optimization 是否必要,因为 failures 并不频繁,而且不太可能存在大量 inconsistent entries。

With this mechanism, a leader does not need to take any special actions to restore log consistency when it comes to power.

有了这种机制,leader 上台时无需采取任何特殊操作来恢复 log consistency。

It just begins normal operation, and the logs automatically converge in response to failures of the AppendEntries consistency check.

它只需开始正常运行,logs 就会在 AppendEntries consistency check 失败的响应过程中自动收敛。

A leader never overwrites or deletes entries in its own log (the Leader Append-Only Property in Figure 3).

leader 永远不会覆盖或删除自己 log 中的 entries(图 3 中的 Leader Append-Only Property)。

This log replication mechanism exhibits the desirable consensus properties described in Section 2: Raft can accept, replicate, and apply new log entries as long as a majority of the servers are up; in the normal case a new entry can be replicated with a single round of RPCs to a majority of the cluster; and a single slow follower will not impact performance.

这种 log replication mechanism 展现了第 2 节描述的理想 consensus properties:只要 majority servers 处于运行状态,Raft 就能接收、复制和应用 new log entries;在 normal case 下,new entry 只需向 cluster majority 发送一轮 RPCs 就能复制;单个缓慢 follower 不会影响性能。

5.4 Safety

5.4 Safety

5.4 Safety。

The previous sections described how Raft elects leaders and replicates log entries.

前面的章节描述了 Raft 如何选举 leaders 和复制 log entries。

However, the mechanisms described so far are not quite sufficient to ensure that each state machine executes exactly the same commands in the same order.

但是,到目前为止描述的 mechanisms 还不足以保证每个 state machine 按相同顺序执行完全相同的 commands。

For example, a follower might be unavailable while the leader commits several log entries, then it could be elected leader and overwrite these entries with new ones; as a result, different state machines might execute different command sequences.

例如,leader 提交几个 log entries 时某个 follower 可能不可用;随后该 follower 可能被选为 leader,并用新的 entries 覆盖这些 entries;结果,不同 state machines 可能会执行不同的 command sequences。

This section completes the Raft algorithm by adding a restriction on which servers may be elected leader.

本节通过增加一项关于哪些 servers 可以被选为 leader 的 restriction,补完整个 Raft algorithm。

The restriction ensures that the leader for any given term contains all of the entries committed in previous terms (the Leader Completeness Property from Figure 3).

该 restriction 保证任意 term 的 leader 都包含 previous terms 中 committed 的全部 entries(图 3 中的 Leader Completeness Property)。

Given the election restriction, we then make the rules for commitment more precise.

在 election restriction 的基础上,我们进一步精确定义 commitment rules。

Finally, we present a proof sketch for the Leader Completeness Property and show how it leads to correct behavior of the replicated state machine.

最后,我们给出 Leader Completeness Property 的 proof sketch,并说明它如何导出 replicated state machine 的 correct behavior。

5.4.1 Election restriction

5.4.1 Election restriction

5.4.1 Election restriction。

In any leader-based consensus algorithm, the leader must eventually store all of the committed log entries.

在任何 leader-based consensus algorithm 中,leader 最终都必须存储所有 committed log entries。

In some consensus algorithms, such as Viewstamped Replication [22], a leader can be elected even if it doesn’t initially contain all of the committed entries.

在一些 consensus algorithms 中,例如 Viewstamped Replication [22],即使 leader 初始并不包含所有 committed entries,它仍然可以被选出。

These algorithms contain additional mechanisms to identify the missing entries and transmit them to the new leader, either during the election process or shortly afterwards.

这些 algorithms 包含额外 mechanisms,用于识别 missing entries,并在 election process 中或不久之后将它们传输给 new leader。

Unfortunately, this results in considerable additional mechanism and complexity.

遗憾的是,这会带来大量额外的 mechanism 和 complexity。

Raft uses a simpler approach where it guarantees that all the committed entries from previous terms are present on each new leader from the moment of its election, without the need to transfer those entries to the leader.

Raft 采用一种更简单的方法:保证 previous terms 中的所有 committed entries 从 new leader 当选的那一刻起就存在于该 leader 中,而无需再把这些 entries 传输给 leader。

This means that log entries only flow in one direction, from leaders to followers, and leaders never overwrite existing entries in their logs.

这意味着 log entries 只沿一个方向流动,即从 leaders 流向 followers;leaders 永远不会覆盖自己 logs 中已有的 entries。

Raft uses the voting process to prevent a candidate from winning an election unless its log contains all committed entries.

Raft 利用 voting process,阻止 log 不包含所有 committed entries 的 candidate 赢得 election。

A candidate must contact a majority of the cluster in order to be elected, which means that every committed entry must be present in at least one of those servers.

candidate 必须联系 cluster 的 majority 才能当选,这意味着每个 committed entry 至少存在于这些 servers 中的一个。

If the candidate’s log is at least as up-to-date as any other log in that majority (where “up-to-date” is defined precisely below), then it will hold all the committed entries.

如果 candidate 的 log 至少与该 majority 中其他任一 log 一样 up-to-date(“up-to-date”的精确定义如下),那么它就会包含全部 committed entries。

The RequestVote RPC implements this restriction: the RPC includes information about the candidate’s log, and the voter denies its vote if its own log is more up-to-date than that of the candidate.

RequestVote RPC 实现了这一 restriction:RPC 携带 candidate log 的信息;如果 voter 自己的 log 比 candidate 的 log 更 up-to-date,voter 就拒绝投票。

Raft determines which of two logs is more up-to-date by comparing the index and term of the last entries in the logs.

Raft 通过比较两个 logs 最后 entries 的 index 和 term,判断哪个 log 更 up-to-date。

If the logs have last entries with different terms, then the log with the later term is more up-to-date.

如果两个 logs 的最后 entries 具有不同 terms,那么 term 较新的 log 更 up-to-date。

If the logs end with the same term, then whichever log is longer is more up-to-date.

如果两个 logs 以相同 term 结束,那么更长的 log 更 up-to-date。

5.4.2 Committing entries from previous terms

5.4.2 Committing entries from previous terms

5.4.2 Committing entries from previous terms。

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.

如第 5.3 节所述,只要当前 term 的 entry 存储在 majority servers 上,leader 就知道该 entry 已 committed。

If a leader crashes before committing an entry, future leaders will attempt to finish replicating the entry.

如果 leader 在提交 entry 前 crash,future leaders 会尝试完成该 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.

但是,previous term 的 entry 即使存储在 majority servers 上,leader 也不能立即断定它已经 committed。

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.

图 8 展示了一种情况:old log entry 存储在 majority servers 上,却仍可能被 future leader 覆盖。

Figure 8: A time sequence showing why a leader cannot determine commitment using log entries from older terms.

图 8:展示为什么 leader 不能使用 older terms 的 log entries 来判断 commitment 的时间序列。

第 9 页:Leader Completeness 证明与 State Machine Safety

raft p09

Figure 9: If S1 (leader for term T) commits a new log entry from its term, and S5 is elected leader for a later term U, then there must be at least one server (S3) that accepted the log entry and also voted for S5.

图 9:如果 S1(term T 的 leader)提交了一个来自自己 term 的 new log entry,而 S5 在之后的 term U 中被选为 leader,那么至少存在一个 server(S3)既接受了该 log entry,也投票给了 S5。

To eliminate problems like the one in Figure 8, Raft never commits log entries from previous terms by counting replicas.

为了消除图 8 中那类问题,Raft 永远不会通过统计 replicas 来提交 previous terms 的 log entries。

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.

只有 leader current term 的 log entries 会通过统计 replicas 的方式提交;current term 的 entry 以这种方式 committed 后,所有此前的 entries 都会由于 Log Matching Property 而被间接提交。

There are some situations where a leader could safely conclude that an older log entry is committed (for example, if that entry is stored on every server), but Raft takes a more conservative approach for simplicity.

在某些情况下,leader 可以安全地断定 older log entry 已 committed(例如该 entry 存储在每个 server 上),但为了简单起见,Raft 采取了更保守的方法。

Raft incurs this extra complexity in the commitment rules because log entries retain their original term numbers when a leader replicates entries from previous terms.

Raft 在 commitment rules 中引入这项额外复杂性,是因为 leader 复制 previous terms 的 entries 时,log entries 会保留原始 term numbers。

In other consensus algorithms, if a new leader re-replicates entries from prior “terms,” it must do so with its new “term number.”

在其他 consensus algorithms 中,如果 new leader 重新复制 prior “terms” 的 entries,就必须使用自己的 new “term number” 来完成。

Raft’s approach makes it easier to reason about log entries, since they maintain the same term number over time and across logs.

Raft 的方法更容易推理 log entries,因为它们在时间上以及不同 logs 之间都保持相同的 term number。

In addition, new leaders in Raft send fewer log entries from previous terms than in other algorithms (other algorithms must send redundant log entries to renumber them before they can be committed).

此外,与其他 algorithms 相比,Raft 的 new leaders 发送的 previous terms log entries 更少(其他 algorithms 必须先发送冗余 log entries 为它们重新编号,之后才能提交)。

5.4.3 Safety argument

5.4.3 Safety argument

5.4.3 Safety argument。

Given the complete Raft algorithm, we can now argue more precisely that the Leader Completeness Property holds (this argument is based on the safety proof; see Section 9.2).

有了完整的 Raft algorithm,我们现在可以更精确地论证 Leader Completeness Property 成立(该论证基于 safety proof,见第 9.2 节)。

We assume that the Leader Completeness Property does not hold, then we prove a contradiction.

我们假设 Leader Completeness Property 不成立,然后证明这会导致 contradiction。

Suppose the leader for term T (leaderT) commits a log entry from its term, but that log entry is not stored by the leader of some future term.

假设 term T 的 leader(leaderT)提交了一个来自其自身 term 的 log entry,但某个 future term 的 leader 并没有存储该 log entry。

Consider the smallest term U > T whose leader (leaderU) does not store the entry.

考虑满足 U > T 且其 leader(leaderU)不存储该 entry 的最小 term U。

  1. The committed entry must have been absent from leaderU’s log at the time of its election (leaders never delete or overwrite entries).
  1. 在 leaderU 当选时,该 committed entry 必然不在 leaderU 的 log 中(leaders 永远不会删除或覆盖 entries)。
  1. leaderT replicated the entry on a majority of the cluster, and leaderU received votes from a majority of the cluster. Thus, at least one server (“the voter”) both accepted the entry from leaderT and voted for leaderU, as shown in Figure 9.
  1. leaderT 将 entry 复制到了 cluster majority,而 leaderU 从 cluster majority 获得了 votes。因此,至少有一个 server(“the voter”)既接受了 leaderT 的 entry,也投票给 leaderU,如图 9 所示。

The voter is key to reaching a contradiction.

the voter 是得到 contradiction 的关键。

  1. The voter must have accepted the committed entry from leaderT before voting for leaderU; otherwise it would have rejected the AppendEntries request from leaderT (its current term would have been higher than T).
  1. the voter 必须在投票给 leaderU 之前就接受了 leaderT 的 committed entry;否则它会拒绝 leaderT 的 AppendEntries request(它的 current term 会高于 T)。
  1. The voter still stored the entry when it voted for leaderU, since every intervening leader contained the entry (by assumption), leaders never remove entries, and followers only remove entries if they conflict with the leader.
  1. the voter 在投票给 leaderU 时仍然存储着该 entry,因为(根据假设)每个 intervening leader 都包含该 entry,leaders 不会删除 entries,而 followers 只有在 entries 与 leader 冲突时才会删除它们。
  1. The voter granted its vote to leaderU, so leaderU’s log must have been as up-to-date as the voter’s.
  1. the voter 将自己的 vote 给了 leaderU,因此 leaderU 的 log 必须至少与 the voter 的 log 一样 up-to-date。

This leads to one of two contradictions.

这会导致两种 contradiction 之一。

  1. First, if the voter and leaderU shared the same last log term, then leaderU’s log must have been at least as long as the voter’s, so its log contained every entry in the voter’s log.
  1. 首先,如果 the voter 和 leaderU 的 last log term 相同,那么 leaderU 的 log 必须至少和 the voter 一样长,因此它的 log 会包含 the voter log 中的每个 entry。

This is a contradiction, since the voter contained the committed entry and leaderU was assumed not to.

这就产生 contradiction,因为 the voter 包含 committed entry,而假设 leaderU 不包含它。

  1. Otherwise, leaderU’s last log term must have been larger than the voter’s.
  1. 否则,leaderU 的 last log term 必须大于 the voter 的 last log term。

Moreover, it was larger than T, since the voter’s last log term was at least T (it contains the committed entry from term T).

而且它必须大于 T,因为 the voter 的 last log term 至少是 T(它包含 term T 的 committed entry)。

The earlier leader that created leaderU’s last log entry must have contained the committed entry in its log (by assumption).

创建 leaderU 最后一个 log entry 的 earlier leader 必须在其 log 中包含 committed entry(根据假设)。

Then, by the Log Matching Property, leaderU’s log must also contain the committed entry, which is a contradiction.

那么根据 Log Matching Property,leaderU 的 log 也必须包含 committed entry,这就产生 contradiction。

  1. This completes the contradiction. Thus, the leaders of all terms greater than T must contain all entries from term T that are committed in term T.
  1. 这就完成了 contradiction。因此,所有大于 T 的 terms 的 leaders,都必须包含 term T 中在 term T 里 committed 的全部 entries。
  1. The Log Matching Property guarantees that future leaders will also contain entries that are committed indirectly, such as index 2 in Figure 8(d).
  1. Log Matching Property 保证 future leaders 也会包含那些被间接 committed 的 entries,例如图 8(d) 中的 index 2。

Given the Leader Completeness Property, we can prove the State Machine Safety Property from Figure 3, which states that if a server has applied a log entry at a given index to its state machine, no other server will ever apply a different log entry for the same index.

有了 Leader Completeness Property,我们就可以证明图 3 中的 State Machine Safety Property:如果某个 server 已经将给定 index 的 log entry 应用到自己的 state machine,那么其他 server 永远不会为同一个 index 应用不同的 log entry。

At the time a server applies a log entry to its state machine, its log must be identical to the leader’s log up through that entry and the entry must be committed.

server 将 log entry 应用到 state machine 时,它的 log 必须与 leader 的 log 在该 entry 之前完全相同,并且该 entry 必须是 committed 的。

Now consider the lowest term in which any server applies a given log index; the Log Completeness Property guarantees that the leaders for all higher terms will store that same log entry, so servers that apply the index in later terms will apply the same value.

现在考虑任意 server 应用某个 log index 的最低 term;Log Completeness Property 保证所有更高 terms 的 leaders 都会存储同一个 log entry,因此在后续 terms 中应用该 index 的 servers 会应用相同的 value。

Thus, the State Machine Safety Property holds.

因此,State Machine Safety Property 成立。

Finally, Raft requires servers to apply entries in log index order.

最后,Raft 要求 servers 按 log index order 应用 entries。

Combined with the State Machine Safety Property, this means that all servers will apply exactly the same set of log entries to their state machines, in the same order.

结合 State Machine Safety Property,这意味着所有 servers 都会以相同顺序,将完全相同的一组 log entries 应用到各自的 state machines。

第 10 页:Follower/candidate crash、timing 与成员变更入口

raft p10

5.5 Follower and candidate crashes

5.5 Follower and candidate crashes

5.5 Follower and candidate crashes。

Until this point we have focused on leader failures.

到这里为止,我们一直聚焦于 leader failures。

Follower and candidate crashes are much simpler to handle than leader crashes, and they are both handled in the same way.

Follower 和 candidate crashes 比 leader crashes 容易处理得多,而且二者用同一种方式处理。

If a follower or candidate crashes, then future RequestVote and AppendEntries RPCs sent to it will fail.

如果 follower 或 candidate crash,那么之后发送给它的 RequestVote 和 AppendEntries RPCs 都会失败。

Raft handles these failures by retrying indefinitely; if the crashed server restarts, then the RPC will complete successfully.

Raft 通过无限重试来处理这些 failures;如果 crashed server 重启,RPC 最终就会成功完成。

If a server crashes after completing an RPC but before responding, then it will receive the same RPC again after it restarts.

如果 server 在完成 RPC 但尚未发送 response 后 crash,那么重启后会再次收到相同的 RPC。

Raft RPCs are idempotent, so this causes no harm.

Raft RPCs 是 idempotent 的,因此这不会造成问题。

For example, if a follower receives an AppendEntries request that includes log entries already present in its log, it ignores those entries in the new request.

例如,如果 follower 收到的 AppendEntries request 包含已经存在于其 log 中的 log entries,它会忽略 new request 中的这些 entries。

5.6 Timing and availability

5.6 Timing and availability

5.6 Timing and availability。

One of our requirements for Raft is that safety must not depend on timing: the system must not produce incorrect results just because some event happens more quickly or slowly than expected.

Raft 的要求之一是 safety 不能依赖 timing:系统不能仅仅因为某个事件比预期更快或更慢发生,就产生错误结果。

However, availability (the ability of the system to respond to clients in a timely manner) must inevitably depend on timing.

但是,availability(系统及时响应 clients 的能力)不可避免地依赖 timing。

For example, if message exchanges take longer than the typical time between server crashes, candidates will not stay up long enough to win an election; without a steady leader, Raft cannot make progress.

例如,如果 message exchanges 比 server crashes 之间的典型时间还长,candidates 就无法保持运行足够长的时间来赢得 election;没有稳定的 leader,Raft 就无法推进。

Leader election is the aspect of Raft where timing is most critical.

Leader election 是 Raft 中 timing 最关键的部分。

Raft will be able to elect and maintain a steady leader as long as the system satisfies the following timing requirement:

只要系统满足以下 timing requirement,Raft 就能够选出并维持一个稳定的 leader:

broadcastTime ≪ electionTimeout ≪ MTBF

broadcastTime ≪ electionTimeout ≪ MTBF。

In this inequality broadcastTime is the average time it takes a server to send RPCs in parallel to every server in the cluster and receive their responses; electionTimeout is the election timeout described in Section 5.2; and MTBF is the average time between failures for a single server.

在这个不等式中,broadcastTime 是 server 并行向 cluster 中每个 server 发送 RPCs 并接收 responses 所需的平均时间;electionTimeout 是第 5.2 节描述的 election timeout;MTBF 是单个 server 两次 failures 之间的平均时间。

The broadcast time should be an order of magnitude less than the election timeout so that leaders can reliably send the heartbeat messages required to keep followers from starting elections; given the randomized approach used for election timeouts, this inequality also makes split votes unlikely.

broadcast time 应比 election timeout 小一个数量级,这样 leaders 才能可靠发送 heartbeat messages,阻止 followers 开始 elections;鉴于 election timeouts 使用 randomized approach,该不等式也会降低 split votes 的可能性。

The election timeout should be a few orders of magnitude less than MTBF so that the system makes steady progress.

election timeout 应比 MTBF 小几个数量级,从而让系统持续推进。

When the leader crashes, the system will be unavailable for roughly the election timeout; we would like this to represent only a small fraction of overall time.

leader crash 时,系统大约会在一个 election timeout 内不可用;我们希望这只占总时间的一小部分。

The broadcast time and MTBF are properties of the underlying system, while the election timeout is something we must choose.

broadcast time 和 MTBF 是底层系统的 properties,而 election timeout 是我们必须选择的参数。

Raft’s RPCs typically require the recipient to persist information to stable storage, so the broadcast time may range from 0.5ms to 20ms, depending on storage technology.

Raft 的 RPCs 通常要求接收方将 information 持久化到 stable storage,因此 broadcast time 可能根据 storage technology 的不同处于 0.5ms~20ms 范围。

As a result, the election timeout is likely to be somewhere between 10ms and 500ms.

因此,election timeout 很可能处于 10ms~500ms 之间。

Typical server MTBFs are several months or more, which easily satisfies the timing requirement.

典型 server 的 MTBF 是数月或更长,很容易满足该 timing requirement。

6 Cluster membership changes

6 Cluster membership changes

6 Cluster membership changes。

Up until now we have assumed that the cluster configuration (the set of servers participating in the consensus algorithm) is fixed.

到目前为止,我们一直假设 cluster configuration(参与 consensus algorithm 的 servers 集合)是固定的。

In practice, it will occasionally be necessary to change the configuration, for example to replace servers when they fail or to change the degree of replication.

实践中偶尔必须修改 configuration,例如在 servers failures 后替换 servers,或改变 replication degree。

Although this can be done by taking the entire cluster off-line, updating configuration files, and then restarting the cluster, this would leave the cluster unavailable during the changeover.

虽然可以让整个 cluster off-line、更新 configuration files,再重启 cluster,但这样会让 cluster 在切换期间不可用。

In addition, if there are any manual steps, they risk operator error.

此外,只要存在任何 manual steps,就存在 operator error 风险。

In order to avoid these issues, we decided to automate configuration changes and incorporate them into the Raft consensus algorithm.

为了避免这些问题,我们决定自动化 configuration changes,并把它们纳入 Raft consensus algorithm。

For the configuration change mechanism to be safe, there must be no point during the transition where it is possible for two leaders to be elected for the same term.

要让 configuration change mechanism safe,transition 期间不能存在任何一个时刻,使同一 term 可以选出两个 leaders。

Unfortunately, any approach where servers switch directly from the old configuration to the new configuration is unsafe.

遗憾的是,任何让 servers 直接从 old configuration 切换到 new configuration 的方法都是 unsafe 的。

It isn’t possible to atomically switch all of the servers at once, so the cluster can potentially split into two independent majorities during the transition (see Figure 10).

不可能一次性 atomically 切换所有 servers,因此 transition 期间 cluster 可能分裂成两个独立的 majorities(见图 10)。

Figure 10: Switching directly from one configuration to another is unsafe because different servers will switch at different times.

图 10:从一个 configuration 直接切换到另一个 configuration 是 unsafe 的,因为不同 servers 会在不同时间完成切换。

In this example, the cluster grows from three servers to five.

在这个例子中,cluster 从三个 servers 增长到五个。

Unfortunately, there is a point in time where two different leaders can be elected for the same term, one with a majority of the old configuration (Cold) and another with a majority of the new configuration (Cnew).

遗憾的是,存在一个时刻,同一个 term 可以选出两个不同 leaders:一个拥有 old configuration(Cold)的 majority,另一个拥有 new configuration(Cnew)的 majority。

第 11 页:Joint consensus 与配置变更

raft p11

In order to ensure safety, configuration changes must use a two-phase approach.

为了保证 safety,configuration changes 必须使用 two-phase approach。

There are a variety of ways to implement the two phases.

实现这两个 phases 有多种方式。

For example, some systems (e.g., [22]) use the first phase to disable the old configuration so it cannot process client requests; then the second phase enables the new configuration.

例如,一些 systems(如 [22])在第一阶段禁用 old configuration,使其不能处理 client requests;然后在第二阶段启用 new configuration。

In Raft the cluster first switches to a transitional configuration we call joint consensus; once the joint consensus has been committed, the system then transitions to the new configuration.

在 Raft 中,cluster 首先切换到一种称为 joint consensus 的过渡 configuration;joint consensus committed 后,系统再切换到 new configuration。

The joint consensus combines both the old and new configurations:

Joint consensus 同时包含 old 和 new configurations:

Log entries are replicated to all servers in both configurations.

Log entries 会复制到两套 configurations 中的所有 servers。

Any server from either configuration may serve as leader.

来自任一 configuration 的 server 都可以担任 leader。

Agreement (for elections and entry commitment) requires separate majorities from both the old and new configurations.

Agreement(包括 elections 和 entry commitment)需要分别获得 old 和 new configurations 的 majorities。

The joint consensus allows individual servers to transition between configurations at different times without compromising safety.

Joint consensus 允许各个 servers 在不同时间完成 configuration transition,而不会损害 safety。

Furthermore, joint consensus allows the cluster to continue servicing client requests throughout the configuration change.

此外,joint consensus 允许 cluster 在整个 configuration change 期间继续服务 client requests。

Cluster configurations are stored and communicated using special entries in the replicated log; Figure 11 illustrates the configuration change process.

Cluster configurations 通过 replicated log 中的 special entries 存储和传播;图 11 展示了 configuration change process。

When the leader receives a request to change the configuration from Cold to Cnew, it stores the configuration for joint consensus (Cold,new in the figure) as a log entry and replicates that entry using the mechanisms described previously.

leader 收到将 configuration 从 Cold 改为 Cnew 的 request 后,会把 joint consensus configuration(图中的 Cold,new)作为 log entry 存储,并使用前面描述的 mechanisms 复制该 entry。

Once a given server adds the new configuration entry to its log, it uses that configuration for all future decisions (a server always uses the latest configuration in its log, regardless of whether the entry is committed).

某个 server 将 new configuration entry 加入自己的 log 后,就会在所有后续 decisions 中使用该 configuration(server 总是使用自己 log 中最新的 configuration,不论该 entry 是否 committed)。

This means that the leader will use the rules of Cold,new to determine when the log entry for Cold,new is committed.

这意味着,leader 会使用 Cold,new 的 rules 来决定 Cold,new 的 log entry 何时 committed。

If the leader crashes, a new leader may be chosen under either Cold or Cold,new, depending on whether the winning candidate has received Cold,new.

如果 leader crash,new leader 可能依据 Cold 或 Cold,new 选出,取决于 winning candidate 是否收到 Cold,new。

In any case, Cnew cannot make unilateral decisions during this period.

无论如何,Cnew 在此期间都不能做出 unilateral decisions。

Once Cold,new has been committed, neither Cold nor Cnew can make decisions without approval of the other, and the Leader Completeness Property ensures that only servers with the Cold,new log entry can be elected as leader.

Cold,new committed 后,Cold 和 Cnew 中任一方都不能在没有另一方批准的情况下做 decisions;Leader Completeness Property 保证只有拥有 Cold,new log entry 的 servers 才能被选为 leader。

It is now safe for the leader to create a log entry describing Cnew and replicate it to the cluster.

此时,leader 可以安全地创建描述 Cnew 的 log entry,并将其复制到 cluster。

Again, this configuration will take effect on each server as soon as it is seen.

同样,各 server 一看到该 configuration,它就会在该 server 上生效。

When the new configuration has been committed under the rules of Cnew, the old configuration is irrelevant and servers not in the new configuration can be shut down.

new configuration 按 Cnew 的 rules committed 后,old configuration 就不再重要,不属于 new configuration 的 servers 可以关闭。

Figure 11: Timeline for a configuration change. Dashed lines show configuration entries that have been created but not committed, and solid lines show the latest committed configuration entry.

图 11:configuration change 的时间线。虚线表示已经创建但尚未 committed 的 configuration entries,实线表示最新的 committed configuration entry。

The leader first creates the Cold,new configuration entry in its log and commits it to Cold,new (a majority of Cold and a majority of Cnew).

leader 首先在自己的 log 中创建 Cold,new configuration entry,并将其提交到 Cold,new(即 Cold 的 majority 和 Cnew 的 majority)。

Then it creates the Cnew entry and commits it to a majority of Cnew.

然后它创建 Cnew entry,并将其提交到 Cnew 的 majority。

There is no point in time in which Cold and Cnew can both make decisions independently.

不存在 Cold 和 Cnew 能够同时独立做 decisions 的时刻。

There are three more issues to address for reconfiguration.

Reconfiguration 还需要处理三个问题。

The first issue is that new servers may not initially store any log entries.

第一个问题是,new servers 初始可能没有存储任何 log entries。

If they are added to the cluster in this state, it could take quite a while for them to catch up, during which time it might not be possible to commit new log entries.

如果在这种状态下把它们加入 cluster,它们可能需要很长时间才能 catch up,而在此期间可能无法提交 new log entries。

In order to avoid availability gaps, Raft introduces an additional phase before the configuration change, in which the new servers join the cluster as non-voting members.

为了避免 availability gaps,Raft 在 configuration change 之前增加一个 phase,让 new servers 以 non-voting members 身份加入 cluster。

The leader replicates log entries to them, but they are not considered for majorities.

leader 会向它们复制 log entries,但它们不计入 majorities。

Once the new servers have caught up with the rest of the cluster, the reconfiguration can proceed as described above.

new servers 与 cluster 其余部分 catch up 后,reconfiguration 就可以按上文所述继续。

The second issue is that the cluster leader may not be part of the new configuration.

第二个问题是,cluster leader 可能不属于 new configuration。

In this case, the leader steps down (returns to follower state) once it has committed the Cnew log entry.

此时,leader 一旦提交 Cnew log entry,就会 step down(返回 follower state)。

This means that there will be a period of time (while it is committing Cnew) when the leader is managing a cluster that does not include itself; it replicates log entries but does not count itself in majorities.

这意味着,在提交 Cnew 的期间,会有一段时间 leader 管理的 cluster 并不包含它自己;它会复制 log entries,但不把自己计入 majorities。

The leader transition occurs when Cnew is committed because this is the first point when the new configuration can operate independently.

leader transition 发生在 Cnew committed 时,因为这是 new configuration 第一次可以独立运行的时刻。

Before this point, it may be the case that only a server from Cold can be elected leader.

在此之前,可能只有来自 Cold 的 server 能够被选为 leader。

The third issue is that removed servers (those not in Cnew) can disrupt the cluster.

第三个问题是,removed servers(不属于 Cnew 的 servers)可能干扰 cluster。

These servers will not receive heartbeats, so they will time out and start new elections.

这些 servers 收不到 heartbeats,因此会 timeout 并开始 new elections。

They will then send RequestVote RPCs with new term numbers, and this will cause the current leader to revert to follower state.

然后它们会发送带有 new term numbers 的 RequestVote RPCs,这会导致 current leader 退回 follower state。

A new leader will eventually be elected, but the removed servers will time out again and the process will repeat, resulting in poor availability.

最终会选出 new leader,但 removed servers 会再次 timeout,流程会重复,从而导致 poor availability。

To prevent this problem, servers disregard RequestVote RPCs when they believe a current leader exists.

为防止这个问题,当 servers 认为 current leader 存在时,它们会忽略 RequestVote RPCs。

Specifically, if a server receives a RequestVote RPC within the minimum election timeout of hearing from a current leader, it does not update its term or grant its vote.

具体来说,如果 server 在听到 current leader 消息后的 minimum election timeout 内收到 RequestVote RPC,它不会更新 term,也不会授予 vote。

This does not affect normal elections, where each server waits at least a minimum election timeout before starting an election.

这不会影响正常 elections,因为每个 server 都会至少等待一个 minimum election timeout 后才开始 election。

However, it helps avoid disruptions from removed servers: if a leader is able to get heartbeats to its cluster, then it will not be deposed by larger term numbers.

但是,这有助于避免 removed servers 带来的干扰:如果 leader 能够向自己的 cluster 发送 heartbeats,就不会被更大的 term numbers 罢免。

7 Log compaction

7 Log compaction

7 Log compaction。

Raft’s log grows during normal operation to incorporate more client requests, but in a practical system, it cannot grow without bound.

Raft 的 log 在正常运行时会不断增长,以纳入更多 client requests;但在实际系统中,它不能无限增长。

As the log grows longer, it occupies more space and takes more time to replay.

log 越长,占用的空间越多,replay 所需的时间也越长。

This will eventually cause availability problems without some mechanism to discard obsolete information that has accumulated in the log.

如果没有机制丢弃 log 中累积的 obsolete information,最终会导致 availability problems。

第 12 页:Snapshot 与 InstallSnapshot

raft p12

Figure 12: A server replaces the committed entries in its log (indexes 1 through 5) with a new snapshot, which stores just the current state (variables x and y in this example).

图 12:server 用一个 new snapshot 替换 log 中已 committed 的 entries(index 1 到 5);该 snapshot 只存储 current state(本例中的 variables x 和 y)。

The snapshot’s last included index and term serve to position the snapshot in the log preceding entry 6.

snapshot 的 last included index 和 term 用于在 log 中定位 snapshot,使它位于 entry 6 之前。

Snapshotting is the simplest approach to compaction.

Snapshotting 是最简单的 compaction 方法。

In snapshotting, the entire current system state is written to a snapshot on stable storage, then the entire log up to that point is discarded.

在 snapshotting 中,整个 current system state 会写入 stable storage 上的 snapshot,然后丢弃截至该位置的整个 log。

Snapshotting is used in Chubby and ZooKeeper, and the remainder of this section describes snapshotting in Raft.

Chubby 和 ZooKeeper 都使用 snapshotting,本节剩余部分将描述 Raft 中的 snapshotting。

Incremental approaches to compaction, such as log cleaning [36] and log-structured merge trees [30, 5], are also possible.

也可以使用 incremental compaction approaches,例如 log cleaning [36] 和 log-structured merge trees [30, 5]。

These operate on a fraction of the data at once, so they spread the load of compaction more evenly over time.

这些方法每次只处理部分 data,因此会把 compaction 的负载更均匀地分散到时间轴上。

They first select a region of data that has accumulated many deleted and overwritten objects, then they rewrite the live objects from that region more compactly and free the region.

它们首先选择一个积累了大量 deleted 和 overwritten objects 的 data region,然后更紧凑地重写该 region 中的 live objects,并释放这个 region。

This requires significant additional mechanism and complexity compared to snapshotting, which simplifies the problem by always operating on the entire data set.

与 snapshotting 相比,这需要大量额外的 mechanism 和 complexity;snapshotting 总是处理整个 data set,从而简化了问题。

While log cleaning would require modifications to Raft, state machines can implement LSM trees using the same interface as snapshotting.

虽然 log cleaning 需要修改 Raft,但 state machines 可以使用与 snapshotting 相同的 interface 实现 LSM trees。

Figure 12 shows the basic idea of snapshotting in Raft.

图 12 展示了 Raft 中 snapshotting 的基本思想。

Each server takes snapshots independently, covering just the committed entries in its log.

每个 server 独立创建 snapshots,只覆盖自己 log 中已经 committed 的 entries。

Most of the work consists of the state machine writing its current state to the snapshot.

大部分工作是由 state machine 将 current state 写入 snapshot。

Raft also includes a small amount of metadata in the snapshot: the last included index is the index of the last entry in the log that the snapshot replaces (the last entry the state machine had applied), and the last included term is the term of this entry.

Raft 还会在 snapshot 中包含少量 metadata:last included index 是 snapshot 替换的 log 中最后一个 entry 的 index(即 state machine 已应用的最后一个 entry),last included term 是该 entry 的 term。

These are preserved to support the AppendEntries consistency check for the first log entry following the snapshot, since that entry needs a previous log index and term.

保留这些信息是为了支持 snapshot 后第一个 log entry 的 AppendEntries consistency check,因为该 entry 需要一个 previous log index 和 term。

To enable cluster membership changes (Section 6), the snapshot also includes the latest configuration in the log as of last included index.

为了支持 cluster membership changes(第 6 节),snapshot 还包含截至 last included index 时 log 中的 latest configuration。

Once a server completes writing a snapshot, it may delete all log entries up through the last included index, as well as any prior snapshot.

server 完成 snapshot 写入后,可以删除截至 last included index 的所有 log entries,以及任何 prior snapshot。

Although servers normally take snapshots independently, the leader must occasionally send snapshots to followers that lag behind.

虽然 servers 通常独立创建 snapshots,但 leader 偶尔必须向落后的 followers 发送 snapshots。

This happens when the leader has already discarded the next log entry that it needs to send to a follower.

当 leader 已经丢弃了本来需要发送给 follower 的下一个 log entry 时,就会发生这种情况。

Fortunately, this situation is unlikely in normal operation: a follower that has kept up with the leader would already have this entry.

幸运的是,这种情况在正常运行中不太可能发生:跟上 leader 的 follower 已经拥有该 entry。

However, an exceptionally slow follower or a new server joining the cluster (Section 6) would not.

但是,特别缓慢的 follower 或加入 cluster 的 new server(第 6 节)可能没有该 entry。

The way to bring such a follower up-to-date is for the leader to send it a snapshot over the network.

让这类 follower up-to-date 的方法,是由 leader 通过 network 向它发送 snapshot。

InstallSnapshot RPC

InstallSnapshot RPC。

Invoked by leader to send chunks of a snapshot to a follower. Leaders always send chunks in order.

由 leader 调用,用于向 follower 发送 snapshot chunks。Leaders 总是按顺序发送 chunks。

Arguments: term: leader’s term; leaderId: so follower can redirect clients; lastIncludedIndex: the snapshot replaces all entries up through and including this index; lastIncludedTerm: term of lastIncludedIndex; offset: byte offset where chunk is positioned in the snapshot file; data[]: raw bytes of the snapshot chunk, starting at offset; done: true if this is the last chunk

Arguments:term:leader 的 term;leaderId:让 follower 能重定向 clients;lastIncludedIndex:snapshot 替换截至并包括该 index 的所有 entries;lastIncludedTerm:lastIncludedIndex 的 term;offset:chunk 在 snapshot file 中的 byte offset;data[]:从 offset 开始的 snapshot chunk 原始 bytes;done:如果这是最后一个 chunk,则为 true。

Results: term: currentTerm, for leader to update itself

Results:term:currentTerm,供 leader 更新自身。

Receiver implementation: 1. Reply immediately if term < currentTerm 2. Create new snapshot file if first chunk (offset is 0) 3. Write data into snapshot file at given offset 4. Reply and wait for more data chunks if done is false 5. Save snapshot file, discard any existing or partial snapshot with a smaller index 6. If existing log entry has same index and term as snapshot’s last included entry, retain log entries following it and reply 7. Discard the entire log 8. Reset state machine using snapshot contents (and load snapshot’s cluster configuration)

Receiver implementation:1. 如果 term < currentTerm,立即回复;2. 如果这是第一个 chunk(offset 为 0),创建 new snapshot file;3. 在给定 offset 将 data 写入 snapshot file;4. 如果 done 为 false,则回复并等待更多 data chunks;5. 保存 snapshot file,丢弃任何 index 更小的 existing 或 partial snapshot;6. 如果已有 log entry 的 index 和 term 与 snapshot 的 last included entry 相同,则保留它后面的 log entries 并回复;7. 丢弃整个 log;8. 使用 snapshot contents 重置 state machine(并加载 snapshot 的 cluster configuration)。

Figure 13: A summary of the InstallSnapshot RPC. Snapshots are split into chunks for transmission; this gives the follower a sign of life with each chunk, so it can reset its election timer.

图 13:InstallSnapshot RPC 摘要。Snapshots 会被拆成 chunks 进行传输;每个 chunk 都向 follower 表明 leader 仍然存活,因此 follower 可以重置 election timer。

The leader uses a new RPC called InstallSnapshot to send snapshots to followers that are too far behind; see Figure 13.

leader 使用名为 InstallSnapshot 的 new RPC,向落后太多的 followers 发送 snapshots;见图 13。

When a follower receives a snapshot with this RPC, it must decide what to do with its existing log entries.

follower 通过该 RPC 收到 snapshot 后,必须决定如何处理现有 log entries。

Usually the snapshot will contain new information not already in the recipient’s log.

通常,snapshot 会包含 recipient log 中尚不存在的新 information。

In this case, the follower discards its entire log; it is all superseded by the snapshot and may possibly have uncommitted entries that conflict with the snapshot.

此时,follower 丢弃整个 log;snapshot 已经替代了整个 log,而且该 log 可能包含与 snapshot 冲突的 uncommitted entries。

If instead the follower receives a snapshot that describes a prefix of its log (due to retransmission or by mistake), then log entries covered by the snapshot are deleted but entries following the snapshot are still valid and must be retained.

如果 follower 收到的 snapshot 描述的是自己 log 的 prefix(可能由于 retransmission 或误操作),那么 snapshot 覆盖的 log entries 会被删除,但 snapshot 之后的 entries 仍然有效,必须保留。

This snapshotting approach departs from Raft’s strong leader principle, since followers can take snapshots without the knowledge of the leader.

这种 snapshotting approach 偏离了 Raft 的 strong leader principle,因为 followers 可以在 leader 不知情的情况下创建 snapshots。

However, we think this departure is justified.

但是,我们认为这种偏离是合理的。

While having a leader helps avoid conflicting decisions in reaching consensus, consensus has already been reached when snapshotting, so no decisions conflict.

leader 有助于在达成 consensus 时避免 conflicting decisions;但 snapshotting 发生时 consensus 已经达成,因此不会有 decisions 发生冲突。

Data still only flows from leaders to followers.

Data 仍然只从 leaders 流向 followers。

第 13 页:Snapshot 性能、Client interaction 与 Evaluation

raft p13

Data still only flows from leaders to followers.

Data 仍然只从 leaders 流向 followers。

We considered an alternative leader-based approach in which only the leader would create a snapshot, then it would send this snapshot to each of its followers.

我们考虑过另一种 leader-based approach:只有 leader 创建 snapshot,然后将 snapshot 发送给自己的每个 follower。

However, this has two disadvantages.

但是,这有两个缺点。

First, sending the snapshot to each follower would waste network bandwidth and slow the snapshotting process.

第一,将 snapshot 发送给每个 follower 会浪费 network bandwidth,并减慢 snapshotting process。

Each follower already has the information needed to produce its own snapshots, and it is typically much cheaper for a server to produce a snapshot from its local state than it is to send and receive one over the network.

每个 follower 已经拥有生成自己 snapshot 所需的信息;通常,server 从 local state 生成 snapshot 的成本远低于通过 network 发送和接收 snapshot 的成本。

Second, the leader’s implementation would be more complex.

第二,leader 的 implementation 会更复杂。

For example, the leader would need to send snapshots to followers in parallel with replicating new log entries to them, so as not to block new client requests.

例如,leader 必须在向 followers 复制 new log entries 的同时并行发送 snapshots,以免阻塞 new client requests。

There are two more issues that impact snapshotting performance.

还有两个问题会影响 snapshotting performance。

First, servers must decide when to snapshot.

第一,servers 必须决定何时 snapshot。

If a server snapshots too often, it wastes disk bandwidth and energy; if it snapshots too infrequently, it risks exhausting its storage capacity, and it increases the time required to replay the log during restarts.

如果 server snapshot 过于频繁,就会浪费 disk bandwidth 和 energy;如果过于少,可能耗尽 storage capacity,并增加 restart 时 replay log 所需的时间。

One simple strategy is to take a snapshot when the log reaches a fixed size in bytes.

一种简单策略是:当 log 达到固定 byte size 时创建 snapshot。

If this size is set to be significantly larger than the expected size of a snapshot, then the disk bandwidth overhead for snapshotting will be small.

如果将这个 size 设为明显大于 snapshot 预期大小,那么 snapshotting 带来的 disk bandwidth overhead 就会很小。

The second performance issue is that writing a snapshot can take a significant amount of time, and we do not want this to delay normal operations.

第二个 performance issue 是写入 snapshot 可能耗费相当长时间,而我们不希望它延迟 normal operations。

The solution is to use copy-on-write techniques so that new updates can be accepted without impacting the snapshot being written.

解决方案是使用 copy-on-write techniques,使得接受 new updates 时不影响正在写入的 snapshot。

For example, state machines built with functional data structures naturally support this.

例如,使用 functional data structures 构建的 state machines 天然支持这一点。

Alternatively, the operating system’s copy-on-write support (e.g., fork on Linux) can be used to create an in-memory snapshot of the entire state machine (our implementation uses this approach).

也可以使用 operating system 的 copy-on-write support(例如 Linux 上的 fork)创建整个 state machine 的 in-memory snapshot(我们的 implementation 使用这种方法)。

8 Client interaction

8 Client interaction

8 Client interaction。

This section describes how clients interact with Raft, including how clients find the cluster leader and how Raft supports linearizable semantics [10].

本节描述 clients 如何与 Raft 交互,包括 clients 如何找到 cluster leader,以及 Raft 如何支持 linearizable semantics [10]。

These issues apply to all consensus-based systems, and Raft’s solutions are similar to other systems.

这些问题适用于所有 consensus-based systems,而 Raft 的 solutions 与其他 systems 类似。

Clients of Raft send all of their requests to the leader.

Raft 的 clients 将所有 requests 发送给 leader。

When a client first starts up, it connects to a randomly-chosen server.

client 初次启动时,会连接到一个 randomly-chosen server。

If the client’s first choice is not the leader, that server will reject the client’s request and supply information about the most recent leader it has heard from (AppendEntries requests include the network address of the leader).

如果 client 首先选择的 server 不是 leader,该 server 会拒绝 client request,并提供自己最近听说的 leader 的 information(AppendEntries requests 包含 leader 的 network address)。

If the leader crashes, client requests will time out; clients then try again with randomly-chosen servers.

如果 leader crash,client requests 会 timeout;随后 clients 会再次尝试 randomly-chosen servers。

Our goal for Raft is to implement linearizable semantics (each operation appears to execute instantaneously, exactly once, at some point between its invocation and its response).

Raft 的目标是实现 linearizable semantics(每个 operation 看起来都在 invocation 和 response 之间的某个时刻 instantaneously、exactly once 地执行)。

However, as described so far Raft can execute a command multiple times.

但是,按照目前的描述,Raft 可能多次执行同一个 command。

For example, if the leader crashes after committing the log entry but before responding to the client, the client will retry the command with a new leader, causing it to be executed a second time.

例如,如果 leader 在提交 log entry 后、向 client 返回 response 前 crash,client 会向 new leader 重试 command,导致它被第二次执行。

The solution is for clients to assign unique serial numbers to every command.

解决办法是让 clients 为每个 command 分配唯一 serial numbers。

Then, the state machine tracks the latest serial number processed for each client, along with the associated response.

然后,state machine 跟踪每个 client 已处理的 latest serial number,以及对应的 response。

If it receives a command whose serial number has already been executed, it responds immediately without re-executing the request.

如果它收到的 command 的 serial number 已经执行过,就立即 response,而不重新执行 request。

Read-only operations can be handled without writing anything into the log.

Read-only operations 可以在不向 log 写入任何内容的情况下处理。

However, with no additional measures, this would run the risk of returning stale data, since the leader responding to the request might have been superseded by a newer leader of which it is unaware.

但是,如果没有额外措施,这可能返回 stale data,因为响应 request 的 leader 可能已经被它不知道的 newer leader 取代。

Linearizable reads must not return stale data, and Raft needs two extra precautions to guarantee this without using the log.

Linearizable reads 不能返回 stale data,而 Raft 需要两项额外 precautions,在不使用 log 的情况下保证这一点。

First, a leader must have the latest information on which entries are committed.

第一,leader 必须拥有哪些 entries 已 committed 的最新 information。

The Leader Completeness Property guarantees that a leader has all committed entries, but at the start of its term, it may not know which those are.

Leader Completeness Property 保证 leader 拥有全部 committed entries,但在 term 开始时,它可能不知道究竟哪些 entries 已 committed。

To find out, it needs to commit an entry from its term.

为了获知这一点,它需要提交一个来自自己 term 的 entry。

Raft handles this by having each leader commit a blank no-op entry into the log at the start of its term.

Raft 的处理方式是:每个 leader 在 term 开始时向 log 提交一个 blank no-op entry。

Second, a leader must check whether it has been deposed before processing a read-only request.

第二,leader 在处理 read-only request 前必须检查自己是否已经被 deposed。

Raft handles this by having the leader exchange heartbeat messages with a majority of the cluster before responding to read-only requests.

Raft 的处理方式是:leader 在响应 read-only requests 前,与 cluster majority 交换 heartbeat messages。

Alternatively, the leader could rely on the heartbeat mechanism to provide a form of lease [9], but this would rely on timing for safety (it assumes bounded clock skew).

另一种方法是让 leader 依靠 heartbeat mechanism 提供某种 lease [9];但这会让 safety 依赖 timing(它假设 clock skew 有界)。

9 Implementation and evaluation

9 Implementation and evaluation

9 Implementation and evaluation。

We have implemented Raft as part of a replicated state machine that stores configuration information for RAMCloud [33] and assists in failover of the RAMCloud coordinator.

我们将 Raft 实现为 replicated state machine 的一部分,用于为 RAMCloud [33] 存储 configuration information,并协助 RAMCloud coordinator 的 failover。

The Raft implementation contains roughly 2000 lines of C++ code, not including tests, comments, or blank lines.

Raft implementation 约包含 2000 行 C++ code,不包括 tests、comments 和 blank lines。

The source code is freely available [23].

Source code 可自由获取 [23]。

There are also about 25 independent third-party open source implementations [34] of Raft in various stages of development, based on drafts of this paper.

此外,还有约 25 个独立的 third-party open source Raft implementations [34],处于不同开发阶段,且基于本文的 drafts。

Also, various companies are deploying Raft-based systems [34].

还有多家公司正在部署 Raft-based systems [34]。

The remainder of this section evaluates Raft using three criteria: understandability, correctness, and performance.

本节剩余部分从三个标准评估 Raft:understandability、correctness 和 performance。

9.1 Understandability

9.1 Understandability

9.1 Understandability。

To measure Raft’s understandability relative to Paxos, we conducted an experimental study using upper-level undergraduate and graduate students in an Advanced Operating Systems course at Stanford University and a Distributed Computing course at U.C. Berkeley.

为了相对于 Paxos 测量 Raft 的 understandability,我们在 Stanford University 的 Advanced Operating Systems 课程以及 U.C. Berkeley 的 Distributed Computing 课程中,使用高年级本科生和研究生开展了一项实验研究。

We recorded a video lecture of Raft and another of Paxos, and created corresponding quizzes.

我们分别录制了 Raft 和 Paxos 的 video lecture,并创建了对应的 quizzes。

The Raft lecture covered the content of this paper except for log compaction; the Paxos lecture covered enough material to create an equivalent replicated state machine, including single-decree Paxos, multi-decree Paxos, reconfiguration, and a few optimizations needed in practice (such as leader election).

Raft lecture 覆盖本文内容,但不包括 log compaction;Paxos lecture 覆盖了构建等价 replicated state machine 所需的足够材料,包括 single-decree Paxos、multi-decree Paxos、reconfiguration,以及实践所需的一些 optimizations(例如 leader election)。

The quizzes tested basic understanding of the algorithms and also required students to reason about corner cases.

Quizzes 测试对 algorithms 的基本理解,也要求学生推理 corner cases。

Each student watched one video, took the corresponding quiz, watched the second video, and took the second quiz.

每个学生先观看一个 video、完成对应 quiz,再观看第二个 video、完成第二个 quiz。

About half of the participants did the Paxos portion first and the other half did the Raft portion first in order to account for both individual differences in performance and experience gained from the first portion of the study.

约一半参与者先完成 Paxos 部分,另一半先完成 Raft 部分,以同时控制个人表现差异和研究前半部分带来的经验。

We compared participants’ scores on each quiz to determine whether participants showed a better understanding of Raft.

我们比较参与者在两个 quizzes 上的分数,以判断参与者是否对 Raft 展现出更好的理解。

第 14 页:Understandability study 与 Correctness

raft p14

Figure 14: A scatter plot comparing 43 participants’ performance on the Raft and Paxos quizzes. Points above the diagonal (33) represent participants who scored higher for Raft.

图 14:比较 43 名参与者在 Raft 和 Paxos quizzes 中表现的 scatter plot。位于对角线之上的点(33 个)表示参与者在 Raft 上得分更高。

We tried to make the comparison between Paxos and Raft as fair as possible.

我们尽力让 Paxos 与 Raft 的比较尽可能公平。

The experiment favored Paxos in two ways: 15 of the 43 participants reported having some prior experience with Paxos, and the Paxos video is 14% longer than the Raft video.

实验在两方面偏向 Paxos:43 名参与者中有 15 人表示此前有一些 Paxos 经验,而且 Paxos video 比 Raft video 长 14%。

As summarized in Table 1, we have taken steps to mitigate potential sources of bias.

如表 1 总结的那样,我们采取了措施来减轻潜在 bias sources。

All of our materials are available for review [28, 31].

我们的所有 materials 都可供 review [28, 31]。

On average, participants scored 4.9 points higher on the Raft quiz than on the Paxos quiz (out of a possible 60 points, the mean Raft score was 25.7 and the mean Paxos score was 20.8); Figure 14 shows their individual scores.

平均而言,参与者在 Raft quiz 上比 Paxos quiz 高 4.9 分(满分 60 分,Raft 平均分为 25.7,Paxos 平均分为 20.8);图 14 展示了他们的 individual scores。

A paired t-test states that, with 95% confidence, the true distribution of Raft scores has a mean at least 2.5 points larger than the true distribution of Paxos scores.

paired t-test 表明,在 95% confidence 下,Raft scores 的真实分布均值至少比 Paxos scores 的真实分布均值高 2.5 分。

We also created a linear regression model that predicts a new student’s quiz scores based on three factors: which quiz they took, their degree of prior Paxos experience, and the order in which they learned the algorithms.

我们还创建了一个 linear regression model,根据三个因素预测新学生的 quiz scores:他参加了哪个 quiz、此前 Paxos experience 的程度,以及学习 algorithms 的顺序。

The model predicts that the choice of quiz produces a 12.5-point difference in favor of Raft.

该 model 预测,quiz choice 会带来偏向 Raft 的 12.5 分差异。

This is significantly higher than the observed difference of 4.9 points, because many of the actual students had prior Paxos experience, which helped Paxos considerably, whereas it helped Raft slightly less.

这显著高于观察到的 4.9 分差异,因为许多实际参与者拥有 prior Paxos experience,这对 Paxos 帮助很大,而对 Raft 的帮助略小。

Curiously, the model also predicts scores 6.3 points lower on Raft for people that have already taken the Paxos quiz; although we don’t know why, this does appear to be statistically significant.

有趣的是,对于已经参加过 Paxos quiz 的人,model 还预测 Raft 得分低 6.3 分;虽然我们不知道原因,但这似乎具有 statistical significance。

Figure 15: Using a 5-point scale, participants were asked (left) which algorithm they felt would be easier to implement in a functioning, correct, and efficient system, and (right) which would be easier to explain to a CS graduate student.

图 15:使用 5-point scale,参与者被问及:(左)他们认为哪个 algorithm 更容易实现为 functioning、correct 且 efficient 的 system;(右)哪个 algorithm 更容易向 CS graduate student 解释。

We also surveyed participants after their quizzes to see which algorithm they felt would be easier to implement or explain; these results are shown in Figure 15.

quiz 之后,我们还调查参与者认为哪个 algorithm 更容易实现或解释;结果见图 15。

An overwhelming majority of participants reported Raft would be easier to implement and explain (33 of 41 for each question).

压倒性多数参与者认为 Raft 更容易实现和解释(两个问题都是 41 人中 33 人)。

However, these self-reported feelings may be less reliable than participants’ quiz scores, and participants may have been biased by knowledge of our hypothesis that Raft is easier to understand.

不过,这些自我报告的感受可能不如参与者的 quiz scores 可靠,而且参与者可能因为知道我们的假设——Raft 更容易理解——而产生 bias。

A detailed discussion of the Raft user study is available at [31].

Raft user study 的详细讨论见 [31]。

9.2 Correctness

9.2 Correctness

9.2 Correctness。

We have developed a formal specification and a proof of safety for the consensus mechanism described in Section 5.

我们为第 5 节描述的 consensus mechanism 开发了 formal specification 和 safety proof。

The formal specification [31] makes the information summarized in Figure 2 completely precise using the TLA+ specification language [17].

formal specification [31] 使用 TLA+ specification language [17],将图 2 总结的信息精确定义出来。

It is about 400 lines long and serves as the subject of the proof.

它大约 400 行,是 proof 的对象。

It is also useful on its own for anyone implementing Raft.

对于任何实现 Raft 的人,它本身也很有用。

We have mechanically proven the Log Completeness Property using the TLA proof system [7].

我们使用 TLA proof system [7] 对 Log Completeness Property 做了 mechanical proof。

However, this proof relies on invariants that have not been mechanically checked (for example, we have not proven the type safety of the specification).

但是,这个 proof 依赖一些尚未 mechanical checked 的 invariants(例如,我们没有证明 specification 的 type safety)。

Furthermore, we have written an informal proof [31] of the State Machine Safety property which is complete (it relies on the specification alone) and relatively precise (it is about 3500 words long).

此外,我们还为 State Machine Safety property 编写了一个 informal proof [31];它是 complete 的(只依赖 specification),并且相对 precise(约 3500 words)。

Table 1: Concerns of possible bias against Paxos in the study, steps taken to counter each, and additional materials available.

表 1:研究中可能对 Paxos 不利的 bias concerns、为应对每项 concern 采取的 steps,以及可用的 additional materials。

raft p15

Figure 16: The time to detect and replace a crashed leader. The top graph varies the amount of randomness in election timeouts, and the bottom graph scales the minimum election timeout.

图 16:检测并替换 crashed leader 所需的时间。上方图表改变 election timeouts 中的 randomness 程度,下方图表调整 minimum election timeout。

Each line represents 1000 trials (except for 100 trials for “150–150ms”) and corresponds to a particular choice of election timeouts; for example, “150–155ms” means that election timeouts were chosen randomly and uniformly between 150ms and 155ms.

每条线代表 1000 次 trials(“150–150ms”除外,它代表 100 次 trials),对应一种 election timeouts 选择;例如,“150–155ms”表示从 150ms 到 155ms 之间随机、均匀地选择 election timeouts。

The measurements were taken on a cluster of five servers with a broadcast time of roughly 15ms.

测量在一个五服务器 cluster 上进行,broadcast time 约为 15ms。

Results for a cluster of nine servers are similar.

九服务器 cluster 的结果类似。

9.3 Performance

9.3 Performance

9.3 Performance。

Raft’s performance is similar to other consensus algorithms such as Paxos.

Raft 的 performance 与 Paxos 等其他 consensus algorithms 类似。

The most important case for performance is when an established leader is replicating new log entries.

对 performance 最重要的场景,是 established leader 复制 new log entries 时。

Raft achieves this using the minimal number of messages (a single round-trip from the leader to half the cluster).

Raft 使用最少的 messages 实现这一点(leader 到 cluster 一半节点的一次 round-trip)。

It is also possible to further improve Raft’s performance.

还可以进一步提升 Raft 的 performance。

For example, it easily supports batching and pipelining requests for higher throughput and lower latency.

例如,它可以轻松支持 batching 和 pipelining requests,以获得更高 throughput 和更低 latency。

Various optimizations have been proposed in the literature for other algorithms; many of these could be applied to Raft, but we leave this to future work.

文献中已经为其他 algorithms 提出了各种 optimizations;其中很多也可以应用到 Raft,但我们把它留给 future work。

We used our Raft implementation to measure the performance of Raft’s leader election algorithm and answer two questions.

我们使用自己的 Raft implementation 测量 Raft leader election algorithm 的 performance,并回答两个问题。

First, does the election process converge quickly?

第一,election process 是否快速收敛?

Second, what is the minimum downtime that can be achieved after leader crashes?

第二,leader crash 后能够达到的 minimum downtime 是多少?

To measure leader election, we repeatedly crashed the leader of a cluster of five servers and timed how long it took to detect the crash and elect a new leader (see Figure 16).

为了测量 leader election,我们反复 crash 五服务器 cluster 的 leader,并计时检测 crash 和选出 new leader 所需的时间(见图 16)。

To generate a worst-case scenario, the servers in each trial had different log lengths, so some candidates were not eligible to become leader.

为了产生 worst-case scenario,每次 trial 中的 servers 具有不同 log lengths,因此一些 candidates 没有资格成为 leader。

Furthermore, to encourage split votes, our test script triggered a synchronized broadcast of heartbeat RPCs from the leader before terminating its process.

此外,为了促成 split votes,test script 在终止 leader process 前触发了一次 leader heartbeat RPCs 的 synchronized broadcast。

This approximates the behavior of the leader replicating a new log entry prior to crashing.

这近似模拟了 leader 在 crash 前复制 new log entry 的行为。

The leader was crashed uniformly randomly within its heartbeat interval, which was half of the minimum election timeout for all tests.

leader 在 heartbeat interval 内 uniform randomly crash;该 interval 是所有 tests 的 minimum election timeout 的一半。

Thus, the smallest possible downtime was about half of the minimum election timeout.

因此,最小可能 downtime 约为 minimum election timeout 的一半。

The top graph in Figure 16 shows that a small amount of randomization in the election timeout is enough to avoid split votes in elections.

图 16 的上方图表显示,election timeout 中少量 randomization 就足以避免 elections 中的 split votes。

In the absence of randomness, leader election consistently took longer than 10 seconds in our tests due to many split votes.

没有 randomness 时,由于大量 split votes,测试中的 leader election 持续超过 10 秒。

Adding just 5ms of randomness helps significantly, resulting in a median downtime of 287ms.

只增加 5ms randomness 就有显著帮助,使 median downtime 达到 287ms。

Using more randomness improves worst-case behavior: with 50ms of randomness the worst-case completion time (over 1000 trials) was 513ms.

使用更多 randomness 会改善 worst-case behavior:50ms randomness 下,worst-case completion time(1000 次 trials 中)为 513ms。

The bottom graph in Figure 16 shows that downtime can be reduced by reducing the election timeout.

图 16 的下方图表显示,减少 election timeout 可以降低 downtime。

With an election timeout of 12–24ms, it takes only 35ms on average to elect a leader (the longest trial took 152ms).

election timeout 为 12~24ms 时,选出 leader 平均只需 35ms(最长 trial 用时 152ms)。

However, lowering the timeouts beyond this point violates Raft’s timing requirement: leaders have difficulty broadcasting heartbeats before other servers start new elections.

但是,继续降低 timeouts 会违反 Raft timing requirement:leaders 难以在其他 servers 开始 new elections 前广播 heartbeats。

This can cause unnecessary leader changes and lower overall system availability.

这会导致不必要的 leader changes,并降低整体 system availability。

We recommend using a conservative election timeout such as 150–300ms; such timeouts are unlikely to cause unnecessary leader changes and will still provide good availability.

我们建议使用 150~300ms 这样的 conservative election timeout;这种 timeouts 不太可能造成不必要的 leader changes,同时仍能提供良好的 availability。

10 Related work

10 Related work。

There have been numerous publications related to consensus algorithms, many of which fall into one of the following categories:

已经有大量与 consensus algorithms 相关的 publications,其中许多属于以下类别之一:

Lamport’s original description of Paxos [15], and attempts to explain it more clearly [16, 20, 21].

Lamport 对 Paxos 的原始描述 [15],以及让它更清晰的解释尝试 [16, 20, 21]。

Elaborations of Paxos, which fill in missing details and modify the algorithm to provide a better foundation for implementation [26, 39, 13].

Paxos 的 elaborations:补充缺失细节,并修改 algorithm 以提供更好的实现基础 [26, 39, 13]。

Systems that implement consensus algorithms, such as Chubby [2, 4], ZooKeeper [11, 12], and Spanner [6].

实现 consensus algorithms 的 systems,例如 Chubby [2, 4]、ZooKeeper [11, 12] 和 Spanner [6]。

The algorithms for Chubby and Spanner have not been published in detail, though both claim to be based on Paxos.

Chubby 和 Spanner 的 algorithms 没有被详细发表,尽管两者都声称基于 Paxos。

ZooKeeper’s algorithm has been published in more detail, but it is quite different from Paxos.

ZooKeeper 的 algorithm 发布得更详细,但它与 Paxos 有很大不同。

Performance optimizations that can be applied to Paxos [18, 19, 3, 25, 1, 27].

可以应用于 Paxos 的 performance optimizations [18, 19, 3, 25, 1, 27]。

Oki and Liskov’s Viewstamped Replication (VR), an alternative approach to consensus developed around the same time as Paxos.

Oki 和 Liskov 的 Viewstamped Replication(VR):一种与 Paxos 大约同时发展起来的 alternative consensus approach。

The original description [29] was intertwined with a protocol for distributed transactions, but the core consensus protocol has been separated in a recent update [22].

原始描述 [29] 与 distributed transactions protocol 交织在一起,但最近的更新 [22] 已将 core consensus protocol 分离出来。

VR uses a leader-based approach with many similarities to Raft.

VR 使用 leader-based approach,与 Raft 有许多相似之处。

The greatest difference between Raft and Paxos is Raft’s strong leadership: Raft uses leader election as an essential part of the consensus protocol, and it concentrates as much functionality as possible in the leader.

Raft 与 Paxos 最大的差异是 Raft 的 strong leadership:Raft 将 leader election 作为 consensus protocol 的 essential part,并尽可能将 functionality 集中到 leader。

This approach results in a simpler algorithm that is easier to understand.

这种方法产生了更简单、更容易理解的 algorithm。

第 16 页:Related work、Conclusion 与 Acknowledgments

raft p16

For example, in Paxos, leader election is orthogonal to the basic consensus protocol: it serves only as a performance optimization and is not required for achieving consensus.

例如,在 Paxos 中,leader election 与 basic consensus protocol 正交:它只作为 performance optimization 存在,并不是达成 consensus 所必需的。

However, this results in additional mechanism: Paxos includes both a two-phase protocol for basic consensus and a separate mechanism for leader election.

但是,这会带来额外 mechanism:Paxos 同时包含 basic consensus 的 two-phase protocol,以及独立的 leader election mechanism。

In contrast, Raft incorporates leader election directly into the consensus algorithm and uses it as the first of the two phases of consensus.

相比之下,Raft 将 leader election 直接纳入 consensus algorithm,并将其作为 consensus 两个 phases 中的第一个。

This results in less mechanism than in Paxos.

因此,Raft 所需的 mechanism 少于 Paxos。

Like Raft, VR and ZooKeeper are leader-based and therefore share many of Raft’s advantages over Paxos.

与 Raft 一样,VR 和 ZooKeeper 都是 leader-based,因此共享 Raft 相对于 Paxos 的许多 advantages。

However, Raft has less mechanism than VR or ZooKeeper because it minimizes the functionality in non-leaders.

但是,Raft 比 VR 或 ZooKeeper 所需的 mechanism 更少,因为它将 non-leaders 中的 functionality 降到最低。

For example, log entries in Raft flow in only one direction: outward from the leader in AppendEntries RPCs.

例如,Raft 中的 log entries 只沿一个方向流动:在 AppendEntries RPCs 中从 leader 向外流出。

In VR log entries flow in both directions (leaders can receive log entries during the election process); this results in additional mechanism and complexity.

在 VR 中,log entries 双向流动(leaders 可以在 election process 中接收 log entries);这会带来额外 mechanism 和 complexity。

The published description of ZooKeeper also transfers log entries both to and from the leader, but the implementation is apparently more like Raft [35].

ZooKeeper 的公开描述同样让 log entries 双向传输,但其 implementation 显然更接近 Raft [35]。

Raft has fewer message types than any other algorithm for consensus-based log replication that we are aware of.

据我们所知,在 consensus-based log replication algorithms 中,Raft 的 message types 少于其他任何 algorithm。

For example, we counted the message types VR and ZooKeeper use for basic consensus and membership changes (excluding log compaction and client interaction, as these are nearly independent of the algorithms).

例如,我们统计了 VR 和 ZooKeeper 在 basic consensus 与 membership changes 中使用的 message types(排除 log compaction 和 client interaction,因为它们几乎独立于 algorithms)。

VR and ZooKeeper each define 10 different message types, while Raft has only 4 message types (two RPC requests and their responses).

VR 和 ZooKeeper 各自定义了 10 种不同的 message types,而 Raft 只有 4 种 message types(两个 RPC requests 及其 responses)。

Raft’s messages are a bit more dense than the other algorithms’, but they are simpler collectively.

Raft 的 messages 比其他 algorithms 的略 dense,但整体上更简单。

In addition, VR and ZooKeeper are described in terms of transmitting entire logs during leader changes; additional message types will be required to optimize these mechanisms so that they are practical.

此外,VR 和 ZooKeeper 的描述是在 leader changes 期间传输 entire logs;要优化这些 mechanisms 使其可用于实践,还需要 additional message types。

Raft’s strong leadership approach simplifies the algorithm, but it precludes some performance optimizations.

Raft 的 strong leadership approach 简化了 algorithm,但也排除了某些 performance optimizations。

For example, Egalitarian Paxos (EPaxos) can achieve higher performance under some conditions with a leaderless approach [27].

例如,Egalitarian Paxos(EPaxos)在某些条件下可以使用 leaderless approach 获得更高 performance [27]。

EPaxos exploits commutativity in state machine commands.

EPaxos 利用 state machine commands 的 commutativity。

Any server can commit a command with just one round of communication as long as other commands that are proposed concurrently commute with it.

只要并发提出的其他 commands 与该 command commute,任意 server 都可以仅通过一轮 communication 提交 command。

However, if commands that are proposed concurrently do not commute with each other, EPaxos requires an additional round of communication.

但是,如果并发提出的 commands 彼此不 commute,EPaxos 就需要额外一轮 communication。

Because any server may commit commands, EPaxos balances load well between servers and is able to achieve lower latency than Raft in WAN settings.

由于任意 server 都可以提交 commands,EPaxos 能很好地在 servers 之间平衡 load,并在 WAN settings 中实现低于 Raft 的 latency。

However, it adds significant complexity to Paxos.

但是,它给 Paxos 增加了显著 complexity。

Several different approaches for cluster membership changes have been proposed or implemented in other work, including Lamport’s original proposal [15], VR [22], and SMART [24].

其他工作提出或实现了多种 cluster membership changes approaches,包括 Lamport 的 original proposal [15]、VR [22] 和 SMART [24]。

We chose the joint consensus approach for Raft because it leverages the rest of the consensus protocol, so that very little additional mechanism is required for membership changes.

我们为 Raft 选择 joint consensus approach,是因为它利用 consensus protocol 的其余部分,因此 membership changes 只需要很少 additional mechanism。

Lamport’s α-based approach was not an option for Raft because it assumes consensus can be reached without a leader.

Lamport 的 α-based approach 不适用于 Raft,因为它假设没有 leader 也可以达成 consensus。

In comparison to VR and SMART, Raft’s reconfiguration algorithm has the advantage that membership changes can occur without limiting the processing of normal requests.

与 VR 和 SMART 相比,Raft reconfiguration algorithm 的 advantage 是 membership changes 可以发生,而无需限制 normal requests 的 processing。

In contrast, VR stops all normal processing during configuration changes, and SMART imposes an α-like limit on the number of outstanding requests.

相比之下,VR 在 configuration changes 期间停止所有 normal processing,而 SMART 对 outstanding requests 数量施加类似 α 的限制。

Raft’s approach also adds less mechanism than either VR or SMART.

Raft 的 approach 所增加的 mechanism 也少于 VR 或 SMART。

11 Conclusion

11 Conclusion

11 Conclusion。

Algorithms are often designed with correctness, efficiency, and/or conciseness as the primary goals.

Algorithms 往往将 correctness、efficiency 和/或 conciseness 作为主要目标来设计。

Although these are all worthy goals, we believe that understandability is just as important.

虽然这些都是值得追求的目标,但我们认为 understandability 同样重要。

None of the other goals can be achieved until developers render the algorithm into a practical implementation, which will inevitably deviate from and expand upon the published form.

在 developers 将 algorithm 转化为 practical implementation 之前,其他目标都无法实现;而这个过程不可避免地会偏离并扩展 published form。

Unless developers have a deep understanding of the algorithm and can create intuitions about it, it will be difficult for them to retain its desirable properties in their implementation.

除非 developers 深入理解 algorithm 并形成关于它的 intuitions,否则很难在 implementation 中保留它的 desirable properties。

In this paper we addressed the issue of distributed consensus, where a widely accepted but impenetrable algorithm, Paxos, has challenged students and developers for many years.

本文讨论了 distributed consensus 问题;一个广泛接受但难以洞察的 algorithm——Paxos——多年来一直挑战着 students 和 developers。

We developed a new algorithm, Raft, which we have shown to be more understandable than Paxos.

我们开发了 new algorithm Raft,并证明它比 Paxos 更容易理解。

We also believe that Raft provides a better foundation for system building.

我们还认为,Raft 为 system building 提供了更好的基础。

Using understandability as the primary design goal changed the way we approached the design of Raft; as the design progressed we found ourselves reusing a few techniques repeatedly, such as decomposing the problem and simplifying the state space.

将 understandability 作为 primary design goal 改变了我们设计 Raft 的方式;随着 design 推进,我们发现自己反复复用一些 techniques,例如分解问题和简化 state space。

These techniques not only improved the understandability of Raft but also made it easier to convince ourselves of its correctness.

这些 techniques 不仅提升了 Raft 的 understandability,也让我们更容易确信它的 correctness。

12 Acknowledgments

12 Acknowledgments

12 Acknowledgments。

The user study would not have been possible without the support of Ali Ghodsi, David Mazières, and the students of CS 294-91 at Berkeley and CS 240 at Stanford.

如果没有 Ali Ghodsi、David Mazières,以及 Berkeley 的 CS 294-91 和 Stanford 的 CS 240 学生的支持,user study 不可能完成。

Scott Klemmer helped us design the user study, and Nelson Ray advised us on statistical analysis.

Scott Klemmer 帮助我们设计 user study,Nelson Ray 为 statistical analysis 提供建议。

The Paxos slides for the user study borrowed heavily from a slide deck originally created by Lorenzo Alvisi.

User study 使用的 Paxos slides 大量借鉴了 Lorenzo Alvisi 最初创建的 slide deck。

Special thanks go to David Mazières and Ezra Hoch for finding subtle bugs in Raft.

特别感谢 David Mazières 和 Ezra Hoch,他们发现了 Raft 中的 subtle bugs。

Many people provided helpful feedback on the paper and user study materials.

许多人为 paper 和 user study materials 提供了有帮助的 feedback。

第 17–18 页:Acknowledgments 与 References

raft p17

raft p18

The Paxos slides for the user study borrowed heavily from a slide deck originally created by Lorenzo Alvisi. Special thanks go to David Mazières and Ezra Hoch for finding subtle bugs in Raft.

User study 使用的 Paxos slides 大量借鉴了 Lorenzo Alvisi 最初创建的 slide deck。特别感谢 David Mazières 和 Ezra Hoch,他们发现了 Raft 中的 subtle bugs。

Many people provided helpful feedback on the paper and user study materials, including Ed Bugnion, Michael Chan, Hugues Evrard, Daniel Giffin, Arjun Gopalan, Jon Howell, Vimalkumar Jeyakumar, Ankita Kejriwal, Aleksandar Kracun, Amit Levy, Joel Martin, Satoshi Matsushita, Oleg Pesok, David Ramos, Robbert van Renesse, Mendel Rosenblum, Nicolas Schiper, Deian Stefan, Andrew Stone, Ryan Stutsman, David Terei, Stephen Yang, Matei Zaharia, 24 anonymous conference reviewers, and especially our shepherd Eddie Kohler.

许多人为论文和 user study materials 提供了有帮助的 feedback,包括 Ed Bugnion、Michael Chan、Hugues Evrard、Daniel Giffin、Arjun Gopalan、Jon Howell、Vimalkumar Jeyakumar、Ankita Kejriwal、Aleksandar Kracun、Amit Levy、Joel Martin、Satoshi Matsushita、Oleg Pesok、David Ramos、Robbert van Renesse、Mendel Rosenblum、Nicolas Schiper、Deian Stefan、Andrew Stone、Ryan Stutsman、David Terei、Stephen Yang、Matei Zaharia、24 位 anonymous conference reviewers,尤其是我们的 shepherd Eddie Kohler。

Werner Vogels tweeted a link to an earlier draft, which gave Raft significant exposure.

Werner Vogels 在 Twitter 上发布了 earlier draft 的链接,这让 Raft 获得了显著曝光。

This work was supported by the Gigascale Systems Research Center and the Multiscale Systems Center, two of six research centers funded under the Focus Center Research Program, a Semiconductor Research Corporation program, by STARnet, a Semiconductor Research Corporation program sponsored by MARCO and DARPA, by the National Science Foundation under Grant No. 0963859, and by grants from Facebook, Google, Mellanox, NEC, NetApp, SAP, and Samsung.

本研究得到 Gigascale Systems Research Center 和 Multiscale Systems Center 的支持;这两个中心属于 Focus Center Research Program 资助的六个 research centers 中的两个。研究还得到 Semiconductor Research Corporation program、由 MARCO 和 DARPA 赞助的 Semiconductor Research Corporation program STARnet、National Science Foundation Grant No. 0963859,以及 Facebook、Google、Mellanox、NEC、NetApp、SAP 和 Samsung 的 grants 支持。

Diego Ongaro is supported by The Junglee Corporation Stanford Graduate Fellowship.

Diego Ongaro 得到 The Junglee Corporation Stanford Graduate Fellowship 的支持。

References

References

参考文献。

参考文献的作者、venue、年份、卷期、页码和 URL 按原 PDF 原样保留;下面补充各条目论文题目的中文释义。专有名词、项目名和出版物名不强行汉化。

编号原题目中文释义
[1]Paxos replicated state machines as the basis of a high-performance data store以 Paxos replicated state machines 作为高性能 data store 的基础
[2]The Chubby lock service for loosely-coupled distributed systems面向松耦合 distributed systems 的 Chubby lock service
[3]Multicoordinated PaxosMulticoordinated Paxos
[4]Paxos made live: an engineering perspective让 Paxos 真正运行起来:工程视角
[5]Bigtable: a distributed storage system for structured dataBigtable:面向结构化 data 的 distributed storage system
[6]Spanner: Google’s globally-distributed databaseSpanner:Google 的 globally-distributed database
[7]TLA+ proofsTLA+ proofs
[8]The Google file systemGoogle file system
[9]Leases: An efficient fault-tolerant mechanism for distributed file cache consistencyLeases:一种高效的 fault-tolerant distributed file cache consistency mechanism
[10]Linearizability: a correctness condition for concurrent objectsLinearizability:一种 concurrent objects 的 correctness condition
[11]ZooKeeper: wait-free coordination for internet-scale systemsZooKeeper:面向 internet-scale systems 的 wait-free coordination
[12]Zab: high-performance broadcast for primary-backup systemsZab:面向 primary-backup systems 的高性能 broadcast
[13]Paxos for system builders面向 system builders 的 Paxos
[14]Time, clocks, and the ordering of events in a distributed system分布式系统中的 time、clocks 与 events ordering
[15]The part-time parliamentThe part-time parliament
[16]Paxos made simplePaxos made simple
[17]Specifying Systems, The TLA+ Language and Tools for Hardware and Software EngineersSpecifying Systems:面向 hardware 和 software engineers 的 TLA+ language 与 tools
[18]Generalized consensus and PaxosGeneralized consensus and Paxos
[19]Fast PaxosFast Paxos
[20]How to build a highly available system using consensus如何使用 consensus 构建 highly available system
[21]The ABCD’s of PaxosThe ABCD’s of Paxos
[22]Viewstamped replication revisitedViewstamped replication revisited
[23]LogCabin source codeLogCabin source code
[24]The SMART way to migrate replicated stateful services迁移 replicated stateful services 的 SMART way
[25]Mencius: building efficient replicated state machines for WANsMencius:为 WANs 构建高效 replicated state machines
[26]Paxos made practicalPaxos made practical
[27]There is more consensus in egalitarian parliamentsEgalitarian parliaments 中存在更多 consensus
[28]Raft user studyRaft user study
[29]Viewstamped replication: A new primary copy method to support highly-available distributed systemsViewstamped replication:支持 highly-available distributed systems 的 new primary copy method
[30]The log-structured merge-tree (LSM-tree)log-structured merge-tree(LSM-tree)
[31]Consensus: Bridging Theory and PracticeConsensus:连接 Theory and Practice
[32]In search of an understandable consensus algorithm寻找一种易于理解的 consensus algorithm
[33]The case for RAMCloudRAMCloud 的论证
[34]Raft consensus algorithm websiteRaft consensus algorithm website
[35]Personal communications, May 17, 2013Personal communications,2013 年 5 月 17 日
[36]The design and implementation of a log-structured file systemlog-structured file system 的设计与实现
[37]Implementing fault-tolerant services using the state machine approach: a tutorial使用 state machine approach 实现 fault-tolerant services:教程
[38]The Hadoop distributed file systemHadoop distributed file system
[39]Paxos made moderately complexPaxos made moderately complex

论文机制索引

下面把论文的 Section 2–12 与课程 Lecture、Lab 和实现代码建立交叉索引。

论文部分课程/实现对应物
Section 2 Replicated state machines分布式共识与复制状态机、Lab 4
Section 5 The Raft consensus algorithm6.5840:Lecture 06 RSM and Raft 1、6.5840:Lecture 07 Raft 2
Section 6 Cluster membership changesLab 3D、Lab 5 的 configuration change
Section 7 Log compactionLab 3D 快照与日志压缩
Section 8 Client interactionLab 4 的 KV service
Section 9 Evaluation论文实验与课程实现边界
Section 10 Related workPaxos、VR、ZooKeeper、EPaxos 与 joint consensus 对比
Section 11–12 Conclusion / Acknowledgments可理解性作为设计目标,以及论文背景

本篇验收

  • [x] 已固定官方 Raft Extended Version PDF:18 页、612×792 points、SHA-256 已记录。
  • [x] 已渲染 18 张 1224×1584 PNG,并目视检查第 1 页;每页按 600 宽度引用。
  • [x] 第 1–18 页正文已按 PDF 双栏中的标题、段落、列表和图注逐段翻译;PDF 页面图作为原始格式与图件副本保留。
  • [x] Section 1–12、Figure 1–16、RPC/state/rules、公式 broadcastTime ≪ electionTimeout ≪ MTBF、joint consensus、snapshot、InstallSnapshot、client interaction、evaluation、related work、Conclusion 和 References 均已覆盖。
  • [x] 参考文献的作者、venue、年份、页码、URL 和原始书目信息保留;39 个题目均补充中文释义。
  • [x] 本篇 checker、lint、18 个 PNG 附件和页面引用宽度检查通过;PDF 文本的双栏换行不作为额外语义断句。

参考资料

← 返回列表
← 上一篇 MIT 6.5840:Lecture 22 Project demos 下一篇 → 论文:The Google File System(GFS)

评论 (0)

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