Node.js
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.
Exercise 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)).
Show example solution
function consensusRole(term) {
if (term === 0) return 'follower';
if (term === 1) return 'candidate';
return 'leader';
}
console.log(consensusRole(0));
console.log(consensusRole(2));
Test yourself
-
Complete the leader branch
if (term === 0) return 'follower';
if (term === 1) return 'candidate';
return '____';
Show answer
if (term === 0) return 'follower';
if (term === 1) return 'candidate';
return 'leader';
-
Match each concept to its role
- Raft
- Understandable algorithm
- Paxos
- Mathematical algorithm
- follower
- Passive node
- leader
- Drives writes
-
What happens when a node wins an election in Raft?
consensusRole(2)
- Follower olur
- Candidate olur
- Leader olur
- Client olur
Show answer
Leader olur — The winner becomes the leader.
Next lesson: Distributed tracing