Raft Algorithm Golang Implementation
中文版.
Before implementing the algorithm, please read https://raft.github.io/raft.pdf several times
to ensure that you understand the function and role of each part in Figure 2
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9ZqSLwG9-1673342031456)(null)]
This project assumes that there are 5 Servers for the sake of simplicity
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lTbXAjNg-1673342031412)(null)]
-
Server:
There are only three states of nodes in effect in Raft, i.e. Leader, Candiate, Follower.Please focus on the exact state of each Server at the time of voting, only Candiate has the right to vote. Note that each individual election takes place independently, so you can assume that there are multiple elections taking place at the same time. Note that the time interval between heartbeats is variable, so the election process does not start at the same time for each Server. Follower: Copies the Leader's Log and executes the actions in the already committed Log against its own kvstore. Candiate: Gets votes and can also vote, and sends a heartbeat as soon as it becomes a Leader. Leader: Sends heartbeats periodically to prevent elections from happening Copy logs to all Follower, first to execute the actions in the committed logs to its own kvstore.
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mjoPR6qR-1673342031062)(null)]
2. RequestVote RPC
There can only be one Leader at a time, and according to the selection mechanism, we can assume that the Leader is elected by Candiate.
It is clear that the RPC is parallel, so when counting votes and state changes, it is important to note whether the vote count is duplicated and whether the state change is duplicated. This should be judged.
It is also important to note that when the number of votes reaches half of the currently active servers, the Candiate will immediately become the Leader, and when a Candiate becomes the Leader, it will immediately end its own election cycle and send a notification to all remaining Candiates to make its state Follower and end the election cycle.
During the RequestVote, the Candiate will send a poll request to each candidate, noting