# `Raft` Leader Election

![`smart`](RaftLeaderElect01_aa_002_20220511.png)

------------------------------------------------------------------------------
We first introduce a concept called term, which is a small segment of time that the Raft consensus algorithm divides time into. It can also be understood that in the eyes of the Raft consensus algorithm, time is divided into one term after another, and the size of each term may be different. We use consecutive increasing numbers to identify these terms.

The term is stored in each node, and in the initial stage of the term, it must be the election stage. After the leader is born, the whole Raft cluster provides normal services for the rest of the time of this term. If no exception occurs, this term will continue. If an exception occurs (such as leader crash or network problem), then the current term will end, and the new node will increment the previous term identifier, and then start a new round of election.

Raft must ensure that, within a term, there is at most one leader in the cluster.

At the beginning of the cluster, all nodes are followers. When a follower does not receive a valid message from a leader or candidate within a specified time, an election will be initiated. This specified time is called an election timeout. The election timeout is a random value (e.g. the default is 10 seconds).

The effective messages of leader are heartbeat messages, and the effective messages of candidate are voting messages. Here two state variables are introduced, election timeout and heartbeat time interval, heartbeat time interval is less than min(election timeout), to avoid followers initiating unnecessary voting.

Assuming that node 2 breaks the election timeout first, it will increment its term identifier, become a candidate role, and vote for itself. At the same time, it will send a voting request to other machines in the cluster, which contains its newly incremented term identifier. Other followers who receive the voting request with a term identifier greater than or equal to the current term identifier will agree and update their own term identifier, and send an agreement message to the node with the candidate role.

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

Here, the first election is finished.

