# Raft Leader Election


![left](./student-guide/diagram/03-Raft-Leader-01-01.png)

------------------------------------------------------------
Below, we describe the Leader elect:

At the beginning, let's first introduce a concept called term, the so-called term is a small segment of time divided by the Raft consensus algorithm (it can also be understood that in the eyes of the Raft consensus algorithm, time is divided into one term and one term), the size of each term may be different, we use continuously increasing numbers to identify these Term, which is saved in each node, must be the elect phase in the initial phase of the term. After the leader is born, the entire raft cluster will provide normal services for the remainder of the term. If no exception occurs, the term will continue (the term's identity will not change), and if an exception occurs ( (e.g. leader down or network issues), then the current term will end, the new node will increment the previous term ID, and then a new round of elect will be held. Here we also need to note that Raft guarantees that within a term, there is only one leader in the cluster.

So when will the elect be launched?

At the beginning of the cluster, all nodes are followers, and an elect is initiated when the follower does not receive a valid message from the leader or candidate within the specified period of time. This specified time is called the election timeout and is a random value (for example, 150 ms - 300 ms). What is a valid message? A valid message for a leader is a heartbeat message, and a valid message for a candidate is a voting message. Two state variables are introduced here, election timeout and heartbeat time interval (the time between heartbeats sent by the leader), which require the heartbeat time interval to be less than min (election timeout) to avoid The follower re-initiates an unwarranted vote.

Suppose that node 2 in the figure breaks the election timeout first. At this time, it will first increment its term identifier, change itself to the role of candidate, and vote for itself. At the same time, make a voting request to other machines in the cluster, including the term ID you just incremented. Voting request received by other followers that contain a term greater than or equal to the current term will agree, and update their term ID to send consent information to the candidate role node.

At this point, the TiKV node with the candidate role receives that more than half of the TiKV nodes in the cluster agree to be the leader, the status changes to leader, and immediately sends a heartbeat message to all nodes, and then sends a heartbeat message according to the heartbeat interval.

At this point, the initial elect has been completed.


