kvaps

Blog

PreVote and CheckQuorum: why etcd won't re-elect a leader when you really want it to

etcdraftkubernetesstretched-cluster

A look at two Raft extensions that protect etcd from unnecessary elections, and why the same extensions can leave a cluster member without a leader for hours during a partial network partition.

Contents

When etcd is stretched across several sites, sooner or later you get a partial partition: sites A and B stop seeing each other, while the witness in C sees both. Everyone expects roughly the same thing: the cluster will “somehow” re-elect a leader on its own and keep working. In practice, the member on the cut-off side can stay leaderless for as long as the partition lasts, and the leader doesn’t move anywhere.

This is not a bug. It is a direct consequence of two mechanisms that etcd enables on purpose: PreVote and CheckQuorum. Let’s look at what each of them does, how they are implemented inside etcd, where leader lease fits in, and what all of this means for a stretched cluster.

One disclaimer up front: this is a review, not an experiment report. There are no measurements of my own here, only primary sources: Ongaro’s dissertation, the etcd-io/raft and etcd-io/etcd code, and the etcd documentation. Links are at the end.

Why this is needed at all #

Basic Raft is simple. The leader sends heartbeats; a follower that hasn’t heard from the leader for longer than the election timeout increments its term and starts an election. Any node that sees a message with a higher term must adopt that term and, if it was the leader, step down.

This simplicity has two unpleasant sides.

First: unnecessary elections. A node cut off from the cluster keeps going into elections and keeps bumping its term, even though it cannot win. When connectivity returns, its high term spreads through the cluster via RequestVote or via an AppendEntries response, and the healthy leader is forced to step down. Ongaro describes exactly this scenario in §9.6 of his dissertation and honestly says such events are rare and each one costs a single re-election. But on a flapping network, “rare” quickly turns into “all the time”.

Second: a stuck leader. A leader that ends up in the minority doesn’t find out about it on its own. It keeps believing it is the leader, accepts requests from whichever clients can reach it, and cannot commit them. §6.2 of the dissertation puts it plainly: without an extra mechanism, such a leader can delay a client request indefinitely, even though on the other side there is already a leader of a newer term that could commit it.

PreVote fixes the first problem, CheckQuorum the second. And, as usual, there is a catch: in etcd they only work as a pair.

How it works #

PreVote #

The idea of PreVote (§9.6) is to hold a “trial” election before the real one. The candidate does not increment its term; first it asks the others: would you vote for me if I started an election? A vote is granted only if the candidate’s log is up to date enough and the voter itself hasn’t heard from a valid leader for at least the base election timeout. The term grows only if a majority agrees.

As a result, a cut-off node cannot inflate its term: the majority won’t respond to it. And when it comes back, they still won’t respond, because the others are regularly getting heartbeats from the leader. The very first heartbeat turns it back into a follower in the same term.

In the etcd-io/raft library this is the Config.PreVote field, and its comment points directly to §9.6 of the dissertation. The candidate sends MsgPreVote with a term one higher than its own, but does not change its own term. The receiver doesn’t change its term in response to MsgPreVote either.

CheckQuorum #

CheckQuorum solves the second problem. The leader tracks which followers it has heard from and, once per election timeout, checks whether a quorum was active during that period. If not, it steps down to follower. In code it looks like this: in tickHeartbeat, when electionElapsed >= electionTimeout, the leader sends itself MsgCheckQuorum, and in stepLeader, when !r.trk.QuorumActive(), it calls becomeFollower with this log message:

stepped down to follower since quorum is not active

After the check, all peers are marked inactive so that the next round measures activity from scratch.

The lease check on voting, or why they work as a pair #

The most interesting part is hidden in raft.Step. When a MsgVote or MsgPreVote arrives with a term higher than ours, the node first checks whether it is “within the lease” of the current leader:

inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
if !force && inLease {
    // If a server receives a RequestVote request within the minimum election timeout
    // of hearing from a current leader, it does not update its term or grant its vote
    ...
    return nil
}

This is the rule from §4.2.3 of the dissertation. It was introduced there for a different problem: protecting the cluster from servers that have been removed from the configuration and don’t know it. If a node heard from the leader less than the minimum election timeout ago, it neither changes its term nor grants its vote. The request is simply ignored, and the etcd log gets a line with lease is not expired.

Note the r.checkQuorum in the condition. This check is exactly what implements the part of PreVote where the voter “hasn’t heard from a valid leader”. In the voting function itself, for a MsgPreVote with a future term it’s enough for the candidate’s log to be no older than ours:

canVote := r.Vote == m.GetFrom() ||
    (r.Vote == None && r.lead == None) ||
    (m.GetType() == pb.MsgPreVote && m.GetTerm() > r.Term)

So in etcd-io/raft, PreVote without CheckQuorum only protects against term inflation; it doesn’t stop a follower that can hear the leader from voting for a candidate. Only the combination gives you the full picture from §9.6.

On the leader, r.lead equals its own ID, and electionElapsed is reset every election timeout, so the leader is also always “within the lease” and ignores other nodes’ elections with a higher term.

