Scrivio Interview library
InternalsFoundations7 min read · updated 13 November 2026

ZooKeeper and etcd are coordination services: small, strongly consistent stores with sessions or leases and change notifications, often used to elect one leader among many instances.

How does leader election work with ZooKeeper ephemeral sequential znodes, why does each candidate watch only its predecessor, and how does the etcd approach with leases compare?

With ZooKeeper, each candidate creates an ephemeral sequential znode under an election path, and the one with the lowest sequence number is the leader; ephemeral nodes disappear when their creator's session ends, so a dead leader's node vanishes and the next candidate takes over. Each candidate watches only the node just before its own, so a change wakes one candidate instead of all of them (the herd effect). With etcd, candidates put a key attached to a lease that they keep alive, the key with the lowest creation revision wins, and it vanishes when the lease expires; in both, a leader that loses its session or lease must stop acting, and protected resources should check a fencing value such as the sequence number or revision.

Why this question is asked

Running exactly one active instance of something, a scheduler, a partition owner, a primary, is one of the most common coordination needs, and ZooKeeper and etcd are the standard tools for it. The recipes are short, but each detail exists to prevent a specific failure. Interviewers ask this question to see whether we know those details: why the nodes are ephemeral, why each candidate watches only its predecessor, and what a leader must do when it may have been replaced without knowing. In this answer, we will recap the two services, walk through the ZooKeeper recipe, explain the herd effect, do the same with etcd leases, and finish with fencing and the Java libraries that implement it.

1A Quick Recap of Coordination Services

ZooKeeper and etcd are small, strongly consistent stores replicated with consensus (ZAB in ZooKeeper, Raft in etcd). They hold little data, but every client sees the same order of changes, and they offer two features that make election possible: something that disappears automatically when a client dies, and notifications when data changes.

In ZooKeeper, a client holds a session kept alive by heartbeats; if the heartbeats stop for longer than the session timeout, the session expires. An ephemeral znode is a node tied to the session that created it, deleted automatically when that session ends. A sequential znode gets a monotonically increasing number appended to its name by the server. A watch is a one-time notification when a znode changes or is deleted. In etcd, the equivalent of a session is a lease, a time-to-live the client keeps alive, and keys can be attached to a lease so they are deleted when it expires; watches stream changes.

2The ZooKeeper Recipe

Every candidate creates a znode under the election path with both flags, ephemeral and sequential. The server names them in order: n_0000000015, n_0000000016, n_0000000017. Each candidate then lists the children. If its own node has the lowest number, it is the leader. Otherwise it finds the node with the next lower number, its predecessor, and sets a watch on it.

When the leader crashes, or its session times out, its ephemeral node is deleted. The candidate that was watching it is notified, lists the children again, finds that it now has the lowest number and becomes leader. If instead a node in the middle of the queue disappears, its successor is notified, sees it is still not lowest and simply watches the next lower node.

Java
// what each candidate does (ZooKeeper Java API, simplified)
String me = zk.create("/election/n_", hostId, OPEN_ACL_UNSAFE, EPHEMERAL_SEQUENTIAL);
// me = "/election/n_0000000017"
List<String> kids = sorted(zk.getChildren("/election", false)); // [n_..15, n_..16, n_..17]
if (kids.get(0).equals(name(me))) {
becomeLeader();
} else {
String predecessor = kids.get(kids.indexOf(name(me)) - 1); // n_0000000016
zk.exists("/election/" + predecessor, event -> recheck()); // watch only that node
}
Step throughLeader election with ephemeral sequential znodes
Candidate 15 (leader)ZooKeeperCandidate 16Candidate 17
watch n_15 (my predecessor)
watch n_16 (my predecessor)
crashes; session expires
delete ephemeral n_15
watch fired: n_15 deleted
list children: I am lowest
become leader

7 messages in order. Play them, or step through them one at a time.

Only candidate 16 is woken; candidate 17 keeps waiting on n_16.

3Why Watch Only the Predecessor

A simpler design would have every candidate watch the leader's node. Then when the leader dies, every candidate is notified at once, every one lists the children, and all but one discover they are not leader and set their watches again. With 100 candidates, one leader change causes 100 notifications and 100 list requests at the same instant, a burst of load on ZooKeeper at exactly the moment the system is recovering. This is called the herd effect.

Watching only the predecessor turns the herd into a chain. One deletion wakes exactly one candidate, whatever the size of the group, and the cost of a leader change stays constant. It also handles candidates leaving from the middle of the queue gracefully, as we saw.

4The etcd Approach With Leases

