Hello! Welcome to your next lesson in the "Distributed Systems Building Blocks" module.
In our last session, we designed a distributed rate limiter. We used a replicated Redis cluster with a leader-follower setup to ensure high availability. However, we only briefly touched on what happens when a leader node fails. A simple manual failover isn't robust enough for a production system, and an improperly designed automatic failover can lead to a catastrophic "split-brain" scenario, where multiple nodes believe they are the leader, causing data corruption.
This leads us directly to the core problem we'll tackle today: How does a group of distributed computers reliably agree on a shared state, especially in the face of failures?
This lesson addresses the learning outcome: Explain the purpose of consensus protocols (e.g., Raft, Paxos) in maintaining state. We will explore why consensus is a fundamental problem in distributed systems and how protocols like Raft and Paxos provide the mechanism for building reliable, consistent services.
1. The Problem: Why We Need Consensus
At its heart, consensus is about making a group of computers act as a unified whole. This is essential for implementing State Machine Replication, a core technique for building fault-tolerant services. The idea is simple: if you have a service (the state machine) and you replicate it across multiple servers, you can tolerate the failure of some of those servers. However, for this to work, every replica must process the exact same operations in the exact same order. This guarantee is called total order broadcast.

Achieving total order broadcast is difficult. A common approach is to designate a leader that decides the order of operations. But what happens if that leader fails?
Distributed Systems 6.1: Consensus
To understand the problem more formally, let's watch the first few minutes of a lecture by Martin Kleppmann, a leading researcher in distributed systems. He clearly explains why simple leader-based replication fails and how this leads to the need for consensus.
Watch the video from the beginning to 05:42. Focus on: The limitations of manual failover for unexpected leader crashes. The formal definition of the consensus problem: multiple nodes proposing values and needing to agree on one. The equivalence between consensus (agreeing on one value) and total order broadcast (agreeing on a sequence of values).
As the video explains, the core purpose of consensus protocols is to automate the process of leader election and failover, ensuring that the system can continue to make progress safely even when nodes crash.
Safety vs. Liveness: The Fundamental Trade-off
Before diving into specific algorithms, it's critical to understand the properties they must guarantee. A correct consensus algorithm must provide three guarantees, which fall into two categories: Safety and Liveness. This is a crucial distinction for any Staff-level discussion.
This article from AlgoMaster.io provides an excellent breakdown of these properties.
Read the sections 'Properties of Consensus' and 'Safety vs Liveness'. Pay close attention to the definitions of: Agreement (Safety): All nodes decide on the same value. Validity (Safety): The decided value was actually proposed by a node. Termination (Liveness): All non-faulty nodes eventually decide on a value. \nCritically, understand why real-world systems must prioritize safety over liveness.
To summarize:
- Safety (nothing bad ever happens): The system never enters an invalid state. Nodes will never disagree on the committed value.
- Liveness (something good eventually happens): The system eventually makes progress.
A famous result in distributed systems, the FLP Impossibility Proof, shows that in a fully asynchronous system (where messages can be delayed indefinitely), it's impossible to guarantee both safety and liveness. Therefore, practical consensus algorithms like Paxos and Raft guarantee safety always and provide liveness under certain assumptions (e.g., that network delays are not infinite and a leader can eventually be elected). This is why a system might temporarily become unavailable (a liveness failure) but will never corrupt its data (a safety failure).
2. Raft: Consensus Designed for Understandability
The easiest way to understand the mechanics of consensus is to study Raft. While Paxos came first, Raft was designed explicitly to be more understandable without sacrificing correctness. It provides the same guarantees as Multi-Paxos but is structured in a way that is easier to reason about.
Raft decomposes consensus into three distinct parts:
- Leader Election: Electing a single new leader when an old one fails.
- Log Replication: The leader accepts commands from clients and replicates them across the other nodes (followers), ensuring their logs are identical.
- Safety: Ensuring that if any server has applied a log entry to its state machine, no other server can apply a different command for the same log index.
Core Concepts in Raft
- Node States: A node is always in one of three states: Follower, Candidate, or Leader. All nodes start as followers.
- Terms: Raft divides time into
termsof arbitrary length. Each term is numbered with a consecutive integer. A term begins with an election, and if successful, a single leader manages the cluster for the rest of the term. This term number acts as a logical clock, allowing nodes to detect stale information. - Quorum: Decisions, such as electing a leader or committing a log entry, require a majority vote from the cluster (e.g., 3 out of 5 nodes). This allows the system to tolerate
ffailures with2f + 1nodes.
Heidi Howard — Paxos vs Raft: Have we reached consensus on distributed consensus?
The following video by Heidi Howard provides an excellent, high-level walk-through of how these concepts fit together in both Raft and Paxos.
Watch the sections on the high-level approach (20:07 - 24:15) and leader failures (26:22 - 31:37). Don't worry about the Paxos-specific details for now. Focus on: The role of the leader in receiving client requests and replicating them to followers via an append entries message. How an entry is committed only after being replicated to a majority. The concept of terms as a logical clock to distinguish between different leadership periods. The state transitions: Follower -> Candidate -> Leader.
The process you just watched is the essence of how consensus protocols maintain state. The leader establishes an official history of operations (the log), and the consensus protocol ensures this log is durably replicated and correctly restored even if the leader fails.
3. Paxos: The Foundational Protocol
No discussion of consensus is complete without mentioning Paxos. Developed by Leslie Lamport, Paxos is the original, foundational consensus protocol. It is more of a protocol family than a single algorithm, offering more flexibility but also being notoriously difficult to understand and implement correctly.
While Raft uses friendly terms like Leader, Follower, and Candidate, Paxos defines more abstract roles:
- Proposer: Suggests a value.
- Acceptor: Votes on proposed values.
- Learner: Learns the final, decided-upon value.
In practice, a single node plays all three roles, much like a Raft node. The key insight is that the underlying mechanisms are very similar.
This article from Neon's engineering blog does a great job of creating a 'Rosetta Stone' between Paxos and Raft.
Read the sections 'Paxos' and 'Raft'. Notice how Raft's concepts map to Paxos: Raft's leader election is equivalent to Paxos Phase 1 (Prepare/Promise). Raft's log replication is a continuous execution of Paxos Phase 2 (Accept/Accepted). Raft's Leader is the distinguished Proposer, and Followers are Acceptors/Learners.
The main takeaway is that Raft didn't invent a new way to achieve consensus; it provided a much clearer, more prescriptive structure for the principles that Paxos established.
4. Raft vs. Paxos: A Staff-Level Discussion
In an interview for a Staff+ role, you're expected to go beyond definitions and discuss trade-offs. The choice between Raft and Paxos is a classic example.
The fundamental difference lies in their approach to leader election and log safety.
Heidi Howard — Paxos vs Raft: Have we reached consensus on distributed consensus?
Let's return to Heidi Howard's talk, where she masterfully dissects the exact differences in their leader election mechanisms. This is the most critical part of the comparison.
Watch the detailed comparison from 31:37 to 44:02. This is dense but crucial. Focus on the two different philosophies: Paxos: Any node can try to become a leader. If it has a stale log, the election protocol itself forces it to learn about more recent entries from other nodes before it can act as leader. The work happens during the election. Raft: Only a node whose log is already up-to-date can become a leader. This simplifies the protocol by restricting who can win an election in the first place. The work is done before the election.
This leads to the primary trade-off: Flexibility vs. Understandability.
- Paxos is more flexible. For instance, as the Neon article (LINK) you read earlier explains, its separation of roles allows for architectures where some nodes (proposers) don't have persistent storage, while Raft's original paper assumes all nodes are uniform. This flexibility, however, makes it much harder to implement and verify.
- Raft is less flexible but vastly more understandable and easier to implement correctly. It makes stronger assumptions (e.g., about who can be a leader) to simplify the overall protocol.
For most new systems built today, Raft (or a system using a Raft library) is the pragmatic choice unless a specific architectural constraint, like the one at Neon, makes a Paxos-variant more suitable.
5. Consensus in the Real World
You are not expected to implement consensus from scratch in an interview. The goal is to demonstrate that you understand the problem it solves and know when to use it.
To ground this in reality, let's look at which real-world systems use these protocols. This is excellent practical knowledge for a system design discussion.
Quickly review the tables in this section. Note the patterns: Raft: Dominates modern open-source systems like etcd (Kubernetes), Consul, and distributed databases like CockroachDB and TiDB. Paxos: Powers legendary, high-scale internal Google systems like Chubby and Spanner. ZAB (a Paxos-like protocol): The engine behind Apache ZooKeeper, used extensively in the Hadoop and Kafka ecosystems.
The best interview answer to "How would you ensure consistency?" is often: "For this component, we need a strongly consistent replicated state machine. I would use a battle-tested coordination service like etcd or ZooKeeper, which internally uses a consensus protocol like Raft or ZAB to manage leader election and state replication safely." This demonstrates both theoretical knowledge and practical judgment.
Conclusion
This lesson explained the fundamental purpose of consensus protocols in distributed systems. They are the engine that allows a group of fallible computers to maintain a consistent, shared state.
Key Takeaways:
- Purpose: Consensus protocols solve the problem of state machine replication by enabling total order broadcast. They provide a mechanism for a distributed system to agree on an ordered sequence of operations, even in the face of node failures.
- Core Function: Their most critical function is to manage automated leader election safely, preventing "split-brain" scenarios and ensuring that a system remains available (liveness) without sacrificing correctness (safety).
- Key Mechanisms: They rely on concepts like terms/epochs as logical clocks, and requiring a quorum (majority) to make decisions about leadership and state changes.
- Raft vs. Paxos: They are two different approaches to solving the same problem. Raft prioritizes understandability and provides a complete, prescriptive algorithm. Paxos is a more general and flexible protocol family but is notoriously difficult to implement correctly. The key difference lies in how they ensure a new leader has an up-to-date log.
- Practical Application: In a real-world system, you almost always use an existing, proven implementation (e.g., etcd, ZooKeeper) rather than building consensus from scratch.
Preview of the Next Lesson:
We've now seen how to agree on the order of operations to maintain a consistent state. But what about agreeing on where data lives in the first place, especially in a large cluster where nodes are constantly being added or removed? In our next lesson, we will explore a different but related problem and its solution: Explain and apply consistent hashing for data partitioning and load balancing.