There is one exception: force. These are elections triggered by a leadership transfer (campaignTransfer). The leader itself asked the candidate to replace it, so the lease check is skipped. Ongaro describes this as a special flag meaning “I have permission to depose the leader, it asked me to”. In etcd this path is exposed externally via etcdctl move-leader.

What exactly is enabled in etcd #

Versions get mixed up a lot here, so point by point:

  • CheckQuorum is always enabled in etcd and cannot be configured. The server’s raftConfig has CheckQuorum: true, and there is no flag for it. That was the case in the 3.4 branch and it still is in current main.
  • PreVote is controlled by the --pre-vote flag. The flag already existed in 3.4 but was off by default: embed/config.go in the release-3.4 branch has PreVote: false with the comment TODO: enable by default in v3.5. It was turned on by default in v3.5.0 (PR etcd-io/etcd#12770); the CHANGELOG phrases it as “Should prevent disrupting RAFT leader by an individual member”. So if you still have a 3.4 running somewhere with default settings, PreVote is off.
  • ReadOnlyOption is not set by etcd, so the default ReadOnlySafe is used. Linearizable reads go through ReadIndex, meaning the leader confirms its leadership with a round of heartbeats to a quorum before replying. More on that below.
  • Timings: --heartbeat-interval defaults to 100 ms, --election-timeout to 1000 ms. etcd passes HeartbeatTick: 1 to raft and ElectionTick as the ratio of one to the other, so 10 ticks by default. The actual election timeout on each node is randomized in the range of one to two election timeouts.

The tuning documentation recommends setting the heartbeat roughly equal to the maximum average RTT between members, and the election timeout to at least 10 times the RTT. The upper limit is 50 seconds, and according to the docs it’s only meant for globally distributed clusters.

The easiest way to check what you’re actually running is via process arguments and logs:

# which flags were passed (if not passed, your version's default applies)
ps -o args= -C etcd | tr ' ' '\n' | grep -E 'pre-vote|election-timeout|heartbeat-interval'

# version, leader and term of each member
etcdctl --endpoints=https://10.0.0.1:2379,https://10.0.0.2:2379,https://10.0.0.3:2379 \
  --cacert=ca.crt --cert=client.crt --key=client.key \
  endpoint status -w table

A partial partition, step by step #

Take three members: A and B at the two main sites, witness C at the third. The leader is in A. The A–B link breaks, C sees both.

With PreVote and CheckQuorum (etcd 3.5+ default):

  1. A keeps hearing C. The A+C quorum is active, CheckQuorum leaves the leader alone, writes get committed.
  2. B stops receiving heartbeats and, after the election timeout, starts PreVote. It sends MsgPreVote to C (the message never reaches A).
  3. C hears the leader, is within the lease, and ignores the request. B can’t get a majority, the term doesn’t grow.
  4. This goes on until connectivity returns. B is leaderless the whole time, and every client connected to it gets errors or timeouts.

For Raft this is correct behavior: the cluster is alive, there’s a quorum, no unnecessary elections. But if B runs a kube-apiserver that only talks to its local etcd, from Kubernetes’ point of view that’s one half-dead control-plane node. The fix is a single command: etcdctl move-leader to the member in C, which sees everyone. Then A and B are both neighbors of the leader. This is exactly the command that threek automates; it’s covered in detail in Ænix’s Habr article about losing a datacenter. There is no ready-made mechanism upstream: leader priority was proposed in etcd-io/etcd#10201 and the issue was closed, and while the raft library does have ForgetLeader (etcd-io/raft#78), etcd doesn’t use it.

Without PreVote and without CheckQuorum (plain Raft):

  1. After the election timeout, B increments its term and sends MsgVote to C.
  2. C sees the higher term, adopts it, loses its leader, and votes for B if B’s log is not older.
  3. B becomes leader in the new term. A learns about the new term from C and steps down to follower.
  4. Now A is the one without a leader, because it can’t hear B. After the election timeout A starts an election with its own term+1, and everything repeats in the other direction.

That’s the election storm: leadership bounces between A and B, and every move is a window during which writes don’t commit. This is precisely what PreVote and CheckQuorum protect against.

CheckQuorum only, no PreVote (etcd 3.4 default): C is within the lease and won’t give B its vote, so there’s no storm. But B keeps bumping its term on every attempt. When the A–B link comes back, B’s high term reaches A in an AppendEntries response, and the leader has to step down — exactly the §9.6 scenario. One unnecessary re-election after recovery.

Asymmetry and the stuck leader #

“Asymmetric” partitions deserve a separate word. A packet filter that cuts traffic in one direction almost always becomes a two-way cut for TCP: no stream survives without ACKs. So for etcd, asymmetry in practice looks either like the partial connectivity described above, or like stateful filtering, where only new connections are cut and established ones keep living. etcd peer streams are long-lived, and in this mode the cluster can look healthy for quite a while, until some connection gets re-established.

The most dangerous case for “sticking” is when the leader is isolated entirely, but its clients can still reach it. Without CheckQuorum it remains leader in its own view forever. With CheckQuorum it steps down to follower after the election timeout, and clients get an error and can switch to another endpoint. That’s exactly why CheckQuorum can’t be turned off in etcd.

Where leader lease fits in #

The word lease is used for three different things here, and it’s worth separating them.

Lease as in the lease check on voting. This is inLease from the code above: “I heard from the leader less than an election timeout ago, so I’m not electing anyone”. Only works with CheckQuorum.

Leader lease for reads (§6.4.1). Ongaro describes a variant where the leader, after a majority acknowledges its heartbeats, assumes nobody else will become leader for roughly an election timeout, and serves reads without contacting the quorum. The price is an assumption of bounded clock drift. Ongaro lists explicitly what breaks it: scheduler and GC pauses, VM migrations, clock rate adjustments. When it’s violated you can return arbitrarily stale data, and LogCabin doesn’t implement this variant. etcd-io/raft has it as ReadOnlyLeaseBased, and the library refuses to start with it unless CheckQuorum is on. etcd doesn’t enable it and uses ReadIndex. For a stretched cluster that’s good news: an isolated leader cannot serve a linearizable read, because ReadIndex requires a quorum response. Serializable reads, which a member serves from local data, are a different story: they can be stale on either side of the partition.

Lease in the etcd API, i.e. keys with a TTL. On a leader change, the new leader calls lessor.Promote(electionTimeout) and extends all leases. Without checkpoints, the remaining TTL is not preserved: the lease starts counting from scratch, for the full TTL plus the election timeout. To avoid this there’s --experimental-enable-lease-checkpoint (off by default in 3.5) and --experimental-enable-lease-checkpoint-persist, added in 3.5.2. In 3.6 the same thing is also wired up as the LeaseCheckpoint feature gate, off by default.

What this means for a stretched cluster #

Here are the practical takeaways.

Losing an entire site is a normal scenario. If the site with the leader disappears completely, the remaining members fall out of the lease after the election timeout, PreVote succeeds, and a new leader is elected. Failover time is one to two election timeouts plus network latency. If you raised the election timeout to fit inter-city RTT, failover gets slower in the same proportion. That’s a deliberate price, not a misconfiguration.

A partial partition is not normal. Raft survives it, but not the way Kubernetes expects. The quorum stays, and the cut-off member stays leaderless until the partition ends. If the apiserver on that node only talks to its local etcd, the node drops out. Options: give the apiserver all etcd endpoints, or move the leader to the witness with move-leader, manually or automatically. Disabling PreVote for the sake of “self-healing” is a bad idea: instead of one stuck member you get an election storm.

etcd leases live longer after a leader move. If you’ve built locks or leader election on top of etcd leases — for example, Patroni with etcd as its DCS — then after losing the site with the etcd leader, the lock will be released not after the TTL but later. Leader election in Kubernetes itself works differently: coordination.k8s.io/Lease objects store the renewal time, and clients make the decision based on their own clocks, not on etcd’s TTL.

The witness must see everyone. All the storm protection rests on C hearing the leader. So the witness is not “some third machine”, it’s the best-connected member in the cluster.

How to check it yourself #

You need three etcd 3.5+ instances on three machines, or in three containers with separate network namespaces, so you can cut traffic between pairs. The steps below are for node B, where A is the address of member A.

A symmetric A–B partition, with C still seeing both:

iptables -I INPUT  -s "$A" -j DROP
iptables -I OUTPUT -d "$A" -j DROP

Stateful firewall mode, where only new connections are cut:

iptables -I INPUT -s "$A" -m conntrack --ctstate NEW -j DROP

What to watch:

  • etcdctl endpoint status -w table across all three endpoints: who the leader is and whether RAFT TERM grows. With PreVote, B’s term should not grow during the partition.
  • C’s logs: lines like ignored MsgPreVote from ... lease is not expired.
  • The leader’s logs after full isolation: stepped down to follower since quorum is not active.
  • The etcd_server_has_leader, etcd_server_is_leader and etcd_server_leader_changes_seen_total metrics on each member.

Repeat the same with --pre-vote=false, and the difference in term behavior is visible immediately. To restore the network, use the same rules with -D instead of -I. Do this on a test setup, not on a cluster that hosts your control plane.

What it can’t do #

  • It doesn’t pick a leader by connectivity. PreVote and CheckQuorum answer the question “do we need an election”, not “where is the best place for the leader”. Raft doesn’t know that C sees everyone and A doesn’t.
  • It doesn’t fix a partial partition. That stays a stable but inconvenient state: the leaderless member waits for the network to be fixed.
  • It doesn’t help when removing members. §4.2.3 explicitly shows a case where PreVote is powerless: a server being removed that has a sufficiently fresh log. What saves you there is the lease check, not the log comparison.
  • It doesn’t give you fast failover across distant sites. The election timeout is tied to RTT, and you can’t shorten failover time without risking spurious elections.
  • It doesn’t protect serializable reads. A cut-off member will keep serving whatever it has.

In short, PreVote and CheckQuorum make Raft resistant to unnecessary elections, and that is exactly why it won’t re-elect a leader when you really want it to :)

Sources #