Raft Consensus
When to Use Raft Consensus
In Practice
Sketch
Python
# Raft commit (leader side, simplified)
def append_entries(entry):
log.append(entry)
acks = 1 # self
for f in followers:
if f.replicate(entry, prev_index, prev_term):
acks += 1
if acks > len(cluster) // 2:
commit_index = entry.index
apply_to_state_machine(entry)
return OK
return RETRYHow Raft Consensus Comes Up in Interviews
Scenario
An etcd leader receives a write. Before responding success, what must happen?
Raft requires the leader to append the entry locally and replicate to a majority of the cluster (including itself). Only after majority ack does it commit and apply to the state machine, then reply.
This is why etcd needs an odd cluster size: 3 nodes tolerate 1 failure, 5 tolerate 2. Even sizes give worse availability for the same write cost.
Scenario
You need a strongly-consistent registry of cluster config that ~10 services read on startup. The cluster is 5 nodes.
For a small, strongly-consistent metadata store, Raft (etcd, Consul KV) is the standard answer. Gossip is for soft, eventually-consistent state at scale, not for config-of-record.
Gossip + Raft often coexist: Consul uses Raft for the KV store and SWIM gossip for liveness of thousands of agents.