Summary#
Many systems need exactly one process to do a job at a time: one primary database per shard, one scheduler firing cron jobs, one controller reconciling a cluster, one consumer per partition. Choosing that process, and replacing it when it fails, is leader election. Doing it safely is harder than it looks, because a leader that is merely slow or partitioned looks exactly like one that has crashed, so a naive election produces two leaders, a split brain that corrupts data or duplicates work. The reliable way is to delegate the decision to a coordination service built on consensus, such as ZooKeeper, etcd or Consul, which can tell every candidate the same answer. Candidates race to create a key, or an ephemeral node, tied to a lease or session that expires unless renewed every few seconds. Whoever holds the key is leader. Others watch it and try again when it disappears. A lease alone is not enough, because a leader can pause past its lease without knowing it, so every leader also gets a fencing token, a number that increases with each new leader, and the resources it writes to reject requests carrying an older token. The same coordination services also act as service registries, where instances register with ephemeral entries and clients watch for changes, and as configuration stores, where a change is pushed to every watcher within milliseconds. Use them for small, critical, slowly changing data, typically kilobytes to a few gigabytes in total, and keep bulk data elsewhere.
Why It Exists#
Imagine a chat application running on one server. Every user is connected to that server, so when one user sends a message to another, the server simply looks up the recipient's connection in memory and pushes the message. No coordination is needed, because there is only one place where anything happens.
Now the app grows to 50 servers. Users connect to whichever server the load balancer picks. When a user on server 12 messages a user on server 37, server 12 must learn that the recipient lives on server 37, and it needs to keep learning as users reconnect, servers are added, and servers crash. Meanwhile, a background job that sends daily digest emails must run on exactly one server, or users get 50 emails. A configuration change, such as raising the maximum message size, must reach all 50 servers, and they should not disagree for long about the value.
These are coordination problems:
- Who is in charge? Exactly one instance should run the digest job, own a partition, or act as primary.
- Who is alive, and where? Which servers exist right now, and which user or shard is on which server?
- What is the current configuration? Every instance should converge to the same settings quickly.
- Who holds this resource? Only one instance should modify a given account, file or job at a time.
Each instance could try to answer these questions itself, by pinging the others. But, as described in Failure Detection and Gossip, instances' views of who is alive will differ during partitions, and every instance will reach its own conclusion. A coordination service solves this by being the single, consistent source of truth, replicated with consensus so that it stays available when some of its own machines fail. Instances do not have to agree with each other. They only have to ask the coordination service, and it gives everyone the same answer.
How It Works#
Why a single leader#
A leader is a process that has been given exclusive responsibility for some job, for a period of time, while other processes stand by or do other work. Systems choose a single leader because it turns hard distributed problems into easy local ones:
- Ordering becomes trivial. If one process decides the order of all writes to a shard, there are no conflicting concurrent writes to resolve. This is why primary-replica databases and Raft send all writes through a leader.
- Decisions are made once. A scheduler that fires each job exactly once, a controller that assigns partitions to workers, or a garbage collector that deletes expired data must not run twice in parallel, or work is duplicated or conflicting.
- Expensive state stays in one place. A leader can keep an in-memory view, such as which tasks are assigned where, without synchronising it with peers on every change.
- External side effects happen once. Sending emails, charging cards, or calling a third-party API from several instances at once causes duplicates that cannot be undone.
The alternatives to a single leader are worth knowing, because a leader is a bottleneck and a failover risk:
- Partition the work: give each instance its own subset, such as job IDs hashed into buckets, so there is a leader per bucket, not one for everything. Kafka consumer groups do this with partitions.
- Make the work idempotent: if running the job twice is harmless, several instances can each try, and duplicates are absorbed. See Idempotency.
- Use optimistic concurrency: every instance may attempt the work, and a compare-and-set on the shared state lets exactly one succeed, for example "claim job 42 if its status is still pending".
- Use leaderless replication: Dynamo-style databases accept writes at any replica and resolve conflicts later. See Quorums and Leaderless Replication.
A single leader is the right choice when ordering or exclusivity matters and the leader's workload fits on one machine. When it does not fit, systems have many leaders, one per shard, each elected the same way.
Why a single leader, in depth#
What failure looks like. Three things can happen to a leader, and the system cannot tell them apart from the outside:
- It crashes. It stops sending heartbeats and does no more work. A replacement is needed quickly.
- It pauses. A long garbage collection pause, a VM being live-migrated, a process stopped with
SIGSTOP, or a disk that hangs for 30 seconds. It stops sending heartbeats, but when it resumes, it continues exactly where it left off, believing it is still leader, unaware that time has passed. - It is partitioned. It is alive and working, but cannot reach the coordination service or some peers. It may still reach the database and some clients.
A safe election must handle all three. Detecting the problem and electing a replacement handles case 1. Cases 2 and 3 are the dangerous ones: the old leader is still active, and if nothing stops it, there are two leaders. The rest of this page is about the two mechanisms that stop it: leases, which make the old leader stop on its own when it can no longer prove its leadership, and fencing, which makes the rest of the system reject the old leader if it does not stop in time.
Leadership is a time-bounded claim, not a fact. No process can ever know, at the moment it acts, that it is still leader, because the coordination service could have elected a replacement in the microseconds since it last checked. Leadership is therefore always a claim of the form "I was leader at time T, with token N, and believe I still am until time T plus the lease". Correct systems are designed so that this claim being wrong costs at most a rejected request, never corrupted data.
Leadership granularity. A system can have:
- One leader for the whole system: simple, but the leader's capacity is the system's capacity, and a failover affects everything. Fine for a scheduler or a cluster controller.
- One leader per shard or partition: each shard of a database, each Kafka partition, each range in CockroachDB has its own leader, spread over many machines. Failover affects one shard, and load is spread.
- One leader per task: for example, a lock per job, held while the job runs. This is really a distributed lock, covered in Distributed Locks.
Avoiding leadership where possible. A useful design habit is to ask: "What breaks if two instances do this at once?". If the answer is "nothing, as long as each request is idempotent", skip leader election. If it is "an occasional duplicate email", a best-effort lease without fencing may be acceptable. If it is "two primaries accept conflicting writes", you need a consensus-backed election and fencing.
Election via a consensus store#
The safe way to elect a leader is to let a consensus-backed store decide. The store is itself replicated, with Raft in etcd and Consul, or ZAB in ZooKeeper, so it gives every client the same linearizable answer, and survives the loss of a minority of its own servers. See Consensus. The candidates do not need to agree among themselves. They each perform one atomic operation on the store, and the store guarantees exactly one succeeds.
The basic pattern is the same in every store:
- Create a session or lease with a time-to-live, for example 10 seconds, and keep it alive with periodic renewals, say every 3 seconds.
- Try to claim the leadership key atomically, attached to that lease: "create
/services/scheduler/leaderwith my ID, only if it does not exist". Exactly one candidate succeeds. - The winner acts as leader while its lease is alive. It reads the claim's revision or version number and uses it as a fencing token.
- Losers watch the key, so the store notifies them when it is deleted, instead of polling.
- If the leader crashes or is partitioned, its renewals stop, the lease expires, the store deletes the key, and the watchers are notified. They race again, and one wins.
- A leader that shuts down cleanly deletes the key or revokes its lease, so handover takes milliseconds instead of a full lease period.
How each system expresses it.
- etcd: a lease, plus a transaction that compares the key's create revision to 0 (meaning it does not exist) and puts it with the lease attached. etcd's
concurrencypackage wraps this as anElectionobject withCampaign,Resign,LeaderandObservemethods. Each candidate writes its own key under a common prefix, and the one with the lowest create revision is leader, with each waiting candidate watching the key just before its own. That is the same idea as ZooKeeper's recipe, and it gives a queue of successors instead of a thundering herd. - ZooKeeper: each candidate creates an ephemeral sequential znode under
/election, the lowest sequence number is leader, and each other candidate watches its immediate predecessor. Ephemeral znodes vanish when the creator's session ends. Apache Curator'sLeaderLatchandLeaderSelectorimplement the recipe correctly, including the edge cases. - Consul: create a session with a TTL or tied to the node's health checks, then do a key-value
PUTwith?acquire=<session>. Only one session can hold the key's lock at a time. If the session is invalidated, because the TTL lapses, the node fails its health checks or the session is destroyed, the lock is released.consul lockwraps this for scripts. - Kubernetes: a
Leaseobject in thecoordination.k8s.ioAPI group, holding the holder's identity, lease duration and renew time. Candidates update it with optimistic concurrency, using the object'sresourceVersion, so only one update wins. client-go'sleaderelectionpackage, used by kube-controller-manager and kube-scheduler, defaults to a 15 second lease duration, a 10 second renew deadline and a 2 second retry period. Because the API server stores the object in etcd, the update is linearizable. - A strongly consistent database: a row with
leader_id,lease_expires_atandepoch, claimed with a conditional update such as "update where epoch equals the value I read, or the lease has expired". DynamoDB conditional writes or a PostgreSQL row work. This avoids running a coordination cluster at all, if you already have such a database.
Election via a consensus store, in depth#
Classic algorithms, and why they are not enough. Textbooks describe election algorithms that run among the candidates themselves:
- The Bully algorithm (Hector Garcia-Molina, "Elections in a Distributed Computing System", IEEE Transactions on Computers, 1982): a process that suspects the leader has failed sends an election message to every process with a higher ID. If none answers, it declares itself leader. If one answers, that process takes over the election. The highest-ID live process wins.
- Ring algorithms (such as Chang and Roberts, 1979): processes are arranged in a logical ring, and an election message travels around it collecting IDs, so the highest ID is chosen after one full circuit.
Both assume reliable failure detection. During a partition, each side sees the other as failed, and each elects its own leader, because neither requires a majority. They are useful for understanding the problem, and are fine inside systems where the network is reliable or split brain is harmless, but they do not prevent two leaders. Raft's election is essentially a bully-like race made safe with terms and majorities.
Why the store's linearizability matters. The compare-and-create must be linearizable, meaning that once one candidate's create succeeds, every later read and create, by anyone, sees it. A store with eventually consistent reads would let two candidates each read "no leader" from different replicas and each create one. Redis with asynchronous replication has exactly this weakness: a leader key written to the primary can be lost if the primary fails before replicating it, and the promoted replica lets a second candidate claim leadership. That is fine for an efficiency lock, but not for correctness, as discussed in Distributed Locks.
Choosing what to watch. If every waiting candidate watches the single leader key, then when it is deleted, all of them wake up and send create requests at once, a herd effect. With 5 candidates this is harmless. With 5,000 workers each competing for leadership of their own shard, it is a burst of load on the coordination service exactly when it may be recovering. Watching only the predecessor, in a queue of sequential keys, means each deletion wakes exactly one waiter.
Observers of leadership. Clients that need to know who the leader is, such as a router that sends writes to the current primary, can read the leader key and watch it. etcd's Observe and Curator's LeaderLatch listeners support this. The value can include the leader's address, so service discovery and leader discovery become the same operation.
Handover and priorities. Sometimes a particular instance should be preferred as leader, for example one in the same zone as the database. Common techniques: a candidate that is not preferred waits briefly before campaigning, or a leader that sees a preferred candidate voluntarily resigns. Both should be rare and rate-limited, since every handover is a brief period without a leader.
Leases#
A lease is a grant of a right, such as leadership or a lock, that is valid only for a limited time, and that the holder must renew to keep. Cary Gray and David Cheriton introduced the term in "Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency" (SOSP 1989), for caching files consistently: a server promises to notify a client of changes for the lease period, and if the client becomes unreachable, the server only has to wait for the lease to expire before allowing writes. Leases solve a problem that locks without timeouts cannot: if the holder dies, the right comes back automatically.
How a lease is used for leadership:
- The leader holds a lease with a duration, the TTL, for example 10 seconds.
- It renews well before expiry, typically every one third of the TTL, so a single lost renewal does not cost it the lease.
- The coordination service expires the lease if renewals stop, and only then lets another candidate become leader.
- The leader must stop acting as leader before the lease could have expired, from the coordination service's point of view. If it cannot renew, it must step down on its own, even though nobody has told it to.
The last point is the subtle one. The service and the leader measure time separately. The leader should count its lease from the moment it sent the request that granted or renewed it, not from when it received the reply, since the service may have started the clock earlier. And it should subtract a safety margin for clock rate differences.
A worked example. The lease TTL is 10 seconds, renewals are sent every 3 seconds, and the leader assumes its clock may run up to 1% slower than the service's, plus a fixed 500 ms margin.
- The leader sends a renewal at local time t = 30.0 s, and the reply arrives at t = 30.4 s.
- From the service's point of view, the lease runs until at least 10 seconds after it processed the request, which was after 30.0 s by the leader's clock.
- The leader treats its lease as valid until 30.0 + 10 × 0.99 − 0.5 = 39.4 s, local monotonic time.
- If renewals at 33 s and 36 s both fail, the leader stops all leader work at 39.4 s, and the service expires the lease no earlier than 40.0 s, as seen by the service.
- The safety gap, 0.6 s here, covers small drift and scheduling delays. It does not cover a pause: if the leader is frozen from 35 s to 45 s, it wakes up after its lease has expired, and a check of "is my lease still valid?" made just before the pause, at 34.9 s, said yes. That is why leases need fencing.
Choosing the TTL. The TTL is a trade-off between failover time and false failovers:
| TTL | Failover after a crash | Risk |
|---|---|---|
| 1 to 2 s | Fast | GC pauses, network blips and slow disks on the coordination service cause needless leader changes |
| 10 to 15 s | Typical | Up to 15 s with no leader after a crash |
| 30 to 60 s | Slow | Long outages, but very stable leadership; suits leaders whose failover is expensive |
Graceful shutdowns should release the lease explicitly, so planned restarts and deployments cause handovers in milliseconds, and only real crashes pay the full TTL.
Leases, in depth#
Leases assume bounded clock drift, not synchronised clocks. A lease compares durations, not timestamps: the service measures 10 seconds since the last renewal, and the holder measures slightly less since it sent the renewal. That requires only that both clocks advance at roughly the same rate, and that durations are measured with a monotonic clock, which never jumps when NTP adjusts the time. Quartz oscillators in servers typically drift by tens of parts per million, about a few milliseconds per minute, well within typical margins. Using wall-clock time for lease checks is a classic bug: an NTP step of a few seconds can make a lease look expired too early, causing needless failover, or valid too long, causing two leaders. See Time and Ordering.
Process pauses break the assumption. The holder's code typically looks like "check the lease is valid, then do the work". Between the check and the work, the process can pause for an arbitrary time. Martin Kleppmann's 2016 analysis "How to do distributed locking" gave the canonical example: a client acquires a lock with a lease, then pauses in a long garbage collection, the lease expires, a second client acquires the lock and writes, and the first client then wakes and writes too, corrupting the data. Shortening the TTL makes it less likely, but no TTL rules it out, because pauses are unbounded. Only fencing, checked at the resource, makes it safe.
Leases in consensus itself. Leases also appear inside consensus systems, to make reads fast. A Raft or Paxos leader that holds a leader lease knows no other leader can be elected until it expires, so it can serve linearizable reads from local state without contacting a majority. Spanner's Paxos leaders hold 10-second leases, and CockroachDB's range leaseholders serve reads locally. These rely on bounded clock drift, with each system configuring a maximum allowed offset and refusing to operate if clocks drift beyond it. etcd's default read path avoids this dependency by using read index instead, a round of heartbeats, at the cost of one round trip.
What the coordination service promises during its own failover. If the etcd or ZooKeeper leader fails, the coordination service briefly cannot process renewals. A naive design would expire every lease, causing every client application to lose leadership at once. Both systems avoid this: etcd's new leader extends the remaining TTL of existing leases on election, so that clients have time to renew, and ZooKeeper's new leader does not expire sessions until clients have had a session timeout to reconnect. Applications should still treat "cannot reach the coordination service" as "may have lost leadership" once their own lease deadline passes.
Leases versus heartbeats. A heartbeat tells others "I am alive". A lease is a promise from the coordination service: "nobody else will be given this until this time". The difference matters: heartbeats let others suspect failure, while a lease guarantees that the holder has had time to notice and stop before anybody else starts, as long as clocks behave and the holder checks its deadline.
Fencing tokens#
A fencing token is a number, issued with each grant of leadership or a lock, that increases every time it is granted to someone new. The leader attaches its token to every request it sends to a shared resource, such as a database, a storage service or another service. The resource remembers the highest token it has seen, and rejects any request with a lower one. The term comes from the idea of fencing off a failed node so it cannot touch shared data.
This turns the problem around. Instead of trying to guarantee that an old leader always stops in time, which is impossible, the system guarantees that if it does not stop, its actions are refused.
Where tokens come from.
- etcd: the revision of the leader key's creation (its create revision) or the lease ID. Revisions increase across the whole store, so a newer leader always has a higher one.
- ZooKeeper: the sequence number of the leader's ephemeral sequential znode, or the zxid of its creation, both of which increase.
- Raft and ZAB: the term or epoch number, which is exactly a fencing token for the consensus group's own leader.
- A database row: an
epochcolumn incremented on each takeover, inside the same conditional update that claims leadership. - Kafka: the controller epoch and per-partition leader epoch, which brokers and clients use to reject requests from stale leaders.
How the resource checks them. The check must be atomic with the write itself. In a relational database, the write is conditional:
-- Apply the write only if no newer leader has written
UPDATE shard_owner
SET epoch = :my_token, last_write_at = now()
WHERE shard_id = 7 AND epoch <= :my_token;
-- 0 rows updated means a newer leader exists: abort and step down
-- Or guard data writes with the token stored alongside them
UPDATE orders
SET status = 'shipped', writer_epoch = :my_token
WHERE id = :order_id AND writer_epoch <= :my_token;Object stores and key-value stores can use conditional writes with a version or an If-Match precondition in the same way. Where the resource cannot check tokens at all, such as an external email provider or a third-party payment API, fencing is not possible, and correctness must come from idempotency keys instead, so that a duplicate request has no extra effect.
Fencing tokens, in depth#
Fencing is what makes leases safe. Consider each failure case from earlier:
- Crash: the lease expires and a new leader takes over. Fencing is not needed, but harmless.
- Pause: the old leader wakes up after its lease expired. Its next request carries an old token and is rejected. This is the case leases alone cannot handle.
- Partition: the old leader cannot renew, so it should step down at its lease deadline. If it is buggy and keeps going, any resource that the new leader has written to rejects it.
There is a remaining window: a resource that the new leader has not yet written to has not seen the new token, so it may accept a request from the old leader. Two mitigations: the new leader can "announce" its token to the resources it controls when it takes over, such as writing its epoch to each shard's metadata row first, and resources can also check, on each request, a token stored in a shared place.
Why random lock values are not tokens. Some lock implementations, such as the common Redis SET key value NX PX ttl pattern, use a random value to identify the holder, so that a client only deletes its own lock. That prevents a client from releasing someone else's lock, but it cannot fence, because random values are not ordered: storage cannot tell whether a request's value is newer or older than the last one it saw. A fencing token must be monotonically increasing, which in practice means it must be issued by a linearizable source.
Fencing in hardware and clusters. Classic high-availability clusters with shared disks fence at the storage or power level. SCSI persistent reservations let a node register a key with a shared disk and lock out other keys, so the surviving node revokes the failed node's registration before taking over. STONITH, "shoot the other node in the head", powers off or reboots the failed node through a power controller or a cloud API. These are the same idea as fencing tokens, applied where the resource is a disk or a whole machine. See Failure Detection and Gossip.
HDFS NameNode failover is a worked case. HDFS high availability runs an active and a standby NameNode. ZooKeeper elects the active one through ZKFC, the ZooKeeper Failover Controller, which holds an ephemeral lock znode. The edit log is written to a quorum journal manager, a group of JournalNodes that accept edits only from the writer with the highest epoch. A new active NameNode obtains a higher epoch from a majority of JournalNodes before writing, so an old active NameNode that resumes is refused by the journal, even before any administrator-configured fencing script runs. The design has three layers: ZooKeeper chooses the leader, epochs at the journal fence the data, and optional scripts fence the machine.
ZooKeeper and etcd primitives#
Coordination services do not offer "leader election" or "locks" directly as their core API. They offer a few small primitives from which those recipes are built.
ZooKeeper's data model. ZooKeeper stores a tree of znodes, addressed by paths like /app/config/max_size, much like a file system in which every node can hold data and have children. Each znode holds a small amount of data, limited to 1 MB by default and usually far less, plus metadata (the stat): a data version incremented on every change, a child version, the zxids of its creation and last modification, and the owner session if it is ephemeral. Znode types:
- Persistent: stays until deleted. Used for configuration and metadata.
- Ephemeral: deleted automatically when the session that created it ends. It cannot have children. Used for liveness: "this instance is alive", "this instance holds leadership".
- Sequential: either persistent or ephemeral, with a 10-digit, monotonically increasing counter appended to the name by the server, for example
lock-0000000042. Used for queues, fair locks and elections. - Container and TTL znodes, added in ZooKeeper 3.5: container znodes are deleted automatically once their last child is removed, which keeps lock and election parent paths tidy, and TTL znodes are persistent znodes deleted if not modified within a time limit, when enabled.
Sessions. A ZooKeeper client connects to one server in the ensemble and establishes a session with a timeout, typically a few seconds to tens of seconds. The client sends heartbeats, and if the ensemble hears nothing from it for the session timeout, the session expires: its ephemeral znodes are deleted and its watches are removed. If the client's connection to one server breaks, it can reconnect to another server within the timeout and keep the same session. A client that sees a disconnection does not yet know whether its session has expired. It must assume the worst for safety-critical roles, such as leadership, after its own timeout.
Watches. A client can set a watch when reading a znode's data, checking whether it exists, or listing its children. When the watched data changes, the server sends a one-time notification. Classic ZooKeeper watches are one-shot: after firing, the client must read again and set a new watch, and changes between the notification and the re-read are seen only through the re-read, not as separate events. So watches tell a client "something changed, look again", not a full history. ZooKeeper 3.6 added persistent and recursive watches, which stay registered and can cover a whole subtree.
etcd's data model. etcd is a flat, ordered key-value store, with conventions such as /registry/pods/default/web-1 to imitate a hierarchy, and range queries over prefixes. It is built on MVCC: every change creates a new revision of the whole store, a single 64-bit counter, and each key records its create revision, its modification revision, and its version, the number of changes since creation. Old revisions are kept until compaction. Primitives:
- Leases: a lease has an ID and a TTL. Keys can be attached to a lease, and are all deleted when it expires or is revoked. Clients keep leases alive with a streaming keep-alive. One lease can cover many keys, which is cheaper than one session per key.
- Watches: a client watches a key or a prefix from a given revision, and receives every change since that revision, in order, over a long-lived gRPC stream. Because history is kept, a client that disconnects can resume from the last revision it processed without missing events, as long as that revision has not been compacted.
- Transactions:
if (compare conditions) then (operations) else (operations), atomic and linearizable. Comparisons can check a key's value, version, create revision or modification revision. This is the compare-and-set that elections and locks are built on.
Both offer linearizable writes. Every write goes through the consensus leader and is ordered with all others. Reads differ:
- ZooKeeper serves reads from the server the client is connected to, which may lag the leader slightly. Each client sees its own writes in order, and reads never go backwards for one session, but a client can read a value older than one another client has just written. A client that needs the latest value calls
syncfirst, which makes its server catch up with the leader. - etcd serves linearizable reads by default, using read index through the leader, and offers serializable reads as an option, answered by any member from local state, faster but possibly stale.
ZooKeeper and etcd primitives, in depth#
How ZooKeeper handles a write. A client sends a write, such as creating a znode, to its server. If that server is a follower or observer, it forwards the request to the leader. The leader turns it into an idempotent transaction: instead of "increment the version", it records the resulting version and state, so applying it twice is harmless. The leader assigns the next zxid, sends a proposal to the followers, and once a quorum has logged it to disk, sends a commit. Each server applies committed transactions in zxid order to its in-memory data tree, and the client's server replies. Reads, served locally from memory, take microseconds, which is why ZooKeeper suits read-heavy workloads: the original paper (Hunt, Konar, Junqueira and Reed, "ZooKeeper: Wait-free Coordination for Internet-scale Systems", USENIX ATC 2010) reported throughput in the order of tens of thousands to hundreds of thousands of operations per second for read-dominated workloads, with write throughput much lower and falling as the ensemble grows, because every write involves more servers.
ZooKeeper's guarantees, precisely.
- Linearizable writes: all writes are totally ordered by zxid.
- FIFO client order: all requests from one client are executed in the order the client sent them.
- Single system image: a client never sees an older view after reconnecting to a different server, because the client tracks the last zxid it has seen and a server that is further behind refuses the connection until it catches up.
- Durability: once a write is acknowledged, it survives as long as a quorum survives.
- Timeliness: a client's view is up to date within a bounded time, though not instantly.
These were deliberately chosen to be "wait-free": ZooKeeper does not offer blocking primitives such as locks directly, so a slow or failed client never blocks others inside the service. Locks and barriers are recipes built on top by clients.
Storage. ZooKeeper keeps the whole data tree in memory, writes every transaction to an append-only transaction log on disk, which should be on a dedicated device for low fsync latency, and periodically writes fuzzy snapshots of the tree while it keeps running. A snapshot taken while transactions are applied may not correspond to any single point in time, but because transactions are idempotent, replaying the log from before the snapshot's start produces the correct state. etcd stores its key-value data in bbolt, a B+tree file, with a separate Raft write-ahead log, and both systems are limited by how much data fits comfortably in memory and in a snapshot, typically a few gigabytes.
Handling failures. If a follower fails, the ensemble continues as long as a quorum remains, and the follower's clients reconnect to other servers and keep their sessions. If the leader fails, followers elect a new leader using ZooKeeper's fast leader election, preferring the server with the highest zxid, and the new leader synchronises the others before serving writes. Writes pause for the duration, usually under a few seconds. Reads continue from servers that are still up. If a quorum is lost, the ensemble stops accepting writes, by design, and servers in a minority partition stop serving clients.
Practical limits. Both systems are designed for small data that changes slowly:
- ZooKeeper's 1 MB znode limit, and etcd's 1.5 MiB default request size limit, exist because every write is replicated to every member and stored in memory.
- etcd's default backend quota is 2 GB, with about 8 GB the suggested maximum.
- Large numbers of watchers on one hot znode can overload the server when it changes, since each one is notified and typically re-reads.
- Write throughput is that of one consensus group, thousands to tens of thousands per second, not millions.
Smart routing with a coordination service. Back to the chat application. A natural design stores, for each connected user, which server holds their connection, so that any server can route a message to the right place. With 10 million connected users and frequent reconnects, putting each user's location into ZooKeeper would overwhelm it. A better design stores, in ZooKeeper or etcd, only the server membership and a mapping of shards to servers, for example, user IDs hashed into 1,024 shards with each shard assigned to one server. Each server watches the mapping and keeps it in memory, and routing becomes a local lookup: hash the recipient's ID, look up the shard's server, and forward. When a server dies, its ephemeral registration vanishes, a controller reassigns its shards, and every server sees the new mapping through its watch within milliseconds. Per-user state, if needed, lives in a fast store such as Redis. This shape, a small, consistent map in the coordination service and the bulk data elsewhere, is the right way to use these systems. Apache Helix, built at LinkedIn on ZooKeeper, generalises it into a cluster manager that assigns partitions to nodes using state models such as master-slave and leader-standby.
Service registry and config#
Service discovery is how a client finds the network addresses of healthy instances of a service. Instances come and go constantly with autoscaling, deployments and failures, so the list cannot be hard-coded. A service registry holds the current list.
Registering with a coordination service. Each instance, on start-up, registers itself:
- In ZooKeeper, it creates an ephemeral znode such as
/services/payments/instance-0000000017containing its host, port and metadata. If it crashes, its session expires and the znode disappears. - In etcd, it puts a key such as
/services/payments/10.0.3.7:8080attached to a lease it keeps alive. If keep-alives stop, the lease expires and the key is deleted. - In Consul, the local agent registers the service with health checks. The servers store the catalog in Raft, and gossip plus the agent's checks keep health current.
Clients, or the load balancers and proxies in front of them, list the instances and set a watch, so they learn about additions and removals within milliseconds to seconds, and keep the list in a local cache. If the registry is briefly unreachable, clients keep using their cached list, which is almost always better than failing.
Two ways to use the registry:
- Client-side discovery: each client reads the registry and picks an instance itself, with its own load balancing. Netflix's Eureka with the Ribbon client library worked this way. It avoids an extra hop, but every client needs the library.
- Server-side discovery: clients call a stable address, such as a load balancer, a Kubernetes Service virtual IP, or a service-mesh sidecar, which reads the registry and forwards the request. Clients stay simple. See Load Balancing and Microservices Infrastructure Patterns.
Health matters more than presence. An ephemeral registration proves the instance's process is connected to the registry, not that it can serve requests. A process whose thread pool is stuck still renews its session. Registries therefore combine registration with health checks: Consul runs HTTP, TCP or script checks, Kubernetes removes pods failing readiness probes from a Service's endpoints, and load balancers run their own checks. Clients should also eject instances that keep failing, using passive outlier detection.
Configuration management. A coordination service is also a good home for dynamic configuration: settings that change at runtime without a deploy, such as feature flags, rate limits, timeouts and routing weights.
- Store each setting, or each service's configuration document, under a key.
- Each instance reads it at start-up and watches it.
- A change is a single write, and every watcher sees it within milliseconds to seconds, in the same order everywhere.
- Versioning comes for free: ZooKeeper's data version and etcd's revisions let tools implement compare-and-set updates ("change the limit only if nobody else changed it since I read it"), history, and rollback.
Configuration systems built this way include Kubernetes ConfigMaps (stored in etcd), Consul KV with consul-template or Consul's watch mechanism, Spring Cloud with ZooKeeper or Consul backends, and Apache Kafka, Hadoop and HBase, which historically used ZooKeeper for cluster configuration.
Service registry and config, in depth#
Consistency versus availability in registries. A registry built on consensus, such as ZooKeeper, etcd or Consul's servers, chooses consistency: if it loses quorum, it stops accepting registrations. Netflix took the opposite view with Eureka, an AP registry whose servers replicate to each other asynchronously and keep serving possibly stale data during partitions. Eureka also has a self-preservation mode: if many instances stop renewing at once, which is more likely to be a network problem than mass failure, it stops expiring registrations. The argument, widely made in the mid-2010s debate about ZooKeeper for discovery, is that for discovery, a slightly stale list is far better than no list, because clients retry against another instance anyway. That is a sound argument for discovery, but not for leadership, where a stale answer means two leaders. Many organisations therefore use different tools for the two: an AP or cached discovery layer, and a CP store for elections and locks.
DNS as a registry. DNS is the oldest service registry. Consul and Kubernetes both expose instances through DNS, such as payments.service.consul or payments.default.svc.cluster.local. DNS is universal, but caching in resolvers and clients, governed by TTLs and sometimes ignored, makes it slow to reflect changes, and it returns addresses without health or load information. It suits coarse discovery, while watches or sidecars suit fast-changing instance lists.
Scaling the registry. With 10,000 instances each holding a session and renewing every few seconds, the coordination service handles thousands of renewals per second, plus notifications to every watcher on every change. Techniques that keep it healthy:
- Aggregate registrations through a local agent per machine, as Consul does, so each machine holds one session rather than one per process.
- Batch and debounce notifications at clients, so a deployment that replaces 500 instances triggers a few list refreshes, not 500 per client.
- Use a caching tier: Kubernetes clients watch the API server, which watches etcd once and fans out events from its watch cache to thousands of clients.
- Shard by service or by data centre, with one registry per data centre and federation between them, as Consul does with a WAN gossip pool and per-data-centre Raft clusters.
Safe configuration rollout. A configuration change reaching every instance within a second is also a risk: a bad value reaches everything within a second too. Large outages have been caused by global configuration pushes. Practices that limit the blast radius:
- Validate configuration with schemas and tests before it is written.
- Stage rollouts: write the new value under a version, and have instances adopt it zone by zone, or for a percentage of instances, watching error rates, instead of all at once.
- Keep the previous version and make rollback a single write.
- Fail static: if an instance cannot read the configuration, or reads an invalid value, it keeps the last known good configuration instead of crashing or falling back to defaults.
The notification and scheduling use case. A notification service that accepts scheduled notifications ("send this at 9:00 tomorrow") needs something to scan for due notifications and enqueue them. If every instance scans, each due notification is enqueued many times. Three options, in order of preference: partition the schedule into buckets, with each bucket owned by one instance through leases, so that scanning scales out; elect one scanning leader per data centre, with fencing on the "mark enqueued" write; or let every instance scan but claim each notification with a conditional update from pending to enqueued, so exactly one claim succeeds. The last two use coordination only for ownership, while the delivery pipeline itself stays leaderless and at-least-once, with deduplication downstream. See Design a Job Scheduler and Design a Notification System.
The metrics ingestion use case. A metrics platform that scrapes thousands of services needs to know which targets exist, and which scraper is responsible for each. Prometheus discovers targets from Kubernetes, Consul, DNS or cloud APIs, all forms of service registry. When several scrapers share the work, targets are divided among them by consistent hashing of target labels, or assigned by a coordinator, so each target is scraped once. A scraper that dies has its targets reassigned when the membership changes. Running two scrapers for every target, and deduplicating at query time, is a common alternative when duplicate samples are cheaper than missed ones. See Design a Metrics and Monitoring System.
Preventing split brain#
Split brain happens when two parts of a system each believe they hold a role that only one should hold, typically after a partition or a pause, and both act on it. The defences come in layers, and robust systems use several:
- Majority quorums for the decision. The leader is chosen by a consensus system that needs a majority, so two leaders cannot be elected in the same term or epoch, and a minority partition cannot elect anyone. This rules out "each side elects its own".
- Leases that the leader respects. The leader steps down by itself when it cannot renew before its lease deadline, measured on a monotonic clock with margins. This makes the overlap rare.
- Fencing at every shared resource. Storage rejects writes carrying an older token or epoch. This makes the overlap harmless when it does happen.
- Physical fencing where resources cannot check tokens. STONITH or revoking the old node's access to a shared disk or network before takeover.
- Idempotency for external effects. Where nothing can be fenced, such as an email or a payment provider, operations carry idempotency keys so a duplicate does nothing.
Two-node clusters need a third vote. With two nodes, neither can form a majority on its own after a partition. The choices are all imperfect: stop both (safe but unavailable), let both continue (available but split brain), or add a third voter. The third voter can be small: a witness or arbiter that votes but holds no data, such as a MongoDB arbiter, a cloud quorum device for Windows failover clusters, or a third etcd member in another zone.
Preventing split brain, in depth#
A taxonomy of real split-brain causes.
- Leader elected without quorum: a two-node pair or a "highest ID alive wins" scheme splits during a partition. Fix: majority voting with a third voter.
- Leader keeps acting after losing its lease: a GC pause, VM freeze or slow disk. Fix: lease deadlines on monotonic clocks, plus fencing.
- Asynchronous replication plus failover: the old primary acknowledged writes the new primary never received. When the old one returns, its unreplicated writes conflict. Fix: synchronous or semi-synchronous replication to a quorum for writes that must not be lost, or accept and reconcile the loss explicitly.
- Clients caching the old leader's address: a client keeps sending writes to the old primary, which, if it is not fenced, accepts them. Fix: the old primary must refuse writes once it loses its lease, and clients should rediscover the leader on errors.
- Coordination service misused: using eventually consistent reads, or a store with asynchronous replication, for leader election. Fix: linearizable compare-and-set on a consensus store.
- Cross-region failover on short timeouts: a brief link outage promotes a remote primary while the local one keeps serving. Fix: longer timeouts or human approval for cross-region failover, and quorums spanning three regions.
Redis Sentinel and Redis Cluster illustrate the trade-offs. Sentinel requires a configured quorum of Sentinels to agree a primary is down, and a majority of Sentinels to authorise the failover, with each failover getting an increasing configuration epoch. But Redis replication is asynchronous, so a partitioned old primary can keep accepting writes from clients on its side. The min-replicas-to-write setting makes a primary stop accepting writes when it cannot reach enough replicas, limiting the window in which writes can be lost. Redis Cluster similarly needs a majority of primaries to agree a node has failed. This is "mostly safe" leadership, adequate for caches and many applications, but not a substitute for consensus where every acknowledged write matters.
MongoDB replica sets use a Raft-like protocol with terms. A primary that cannot see a majority steps down to secondary, and writes with w: "majority" are acknowledged only once a majority has them, so they survive failover. Writes acknowledged with w: 1 on an old primary that are not replicated before it steps down are rolled back when it rejoins, and written to rollback files for manual inspection. The design choice is explicit: the client chooses, per write, between speed and survival across failover.
Kafka's controller and leader epochs. Kafka brokers fence stale controllers with the controller epoch: any request from a controller with an older epoch is ignored. Partition leaders carry a leader epoch, which followers use when truncating their logs after a leader change, to find exactly where the new leader's history diverges from theirs. KIP-101 introduced this in 2017 after it was shown that truncating by the high watermark alone could lose or diverge data in some failure sequences. Producers have their own epoch for transactions, so a "zombie" producer instance that was replaced is fenced off when it tries to write.
Testing for split brain. Split brain does not show up in normal testing, because it needs a specific combination of partition, pause and timing. Tools and methods that find it:
- Jepsen tests, by Kyle Kingsbury, which partition, pause and kill nodes while running operations, and then check the history with a linearizability checker. Many published Jepsen analyses have found lost or duplicated acknowledged writes in systems that claimed strong guarantees.
- Fault injection in staging:
tc netemfor latency and packet loss, iptables rules for partitions,SIGSTOPandSIGCONTfor pauses, and clock skew with tools such as libfaketime. - Chaos engineering in production with guardrails, following Netflix's Chaos Monkey tradition.
- Assertions in production: log the leader's epoch with every leader action, and alert if two different epochs act within a short window.
When to Use It#
- Exactly-once roles: schedulers, cron runners, cluster controllers, compaction or cleanup jobs, and anything that must not run in parallel.
- Primary selection for a database, a shard, or a stateful service with one writer.
- Partition or shard ownership: assigning work units to instances so each unit has one owner, with automatic reassignment on failure.
- Service registries where you need instances to appear and disappear automatically and clients to learn quickly.
- Dynamic configuration and feature flags that must reach every instance quickly and consistently, with versioning.
- Cluster membership and metadata for infrastructure: broker lists, partition maps, schema versions.
- Durable distributed locks that protect correctness, combined with fencing tokens.
When NOT to Use It#
- When the work can be partitioned or made idempotent. Prefer no leader to a leader.
- For high-volume data: messages, user records, per-request state, per-user locations. Coordination services hold kilobytes to a few gigabytes, not terabytes, and thousands of writes per second, not millions.
- As a message queue: ZooKeeper queues built from sequential znodes work for small, low-rate cases, but a real queue or log does it far better.
- For locks that only improve efficiency: if a duplicate run only wastes some work, a Redis lock or a database row lock is simpler and cheaper.
- With per-request reads of the coordination service on a hot path: cache locally and watch for changes.
- When the platform already gives it to you: Kubernetes Leases, a managed database's conditional writes, or a cloud provider's managed coordination. Running your own ZooKeeper ensemble just for one leader is rarely worth it.
- When you cannot fence and cannot make effects idempotent: leadership alone cannot guarantee exactly-once side effects, so design for duplicates first.
How to Implement It#
- Ask whether a leader is needed. Try partitioning, idempotency or compare-and-set claims first.
- Pick the store: Kubernetes Lease objects if you run on Kubernetes, etcd or Consul for cloud-native systems, ZooKeeper with Apache Curator in JVM and Apache ecosystems, or a strongly consistent database row with conditional updates if you already have one.
- Use a maintained recipe: etcd's
concurrency.Election, Curator'sLeaderLatchorLeaderSelector, Consul's session-based locks, or client-go'sleaderelection. Do not reimplement the edge cases. - Set the lease TTL from failover requirements: typically 10 to 15 seconds, renewing every one third of the TTL, with the leader stepping down at its own deadline, measured on a monotonic clock, with a margin.
- Obtain a fencing token with every grant, and pass it on every write to shared resources, which must reject older tokens atomically.
- Stop all leader work on loss: when the lease cannot be renewed, the session is disconnected for too long, or the store reports a newer leader, cancel in-flight work and step down immediately. Restarting the process is a simple, robust way to guarantee this.
- Release on shutdown: resign or revoke the lease in shutdown hooks, so deploys hand over in milliseconds.
- Publish leadership: store the leader's address in the leader key, so others can find it.
- Monitor: leader changes per hour, time without a leader, lease renewal latency, and the coordination service's own health.
- Test: kill, pause and partition the leader, and verify that no two epochs ever act at once and that failover time meets the target.
Here is a database-backed election with an epoch as fencing token, for a system that already runs PostgreSQL and does not want a separate coordination service. The database's row locking makes the claim atomic.
-- One row per role; the epoch is the fencing token
CREATE TABLE leadership (
role text PRIMARY KEY,
holder text NOT NULL,
epoch bigint NOT NULL,
lease_until timestamptz NOT NULL
);
-- Claim or renew: succeeds if I already hold it, or the lease has expired
UPDATE leadership
SET holder = :me,
epoch = CASE WHEN holder = :me THEN epoch ELSE epoch + 1 END,
lease_until = now() + interval '10 seconds'
WHERE role = 'scheduler'
AND (holder = :me OR lease_until < now())
RETURNING epoch;
-- No row returned: someone else holds a valid lease, so stay a follower.
-- Row returned: lead with this epoch until local monotonic deadline
-- (send time + 10 s minus margin); renew every ~3 s.The lease expiry is judged by the database's single clock, so instances' clock differences do not matter for the claim, only for each holder's own deadline. Every write the leader makes, to this database or others, should carry the epoch and be conditional on it.
| Technology | Fits when |
|---|---|
etcd (concurrency.Election, leases, watches) | Cloud-native systems and Kubernetes environments; strongly consistent small key-value data |
| Apache ZooKeeper with Apache Curator | JVM and Apache ecosystems (HBase, Hadoop, Solr, older Kafka); ephemeral and sequential znodes, mature recipes |
| Consul (sessions, KV, catalog, health checks) | Service discovery plus leader election and configuration, across many machines and data centres |
Kubernetes Lease objects with client-go leaderelection | Controllers and operators running inside Kubernetes |
| Strongly consistent database row (PostgreSQL, DynamoDB conditional writes, Spanner) | You already run one and need a few leader roles, without operating another cluster |
Redis SET NX PX locks | Efficiency-only exclusivity where an occasional duplicate is acceptable; not for correctness |
| Netflix Eureka | Availability-first service discovery for JVM services, accepting stale registrations |
| Apache Helix | Partition-to-node assignment with state models for stateful services, on ZooKeeper |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Consensus store election (etcd, ZooKeeper, Consul) | Linearizable; one leader per epoch; watches for fast handover | Another cluster to run; small data only; unavailable without quorum | Correctness-critical leaders and metadata |
| Database row with conditional update | No new infrastructure; transactional with your data | Load on the database; failover depends on its availability | A few roles in a system already built on a strong database |
| Kubernetes Lease | Built in; standard client library | Depends on the API server; only inside Kubernetes | Operators and controllers |
| Redis lock | Very fast and simple | Asynchronous replication can lose the lock on failover; random values cannot fence | Efficiency locks where duplicates are tolerable |
| Bully or ring election among peers | No external dependency | Split brain under partitions; relies on accurate failure detection | Teaching, or closed environments where split brain is harmless |
| Short lease TTL | Fast failover | More false failovers from pauses and blips | Leaders whose failover is cheap and frequent checks are acceptable |
| Long lease TTL | Stable leadership | Longer outages after crashes | Leaders whose handover is expensive, such as those that warm large caches |
| CP registry | Consistent instance list | Registrations stop without quorum | Small fleets, or where accuracy matters |
| AP registry (Eureka style) | Keeps serving during partitions | Stale entries; clients must retry | Large service fleets where availability of discovery is paramount |
Common Pitfalls#
- No fencing: trusting the lease alone, so a paused leader corrupts data after waking.
- Checking leadership once, then doing long work without re-checking the deadline or carrying a token.
- Wall-clock lease checks, broken by NTP steps.
- Leader keeps working after a session disconnect because the client library only reported "disconnected", not "expired".
- Herd effects: thousands of waiters all watching one key, waking at once.
- Putting bulk data in ZooKeeper or etcd, such as per-user locations or large blobs, until the cluster slows or hits its quota.
- Reading the coordination service on every request instead of caching and watching.
- Two-node coordination clusters, or all members in one zone.
- Global config pushes without staging, so one bad value breaks every instance within seconds.
- Assuming leadership gives exactly-once external effects, without idempotency keys.
Real-World Examples#
- Kubernetes runs kube-controller-manager and kube-scheduler with several replicas, and uses Lease objects so that only one replica of each is active, with a 15-second default lease.
- HDFS uses ZooKeeper, through the ZooKeeper Failover Controller, to elect the active NameNode, and fences the old one through epochs at the quorum journal.
- Apache HBase uses ZooKeeper to track the active HMaster and live RegionServers.
- Apache Kafka used ZooKeeper for controller election and metadata until KRaft replaced it, and fences stale controllers and leaders with epochs.
- Google built Chubby, a Paxos-based lock service, and its 2006 paper describes how GFS and Bigtable used it to elect masters and store small metadata, and how Chubby also served as a naming service.
- Netflix built Eureka as an availability-first registry for its service fleet.
- LinkedIn built Apache Helix on ZooKeeper to manage partition assignment for stateful systems.
- HashiCorp Vault and Nomad elect their active servers with Raft, and Consul offers session-based leader election to applications.
In the Interview#
Deep Dive: ZooKeeper in the modern worldShow
Where it came from. ZooKeeper was built at Yahoo and became an Apache project around 2008, with its design published at USENIX ATC 2010. It was inspired by Google's Chubby, but chose a different interface: instead of locks as a service, it offers wait-free primitives (znodes, ephemeral nodes, sequential nodes and watches) from which clients build locks, elections, barriers, queues and group membership. That choice made it general enough to become the coordination layer of the Hadoop ecosystem.
Where it is still used. HBase uses it to track the active master and the live RegionServers, Hadoop uses it for NameNode and ResourceManager high availability, Apache Solr's SolrCloud keeps cluster state in it, Apache Pulsar and Apache BookKeeper store metadata in it, and Apache Druid, Apache Storm and older Kafka deployments depend on it. Many companies also run it directly for service discovery and configuration.
Why it is being replaced in some systems.
- Operational burden: a separate cluster with its own tuning, upgrades, monitoring and security, for systems that would rather manage their own metadata.
- Scale limits: all data in memory on every server, single-leader writes, and metadata that grows with the system, such as Kafka's partition metadata, which made ZooKeeper a bottleneck for clusters with hundreds of thousands of partitions.
- Split-brain risks at the boundary: when a system keeps its own state and also mirrors it in ZooKeeper, the two can disagree. Kafka's move to KRaft, which puts the metadata log inside Kafka itself, removed that boundary, and Kafka 4.0 dropped ZooKeeper support entirely.
- Cloud-native alternatives: etcd became the default in the Kubernetes world, and managed databases with conditional writes cover many coordination needs.
Alternatives and how they compare.
| Option | Model | Strength | Weakness |
|---|---|---|---|
| ZooKeeper | Hierarchical znodes, sessions, one-shot (or persistent) watches, ZAB | Mature recipes through Curator; wide Apache adoption | JVM operations; reads can be stale without sync |
| etcd | Flat MVCC key space, leases, revision-based watches, Raft | Linearizable reads by default; watch history; Kubernetes standard | Small data limits; sensitive to disk latency |
| Consul | KV plus service catalog, sessions, health checks, gossip plus Raft | Discovery and health built in; multi-data-centre | More moving parts; KV is secondary to discovery |
| Embedded Raft (KRaft, hashicorp/raft) | Consensus inside your own system | No external dependency; metadata where it is used | You own the correctness and operations |
| Database row leases | Conditional updates on an existing strong database | No new system | Load and availability tied to the database |
Limitations to keep in mind. Data per znode is small, total data must fit in memory, write throughput falls as the ensemble grows, large watch fan-out can overload servers, and session expiry under long client pauses means applications must handle losing ephemeral nodes at any moment. A common failure story is an application that stores too much data in ZooKeeper, so snapshots grow, followers take long to sync after restarts, and the ensemble becomes unstable.
So when should you use ZooKeeper?
- Smart routing: a cluster whose servers must agree on which server owns which shard or connection group, such as the chat example, with the shard map in ZooKeeper and each server watching it.
- Infrastructure design problems: when you are designing something like a distributed message queue, a distributed cache, a key-value store or a job scheduler, ZooKeeper, or etcd, is the natural answer for broker membership, partition leadership, metadata and configuration. Interviewers often welcome it in these designs.
- Durable distributed locks: when a lock must survive the failure of any single server and must be correct, a ZooKeeper lock with sequential znodes, plus fencing with the znode's sequence number or zxid, is a standard choice. See Distributed Locks.
For a product-level design, such as a social feed or an e-commerce site, ZooKeeper is usually an implementation detail of the infrastructure you choose, not something you add yourself. See ZooKeeper and etcd.
Deep Dive: Designing leader election for a job schedulerShow
The setting. A job scheduler stores 2 million job definitions, of which about 5,000 fire per minute at peak. Jobs must not be skipped, and should run at most once per scheduled time, with downstream workers idempotent as a backstop. The service runs in three zones, and must recover from an instance crash within 30 seconds.
Option 1: one global leader. Three scheduler replicas elect a leader through etcd with a 10-second lease. The leader scans for due jobs every second and enqueues them to a durable queue, marking each job's next run time with a conditional update carrying the leader's epoch: update jobs set next_run = :next, enqueued_epoch = :epoch where id = :id and next_run = :due and enqueued_epoch <= :epoch. If a paused old leader wakes up and tries to enqueue the same job, the condition fails, because the next run time has already moved on, or the epoch is lower. Capacity: 5,000 jobs per minute is about 83 per second, easy for one leader. Failover: a crash costs up to 10 seconds of lease expiry, plus a second to start scanning, well within 30 seconds, and jobs due during the gap are enqueued late, not skipped, because the scan picks up everything with next_run <= now.
Option 2: partitioned leadership. If the load grew to 500,000 jobs per minute, one leader would struggle. Split the jobs into 256 buckets by hashing the job ID, and give each bucket its own lease, so each of, say, 16 scheduler instances leads about 16 buckets. Instances claim unowned buckets, renew their leases, and release buckets when the assignment rebalances. The fencing token is per bucket. This is the same pattern used for consumer groups, sharded controllers and Kafka partitions. Coordination load grows to 256 leases renewed every few seconds, about 100 renewals per second, still small for etcd.
Option 3: no leader. Every instance scans and claims due jobs with update ... where status = 'pending' and next_run <= now() returning id, using SELECT ... FOR UPDATE SKIP LOCKED in PostgreSQL to avoid contention. The database guarantees that exactly one claimer wins each job. This avoids a coordination service, at the cost of database load from repeated scans. It is a strong choice when the job store is already a relational database and the rate is moderate.
Decision. Start with Option 1 or 3, depending on whether the team already runs etcd or a strong database, and move to Option 2 only when one leader's capacity is not enough. In every option, the safety comes from the conditional write on the job record, not from the election: election only makes conflicts rare. See Design a Job Scheduler.
Deep Dive: Shard ownership at scaleShow
From one leader to thousands. Large services assign millions of keys, users or partitions to thousands of servers, with each key owned by exactly one server at a time, and ownership moving when servers fail or load shifts. Doing this with one coordination-service lease per key would overwhelm any coordination service. Systems that do this at scale use a hierarchy:
- A small control plane, itself elected through a consensus store, decides the assignment of shards, groups of keys, to servers.
- The assignment is stored in the consensus store, or in a replicated metadata service, with a version or generation number.
- Servers hold one lease each, proving they are alive, rather than one lease per shard.
- Clients route by the current assignment, cached locally and refreshed on change, and servers reject requests for shards they do not own under the current generation.
Published examples. Google's Slicer (Atul Adya and colleagues, "Slicer: Auto-Sharding for Datacenter Applications", OSDI 2016) assigns slices of a hashed key space to tasks, rebalances them based on load, and distributes assignments to clients, and offers an optional strongly consistent mode, built on leases, in which a slice has at most one owner at a time. Facebook's Shard Manager (Sangmin Lee and colleagues, SOSP 2021) manages shard placement, failover and load balancing for a large number of Facebook's stateful services across regions, as a generic framework that applications plug into. Apache Helix does the same in open source, with configurable state models, so a shard can have one master replica and several slave replicas, and transitions between states are coordinated.
The handover problem. When shard S moves from server A to server B, there must be no moment where both serve writes, and ideally only a short moment where neither does. A safe handover:
- The controller writes a new assignment, generation 42, in which S belongs to B, with a flag that S is "moving".
- A stops accepting writes for S under generation 41, finishes in-flight work, flushes state, and acknowledges.
- B loads or receives S's state, then starts serving S under generation 42.
- Clients with the old assignment that send requests to A are told "not owner, refresh", and retry at B.
If A is unreachable, the controller must wait for A's server lease to expire before letting B serve S, because A might still be serving. That wait is the price of correctness, and it is why server lease durations, not just detection times, set the failover time of sharded systems.
Failure of the coordinator itself. If the control plane is down, servers keep serving their current shards as long as their leases remain valid, so a brief control-plane outage stops rebalancing but not serving. A well-designed system degrades to "frozen assignment", which is exactly what you want: the coordination service is on the path of changes, not on the path of every request.
Key Takeaways#
- A single leader simplifies ordering and exactly-once work, but a slow or partitioned leader looks like a dead one, so naive elections create two leaders.
- Elect leaders through a consensus-backed store (etcd, ZooKeeper, Consul, Kubernetes Leases, or a strong database row), using an atomic create or compare-and-set that exactly one candidate can win.
- Leases give leadership a time limit and return it automatically when the holder dies. The holder must step down at its own conservative deadline, measured on a monotonic clock.
- Leases alone are unsafe, because a paused leader can wake after its lease expired. Fencing tokens, increasing with each new leader and checked atomically by every resource, make late writes harmless.
- ZooKeeper offers znodes, ephemeral and sequential nodes, sessions and watches. etcd offers an MVCC key space with revisions, leases, transactions and resumable watches. Both provide linearizable writes and hold small data.
- Coordination services double as service registries, with lease-backed or ephemeral registrations and watches, and as dynamic configuration stores, but configuration changes must be validated and staged.
- Prevent split brain in layers: majority quorums, leases respected by the leader, fencing at resources, physical fencing where needed, and idempotency for external effects.
- Use coordination for small, critical, slowly changing metadata and ownership. Keep bulk data and per-request traffic out of it, and prefer partitioned or leaderless designs when they work.