CodeBlanks Logo Icon CodeBlanks

Consensus

Learn Raft and Paxos consensus algorithms.

What is consensus?

Consensus is the process by which distributed nodes agree on a single value. Raft and Paxos are two common algorithms. Raft prioritizes understandability; Paxos prioritizes mathematical conciseness.

A node in Raft takes one of three roles: follower (passive), candidate (contesting an election) and leader (running writes). A consensusRole(term) function models these: term === 0 returns 'follower', term === 1 returns 'candidate', others return 'leader'. This maps Raft's term logic with a simple lookup; real Raft runs elections by majority vote but the roles stay the same.

Term logic

In Raft a term is a logical clock. Each election starts a new term. A node's role depends on the term it sits in. This drives monotonic progress and prevents stale leaders from returning.

Example: consensusRole(0) returns 'follower'; a fresh node is passive. consensusRole(1) returns 'candidate'; in term 1 it contests an election. consensusRole(2) returns 'leader'; it won a majority vote and leads. This model puts Raft's term-role link into one function. Paxos has a similar mechanism (proposal number); both algorithms rest on majority and monotonic terms.

Practice Write the consensus role function

Write function consensusRole(term). Add if (term === 0) return 'follower';, if (term === 1) return 'candidate'; and return 'leader';. Print console.log(consensusRole(0)) and console.log(consensusRole(2)).

Starter code

index.js
// Write the consensusRole function
// term 0 gives 'follower', 1 gives 'candidate', others give 'leader'
// Print calls with 0 and 2
// write here

Sample solution

index.js
function consensusRole(term) {
  if (term === 0) return 'follower';
  if (term === 1) return 'candidate';
  return 'leader';
}
console.log(consensusRole(0));
console.log(consensusRole(2));

Expected output

follower
leader

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the leader branch

Question
if (term === 0) return 'follower';
if (term === 1) return 'candidate';
return '____';
Answer
if (term === 0) return 'follower';
if (term === 1) return 'candidate';
return 'leader';

Explanation: Other terms return 'leader'.

2 Match each concept to its role

Term Meaning
Raft Understandable algorithm
Paxos Mathematical algorithm
follower Passive node
leader Drives writes

3 What happens when a node wins an election in Raft?

index.js
consensusRole(2)
  • Follower olur
  • Candidate olur
  • Leader olur Correct answer
  • Client olur

Explanation: The winner becomes the leader.

All lessons in Expert