Chapter 29: Consistency and Consensus (Raft, Paxos)

In distributed systems, how do multiple nodes agree on the state of data? This is the consensus problem.

Consistency Models

ModelGuaranteeExample
Strong (Linearizable)All reads see the latest writeSingle-node PostgreSQL
SequentialAll nodes see operations in same orderZooKeeper
CausalCausally related operations are orderedSome distributed DBs
EventualAll nodes converge eventuallyDNS, Cassandra (default)

Raft Consensus Algorithm

Used by etcd, CockroachDB, TiDB. Elects a leader; leader replicates log entries to followers.

Raft cluster (3 nodes): ┌────────┐ ┌──────────┐ ┌──────────┐ │ Leader │────►│ Follower │ │ Follower │ │ │────►│ │ │ │ └────────┘ └──────────┘ └──────────┘ 1. Client sends write to Leader 2. Leader appends to its log 3. Leader replicates to followers 4. Once majority (2/3) acknowledge → committed 5. Leader responds to client If leader dies → followers elect new leader (election timeout)

Two-Phase Commit (2PC)

For transactions spanning multiple nodes:

// Phase 1: PREPARE
Coordinator → all participants: "Can you commit?"
All participants: lock resources, write to WAL, respond YES/NO

// Phase 2: COMMIT (if all said YES)
Coordinator → all participants: "COMMIT"
All participants: make changes permanent, release locks

// Problem: if coordinator crashes between phases, participants are stuck
💡 Practical Impact

You rarely implement consensus yourself. You use databases that implement it internally (CockroachDB, YugabyteDB, TiDB) or coordination services (etcd, ZooKeeper). Understanding the concepts helps you reason about consistency guarantees and failure modes.

Key Takeaways