# Raft Leader Elect
__*Leader Election*__
__*term*__
__*Valid message*__

![left](./student-guide/diagram/RaftLeaderElect01_aa_001_20220511.png)

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

At the beginning, let's first introduce a concept called term, which 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 after another term). The size of each term may be different. We use consecutive incrementing numbers to identify these Term, which is stored in each node, must be the elect stage at the initial stage of the term. When the leader is born, the entire raft cluster provides normal services to the outside world for the remainder of the term. If no exception occurs, the term will continue (the term's logo will not change), and if an exception occurs ( (such as leader down or network problems), then the current term will end, and the new node will increment the previous term identity, and then a new round of elect. We also need to note here that Raft is to ensure that only one leader is in the cluster within a term.

So when will elect be launched?

At the beginning of the cluster, all nodes are followers. If the follower does not receive a valid message from the leader or candidate within the specified time, an elect will be initiated. This specified time is called election timeout and is a random value (for example, 10s by default). What is a valid message? A valid message for 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 (leader sends heartbeat interval), which require the heartbeat time interval to be less than min (election timeout) to avoid Followers relaunch senseless voting.

Assuming that node 2 in the figure first breaks the election timeout, it will first increment its term identity, change itself to the candidate role, and vote for itself. At the same time, a voting request is made to other machines in the cluster, and the request contains the term ID that you just incremented. Other followers receive voting request that contain a term greater than or equal to the current term ID and will update their own term identity and send consent information to the candidate role's node.

At this time, the TiKV node with the candidate role receives more than half of the TiKV nodes in the cluster and agrees to be leader, and the status changes to leader, and immediately sends heartbeat messages to all nodes, and then sends heartbeat messages according to the heartbeat interval.

At this point, the first elect has been completed.

