Consensus and Raft: Elections, Log Replication, Read Consistency, and Leader Election with etcd
System Design series · Part 4 Distributed data (6 of 7)
- Replication and Replication Lag: Why Users Cannot Read What They Just Wrote After Read/Write Splitting
- Sharding: Choosing a Shard Key, Moving Data When You Reshard, and What You Lose Across Shards
- Consistent Hashing: Moving Only 1/N When Nodes Change, Virtual Nodes, Rendezvous Hashing, and Deliberately Chosen Keys
- Distributed IDs: UUIDv7, Snowflake, and Segment Allocation, Compared on Order, Size, and What They Leak
- CAP and PACELC: Consistency or Availability During a Partition, Latency or Consistency Otherwise
- Consensus and Raft: Elections, Log Replication, Read Consistency, and Leader Election with etcd
- Distributed Locks and Fencing Tokens: The Lock Expires, and the Holder Does Not Know
System Design series Part 4-6 | Previous: CAP and PACELC | Next: Distributed Locks and Fencing Tokens | Series map
Read first: Part 4-2 Sharding, Part 4-5 CAP and PACELC.
Scenario and problem
The talk platform has three problems that look unrelated:
- Only one copy of the scheduled job may run: the job that sends “talk starting soon” reminders every minute is deployed on 3 instances. If all three run it, every reminder goes out three times
- Primary database failover: the MySQL primary goes down, and one of the replicas has to be promoted to the new primary. Who decides? If the network partitions and each side elects its own primary, you get split brain
- Configuration must agree: once the “pause sign-ups” switch changes, every instance has to see the same value. No instance may still be accepting sign-ups
- Only one copy of the job may runThe job that sends "talk starting soon" reminders every minute is deployed on 3 instances. If all three run it, the same attendee gets three reminders.
- The primary database goes downThe MySQL primary has gone down, and one of the replicas has to be promoted to the new primary. Who decides?
- A partition, two primariesIf the network happens to partition, each side elects its own primary and both accept writes, so the data diverges. This is called split brain.
- Configuration must agreeOnce the "pause sign-ups" switch changes, every instance has to see the same value. No instance may still be accepting sign-ups.
- The same problemAt heart the three problems are the same: a group of machines agreeing on one value while some of them crash and the network delays or drops messages.
At heart the three problems are the same: a group of machines agreeing on one value while some of them may crash and the network may delay or drop messages. This is consensus.
The simplest approach and its limits
- Designate one coordinator: a single Redis, or one row in a database, decides who the leader is. When the coordinator goes down, nobody can be elected. If the coordinator is backed up with asynchronous replication, a failover can lose the record of who the leader is, and you have two leaders again
- Send each other heartbeats, and take over when the other side goes quiet: in a network partition neither side can reach the other, so both take over. That is exactly split brain
- Two-phase commit (2PC): it solves “all participants commit together or abort together”, not consensus. If the coordinator crashes before the second phase, the participants can only keep waiting
The flaw these approaches share: nothing guarantees that only one side can make a decision at any one time. Consensus algorithms provide that guarantee with majority votes.
Core mechanism
Majorities: why 2f + 1
Any two majorities overlap in at least one machine. As long as every decision needs a majority to agree, two conflicting decisions can never both stand: the machine in the overlap will not agree twice.
| Nodes | Majority | Failures tolerated |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 6 | 4 | 2 |
| 7 | 4 | 3 |
To tolerate f failures you need 2f + 1 machines. An even number gains you nothing: 4 machines and 3 machines both tolerate only 1 failure, but with 4 there is one more machine to wait for and one more that can fail. In practice, use 3 or 5.
Note that a “failure” here means crashing or becoming unreachable. It does not cover a node that lies. Raft and Paxos both assume that nodes never maliciously send wrong messages (see Security).
Replicated state machine
What Raft solves is giving every machine an identical log of commands. Every machine starts from the same initial state and executes the same commands in the same order, so they all end up in the same state. What the machines reach consensus on is “what is entry N of the log”.
Raft splits the problem into three parts: electing a leader, replicating the log from the leader, and guaranteeing safety.
Roles and terms
stateDiagram-v2
[*] --> Follower
Follower --> Candidate: no leader heartbeat within the election timeout
Candidate --> Candidate: split vote, new term after the timeout
Candidate --> Leader: wins a majority of votes
Candidate --> Follower: finds an existing leader or a newer term
Leader --> Follower: finds a newer term
- A term is an integer that only ever increases, and each term has at most one leader. Terms are Raft’s logical clock: any node that receives a message with a larger term updates its own term, and if it is a leader or a candidate, it immediately falls back to follower
- The leader handles all writes and sends heartbeats periodically
- Followers passively receive the leader’s log entries and heartbeats
Leader election
- If a follower receives no heartbeat within the election timeout, it increments its term by 1, becomes a candidate, votes for itself, and sends RequestVote to the other nodes
- Each node casts only one vote per term, first come first served, and only for a candidate whose log is at least as up to date as its own: compare the term of the last entry first, and if the terms are equal, compare the length. This restriction is the key to safety, explained below
- A candidate that gets a majority of votes becomes the leader and immediately sends heartbeats, which make the other candidates fall back to follower
- If nobody gets a majority (a split vote), the nodes wait for the timeout and start a new term to vote again
Each node’s election timeout is picked at random within a range. If the timeout were fixed, then after the leader crashed all followers would time out at almost the same moment, all run at once, and split the vote; in the next round they would time out together again, and the cluster might never elect anyone. With randomization, usually only one node times out first, and it collects its votes before the others time out.
The timeout has to satisfy broadcast time ≪ election timeout ≪ mean time between failures. Too short, and a slight network delay is mistaken for a leader crash, so the leader changes often. Too long, and when the leader really does crash it takes a long time to replace it, with no writes possible in the meantime. etcd defaults to a 100 ms heartbeat and a 1,000 ms election timeout. The official recommendation is a heartbeat of 0.5 to 1.5 times the RTT between members, an election timeout of at least 10 times the RTT, and the same settings on every member.
Log replication
sequenceDiagram
participant C as Client
participant L as Leader
participant F1 as Follower 1
participant F2 as Follower 2
C->>L: write "pause sign-ups"
L->>L: append as log entry 7 and write it to disk
par
L->>F1: AppendEntries (previous entry is entry 6, term 3)
and
L->>F2: AppendEntries (previous entry is entry 6, term 3)
end
F1->>F1: check that entry 6 matches, write to disk
F1-->>L: success
Note over L: self + F1 = 2 of 3 machines, entry 7 is committed
L->>L: apply to the state machine
L-->>C: success
F2-->>L: success (arriving late is fine)
- Every log entry records its term, its position, and the command
- When the leader sends new entries, it attaches the position and term of the entry before them. If the follower’s previous entry does not match, the follower rejects them; the leader steps back one entry and tries again until it finds a position where both logs agree, then overwrites the rest of the follower’s log with its own. So whenever two logs have the same term at some position, everything before that position is identical
- Once an entry is stored on the disks of a majority of nodes, it is committed, and only then does the leader apply it to the state machine and reply to the client. Followers learn the commit position from later messages and each apply the entry themselves
Every write has to wait at least for the leader to write to disk, the entry to reach the followers, the followers to write to disk, and the replies. That is why consensus systems are very sensitive to disk write latency.
Safety: why committed data is never overwritten
The election restriction guarantees that a new leader always has every committed entry: a committed entry is on a majority of nodes, winning an election takes a majority of votes, and any two majorities overlap in at least one node. That node has the entry, and it only votes for a candidate whose log is at least as up to date as its own.
But there is one unintuitive detail: a leader cannot treat an entry from an earlier term as committed just because it has been replicated to a majority of nodes. Take 5 machines, S1 to S5. The table shows the content and term of entry 2 in each machine’s log:
| Step | What happens | S1 | S2 | S3 | S4 | S5 |
|---|---|---|---|---|---|---|
| 1 | Term 2: S1 is the leader, writes X, sends it only to S2, and crashes | X(2) | X(2) | |||
| 2 | Term 3: S5 wins with votes from S3, S4, and S5, writes Y locally, and crashes before sending it | X(2) | X(2) | Y(3) | ||
| 3 | Term 4: S1 restarts, wins with votes from S1, S2, and S3, and sends the missing X to S3 | X(2) | X(2) | X(2) | Y(3) |
After step 3, X is on 3 machines, a majority. If S1 now treated X as committed, replied to the client, and then crashed:
| Step | What happens | S1 | S2 | S3 | S4 | S5 |
|---|---|---|---|---|---|---|
| 4 | Term 5: S5 restarts. The term of its last entry is 3, newer than S2 and S3 (2) and S4 (1), so it wins a majority and overwrites entry 2 on the other nodes with Y | Y(3) | Y(3) | Y(3) | Y(3) | Y(3) |
X, which the client had already been told succeeded, is gone. Raft’s rule is: a leader commits by “replicated to a majority of nodes” only entries from its own term. In term 4, S1 first has to write an entry from term 4 (for example, a no-op command). Once that entry is replicated to a majority of nodes, it and the X before it are committed together. After that, the last entry on a majority of nodes is from term 4, and S5 (term 3) can no longer win an election.
This is also why a new leader writes a no-op entry as soon as it takes office. In etcd’s Raft implementation, a new leader holds off on read requests that need a consistency check until it has committed the first entry of its own term.
Reads need confirmation too
The leader’s local state is not always current: an old leader cut off by a network partition does not know that the other side has already elected a new leader and accepted new writes. It still believes it is the leader, and it replies with stale data.
| Approach | How | Cost |
|---|---|---|
| Write reads into the log too | Treat a read as a log entry and reply only after it is committed | Every read writes to disk; the slowest |
| ReadIndex | The leader records the current commit position, confirms with a majority of nodes that it is still the leader, waits until the state machine has applied up to that position, then reads its local data | One extra network round trip per read, no disk write |
| Lease read | During its lease, the leader assumes it is still the leader and reads its local data directly | Fastest, but depends on the clock drift of every machine being bounded |
| Follower read | A follower gets a ReadIndex from the leader, waits until it has applied up to that position, then reads its local data | Takes read load off the leader |
Reads in etcd are linearizable by default and go through Raft. You can also ask for serializable reads, which read only the local data of the member you are connected to: lower latency, and they still answer when quorum is lost, but the data may be stale. This is the PACELC trade-off reduced to a single API parameter.
Membership changes
When you grow from 3 machines to 5, if each machine switches to the new configuration at a different moment, a “majority of the old configuration” and a “majority of the new configuration” may not overlap, and each side elects its own leader. Raft’s answer is to add or remove one machine at a time (the majorities of any two adjacent configurations always overlap), or to transition through joint consensus.
Since 3.4, etcd supports learners: a new member joins without a vote, catches up on the leader’s log, and is then promoted to a voting member. If a new member joined with a vote right away, the cluster’s majority threshold would go up before the member had caught up, and the cluster would gain one more member that slows down commits. etcd’s --strict-reconfig-check is on by default and rejects membership changes that would make the cluster lose quorum.
When an isolated node comes back
A follower cut off by the network receives no heartbeats, so it keeps timing out and keeps incrementing its term. When the network recovers, it comes back with a large term; the healthy leader sees the larger term and steps down, which triggers an unnecessary election.
- PreVote: before running, a node asks the others “if I ran, would you vote for me?”, and this step does not increment the term. Nodes that have heard the leader’s heartbeat recently say no. Since etcd 3.5,
--pre-voteis on by default - CheckQuorum: a leader that does not hear back from a majority of nodes within one election timeout steps down on its own, so an old leader isolated in the minority does not go on believing it is the leader. etcd’s Raft library offers this as an option
The limits of the theory
The FLP result (1985) proves that in an asynchronous system with no upper bound on message delay, if even one machine may crash, no deterministic algorithm can guarantee reaching consensus in finite time. Raft’s trade-off: safety always holds (two different values are never committed at the same position), while progress depends on timing assumptions (a leader can be elected only when network delay is stable enough). When the network is very unstable, Raft may fail to elect a leader and stop accepting writes, but it never writes anything wrong.
Comparing options
Consensus algorithms
| Algorithm | Used by | Characteristics |
|---|---|---|
| Raft | etcd, Consul, Kafka (KRaft), TiKV, CockroachDB | Designed to be easy to understand, strong leader, the most implementations and documentation |
| Multi-Paxos | Google Chubby, Spanner | The earliest approach proven correct; many variants, and implementations differ widely |
| ZAB | ZooKeeper | A strong-leader design similar to Raft |
| Paxos variant | MySQL Group Replication | Built into the database’s replication |
Distributed databases such as TiKV and CockroachDB split their data into many ranges, and each range is its own Raft group (multi-Raft). They use Sharding to get past the write ceiling of a single leader.
Use an existing service, do not build your own
The Raft paper is easy to read, but a correct implementation has to handle disk write failures, snapshots, membership changes, and every combination of reordered and resent messages, all of which are hard to test. When an application needs consensus, use etcd, ZooKeeper, or Consul. If all you need is “run only one copy of the scheduled job” and you already have a database, a row in the database used as a lock (ShedLock, for example) is usually enough. The next post compares the two.
Cluster size and placement
| Setup | Tolerates | Write latency |
|---|---|---|
| 3 machines, one availability zone | 1 machine failure | Lowest, but an availability zone failure takes everything down |
| 3 machines, 1 in each of 3 availability zones | 1 machine or 1 availability zone failure | Every write waits for another availability zone |
| 5 machines, 3 availability zones as 2/2/1 | 2 machines or 1 availability zone failure | Same as above; a majority can be formed from two availability zones |
| Across regions | 1 region failure | Every write waits for at least one cross-region round trip |
Write latency depends on the round trip from the leader to its (majority - 1)th closest follower, plus the disk write.
In Java
1. Run the scheduled job only on the leader
etcd has a built-in election API: each instance gets a lease with a TTL and campaigns with that lease. The winner keeps renewing the lease; when it stops renewing (a crash, a disconnect, a long GC pause), the lease expires and leadership passes to the next candidate automatically.
import static java.nio.charset.StandardCharsets.UTF_8;
import io.etcd.jetcd.ByteSequence;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.election.LeaderKey;
import io.etcd.jetcd.lease.LeaseKeepAliveResponse;
import io.etcd.jetcd.support.CloseableClient;
import io.grpc.stub.StreamObserver;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
/** Every instance campaigns; only the one that wins returns a leadership. */
public class EtcdLeadership implements AutoCloseable {
private static final long LEASE_TTL_SECONDS = 10;
private final Client client;
private final ByteSequence election;
private final ByteSequence instanceId;
private final Thread campaigner;
private volatile LeaderKey leadership; // null means this instance is not the leader right now
public EtcdLeadership(Client client, String electionName, String instanceId) {
this.client = client;
this.election = ByteSequence.from(electionName, UTF_8);
this.instanceId = ByteSequence.from(instanceId, UTF_8);
this.campaigner = Thread.ofVirtual().name("campaign-" + electionName).start(this::campaignForever);
}
public Optional<LeaderKey> current() {
return Optional.ofNullable(leadership);
}
private void campaignForever() {
while (!Thread.currentThread().isInterrupted()) {
try {
campaignOnce();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
pause(); // cannot reach etcd; campaign again shortly
}
}
}
private void campaignOnce() throws InterruptedException, ExecutionException {
long leaseId = client.getLeaseClient().grant(LEASE_TTL_SECONDS).get().getID();
CountDownLatch lost = new CountDownLatch(1);
CloseableClient keepAlive = client.getLeaseClient().keepAlive(leaseId, signalOnFailure(lost));
try {
// Blocks until elected; the lease keeps being renewed while waiting
leadership = client.getElectionClient().campaign(election, leaseId, instanceId).get().getLeader();
lost.await(); // a keep-alive error or the stream ending always counts as losing leadership
} finally {
leadership = null;
keepAlive.close();
client.getLeaseClient().revoke(leaseId); // lets another instance take over now instead of waiting for the TTL
}
}
private static StreamObserver<LeaseKeepAliveResponse> signalOnFailure(CountDownLatch lost) {
return new StreamObserver<>() {
@Override
public void onNext(LeaseKeepAliveResponse response) {
}
@Override
public void onError(Throwable error) {
lost.countDown();
}
@Override
public void onCompleted() {
lost.countDown();
}
};
}
private static void pause() {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void close() {
campaigner.interrupt();
}
}Before each run, the scheduled job checks leadership and passes the leader key’s revision down:
@Component
public class LectureReminderJob {
private final EtcdLeadership leadership;
private final ReminderService reminderService;
public LectureReminderJob(EtcdLeadership leadership, ReminderService reminderService) {
this.leadership = leadership;
this.reminderService = reminderService;
}
@Scheduled(fixedDelay = 60_000)
public void run() {
leadership.current().ifPresent(key -> reminderService.sendUpcoming(key.getRevision()));
}
}- An error on the keep-alive stream does not necessarily mean the lease has expired (jetcd re-creates the stream automatically), but here it always counts as losing leadership, and the instance campaigns again. Better to have no leader for a moment than two instances that both think they are the leader
getRevision()is the revision at which the leader key was created in etcd. etcd revisions increase globally, so a leader elected later always has a larger revision. The next post uses it as a fencing token
2. Choose read consistency by use case
KV kv = client.getKVClient();
ByteSequence key = ByteSequence.from("/config/registration-paused", UTF_8);
// Linearizable by default: confirmed through Raft, always reads the latest value; fails when the cluster has lost quorum
GetResponse latest = kv.get(key).get();
// Serializable: reads only the local data of the member you are connected to, may be stale; still answers when quorum is lost
GetResponse local = kv.get(key, GetOption.builder().withSerializable(true).build()).get();Use a linearizable read for a switch like “pause sign-ups” that has to take effect immediately. Use a serializable read for data such as UI display settings, where taking effect a few seconds late does no harm, so it can still be read when etcd is partly down.
The code above is written against the jetcd 0.8.8 API and the official etcd documentation; it has not been run against a real etcd.
Pitfalls and gotchas
- Leader election is not mutual exclusion: instance A checks leadership and then goes into a long GC pause. The lease expires, instance B is elected and starts sending reminders, and when A wakes up it finishes sending its batch. There is always a gap between the check and the action. Downstream has to be able to reject operations from an old leader (a fencing token), or the operation has to be idempotent (for example, a unique index on the send log). The next post covers this in detail
- An even number of nodes: 4 machines tolerate the same number of failures as 3; they only add latency and points of failure
- Slow disks: etcd writes to disk on every write. When disk write latency is high, the leader cannot send heartbeats in time, the followers time out and start elections, and the leader changes often. The official docs strongly recommend SSDs and monitoring
etcd_disk_wal_fsync_duration_secondsandetcd_disk_backend_commit_duration_seconds - Keeping the default timeouts in a cross-region deployment: with an RTT of tens to hundreds of milliseconds, a 1-second election timeout is too short, and any network blip triggers a new election. Tune it to the RTT, with the same settings on every member
- Using etcd as a database: etcd’s default storage limit is 2 GB, and the official recommendation is no more than 8 GB. It suits small amounts of coordination data that need strong consistency, not business data
- Adding several new members at once: a new member should not vote before it has caught up on the log. Add it as a learner and promote it once it has caught up, one member at a time
- Permanently losing a majority: if 3 of 5 machines have corrupted disks, the cluster can never reach consensus again and can only be rebuilt from a snapshot. Back up snapshots regularly and rehearse restores
- A write timeout does not mean the write failed: when the client times out, the write may already be committed. Retries have to be idempotent
Security
- Raft does not defend against malicious nodes: Raft tolerates only crashes and network problems, and it assumes every node is honest. A compromised member can send huge terms and keep disrupting elections; once elected, it can write arbitrary log entries, and the other nodes accept them without question. Communication between members needs mTLS (etcd’s
--peer-client-cert-auth), so that only machines holding a certificate signed by the cluster CA can join. Where you have to withstand malicious participants (a ledger shared across organizations, for example), use a Byzantine fault-tolerant protocol such as PBFT, which needs 3f + 1 machines to tolerate f malicious nodes - etcd holds the keys to the whole system: Kubernetes stores all of its state in etcd, Secrets included. Client connections should verify certificates too (
--client-cert-auth), RBAC should be enabled (etcdctl auth enable), and ports 2379 and 2380 should never be exposed to the outside - Election keys need authorization too: any client that can write under the election key prefix can campaign and take leadership, or delete the current leader’s key to force a handover. Use RBAC to grant write access to the election prefix only to the service accounts that need it
- Snapshots and backups are full copies of the data: an etcd snapshot contains all of the data. If Kubernetes does not have encryption at rest enabled for Secrets, the Secrets in a snapshot are only base64-encoded. Encrypt backup files, restrict access to them, and protect where they are stored as strictly as etcd itself
- Fail closed during a partition: when quorum is lost, linearizable reads fail. Do not switch data such as permissions and account status to serializable reads just to keep letting requests through (the CAP and PACELC post)
When to use it, and when not to
- Use a consensus service: for leader election, primary database failover, configuration and service registration, and as the foundation of distributed locks; in other words, small amounts of coordination data where mistakes are very costly and strong consistency is required
- Don’t use it: for large volumes of business data or high-throughput writes (every write goes through the leader and the disks of a majority of nodes)
- Don’t implement Raft yourself: unless you are building a database or a coordination service itself
- Consider something simpler first: if all you need is to run only one copy of a scheduled job and you already have a database, a database lock is usually enough
References
- Diego Ongaro, John Ousterhout, “In Search of an Understandable Consensus Algorithm (Extended Version)”, USENIX ATC 2014: https://raft.github.io/raft.pdf
- Diego Ongaro, “Consensus: Bridging Theory and Practice”, Ph.D. dissertation, Stanford University, 2014
- The Raft Consensus Algorithm: https://raft.github.io/
- Leslie Lamport, “Paxos Made Simple”, ACM SIGACT News, 2001
- Michael J. Fischer, Nancy A. Lynch, Michael S. Paterson, “Impossibility of Distributed Consensus with One Faulty Process”, Journal of the ACM, 1985
- etcd-io/raft README (ReadIndex and lease read): https://github.com/etcd-io/raft
- etcd Documentation — API guarantees: https://etcd.io/docs/v3.8/learning/api_guarantees/
- etcd Documentation — Tuning: https://etcd.io/docs/v3.8/tuning/
- etcd Documentation — Runtime reconfiguration (learner): https://etcd.io/docs/v3.8/op-guide/runtime-configuration/
- etcd Documentation — Configuration options: https://etcd.io/docs/v3.8/op-guide/configuration/
- etcd Documentation — Hardware recommendations: https://etcd.io/docs/v3.8/op-guide/hardware/
- etcd Documentation — Transport security model: https://etcd.io/docs/v3.8/op-guide/security/
- etcd Documentation — Concurrency API reference (Election): https://etcd.io/docs/v3.8/dev-guide/api_concurrency_reference_v3/
- jetcd: https://github.com/etcd-io/jetcd
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments