Consensus Algorithms

In a distributed system, how do multiple nodes agree on a single value?

This is called Consensus.

It is one of the hardest problems in computer science.


Why Consensus is Hard

Nodes can fail. Networks can be slow. Messages can be lost.

If three servers need to decide whether User A has $10 left:

How do they reach an agreement?


The Two Big Algorithms

1. Paxos

2. Raft


How Raft Works (Simplified)

Raft works by following three steps:

Phase 1: Leader Election

Phase 2: Log Replication

Phase 3: Commitment

sequenceDiagram
    participant User
    participant Leader
    participant F1 as Follower 1
    participant F2 as Follower 2

    User->>Leader: Write "X=10"
    Leader->>F1: Replicate "X=10"
    Leader->>F2: Replicate "X=10"
    F1-->>Leader: ACK
    Note over Leader: Majority Reached!
    Leader->>Leader: Commit "X=10"
    Leader-->>User: Success
    Leader->>F2: Commit "X=10"

What Happens During Failure?

If the Leader crashes:

  1. Followers wait for a timeout.
  2. They realize the leader is gone.
  3. They start a new election.

If a Follower crashes:

  1. The leader keeps sending heartbeats.
  2. When the follower wakes up, it catches up on the missing logs from the leader.

Key Takeaways

Consensus is the foundation of Strong Consistency. Without it, you cannot build databases that guarantee data accuracy at scale.