With etcd, each candidate grants a lease with a TTL, for example 10 seconds, and keeps it alive with periodic keep-alive messages. It then puts a key under an election prefix, such as /election/svc/<lease-id>, attached to that lease. Every key in etcd records the revision at which it was created, a cluster-wide increasing number. The candidate whose key has the lowest create revision is the leader; the others watch the key with the next lower revision, the same predecessor idea.

If the leader dies, its keep-alives stop, the lease expires after the TTL, its key is deleted and the next candidate is notified. etcd's concurrency package and its election API wrap this recipe, using a transaction that creates the key only if it does not exist and then campaigns by waiting for keys with lower revisions to disappear.

ZooKeeper and etcd election compared
AspectZooKeeperetcd
Liveness tiesession (heartbeats, session timeout)lease (TTL, keep-alive)
Orderingsequence number in the znode namekey's create revision
Leaderlowest sequence numberlowest create revision
Avoiding the herdwatch the predecessor znodewatch the predecessor key
Fencing valueznode sequence (or zxid)key revision or lease id
Java libraryApache Curator LeaderLatch, LeaderSelectorjetcd Election client

5Stepping Down and Fencing

In both systems, a leader that loses its session or lease must stop acting as leader. The difficulty is that it may learn this late. A leader paused by a 15-second GC pause has its session expire during the pause, another candidate becomes leader, and then the old leader wakes up and continues writing, believing it is still in charge. For a few moments there are two leaders.

Stepping down promptly helps but cannot close the gap, because the pause can happen at any instruction. The robust answer is fencing. Each leadership carries a number that only increases: the znode's sequence number in ZooKeeper, or the key's revision in etcd. The leader sends it with every write to the protected resource, and the resource rejects any write carrying a smaller number than one it has already seen. When the old leader wakes and writes with token 15, the database, which has already seen 16 from the new leader, refuses it.

In Java we rarely write the recipe by hand. Apache Curator implements it for ZooKeeper: LeaderLatch for 'am I leader' checks and LeaderSelector for running a task while leader, with listeners for session loss. Even with Curator, the application must still react to losing leadership and use fencing for writes that matter.

6Follow-up questions

What happens if the ZooKeeper connection drops briefly but the session does not expire?

The client is disconnected but its session, and the ephemeral node, survive until the session timeout. Curator reports this as a suspended state; a careful leader pauses work while suspended and resumes if the connection returns before expiry, or steps down if the session is lost.

Why not use a regular, non-sequential lock node?

With a single lock node, every waiting candidate must watch it and retry creating it when it is deleted, which brings back the herd effect, and there is no natural fencing number. Sequential nodes give both an orderly queue and an increasing token.

How long does failover take?

Roughly the session timeout or lease TTL plus a notification round trip. Shorter timeouts mean faster failover but more false failovers during GC pauses or network blips, so values of 10 to 30 seconds are common.

7Conclusion

In this answer, we saw that ZooKeeper elections use ephemeral sequential znodes: the lowest sequence number leads, ephemeral nodes vanish when their session ends so a dead leader is replaced automatically, and each candidate watches only its predecessor to avoid the herd effect. etcd achieves the same with keys attached to leases and ordered by create revision. In both, a leader that loses its session or lease must stop, and because it may learn too late, writes to protected resources should carry a fencing value, which Curator users must still handle on top of LeaderLatch and LeaderSelector.

What to say in the interviewAbout 90 seconds aloud

Open with

In ZooKeeper, each candidate creates an ephemeral sequential znode under an election path, say /election/n_0000000017. The server assigns increasing sequence numbers, and whoever has the lowest number is the leader.

Then, if they want more

Ephemeral means the znode is tied to the creator's session, so if the leader crashes or its session times out, its node is deleted automatically and the next candidate takes over. Each candidate watches only the node immediately before its own.

If everyone watched the leader's node, every change would wake every candidate at once and they'd all hit ZooKeeper together, which is the herd effect; watching the predecessor means one deletion wakes exactly one candidate.

With etcd it's the same idea built on leases: each candidate grants a lease with a TTL, keeps it alive, and puts a key attached to it under an election prefix. The key with the lowest create revision is leader, others watch their predecessor, and when a leader's lease expires its key disappears. etcd's election API wraps this.

In both, a leader that loses its session or lease must stop acting, but it can learn that late, for example after a long GC pause, so protected resources should check a fencing value like the znode sequence or the key's revision and reject older ones.

In Java I'd use Apache Curator's LeaderLatch or LeaderSelector rather than writing the recipe myself.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does leader election work with ZooKeeper ephemeral sequential znodes, why does each...": https://scrivio-interview-library.netlify.app/architecture/distributed-systems/4c2a6230cb/