Summary#
ZooKeeper and etcd are coordination services: small, strongly consistent, replicated stores that a cluster of machines uses to agree on a few critical facts. Typical facts are:
- who the leader is;
- which servers are alive;
- what the current configuration is;
- who holds a lock.
They give you a tiny key-value tree with ephemeral entries that vanish when their owner dies, and watches that notify you when something changes. Underneath, consensus keeps every replica identical: ZAB for ZooKeeper and Raft for etcd. The trade-off is deliberate. You get linearizable writes and reliable failure detection, but only for kilobytes of data and thousands of writes per second. Never use them as a general database.
Why It Exists#
Picture a chat application. At first it runs on one server. Alice and Bob both hold WebSocket connections to that machine. When Alice sends Bob a message, the server looks up Bob's socket in a local hash map and writes to it. There's no coordination, and delivery takes under a millisecond.
Then the app grows to 50 chat servers behind a load balancer. Alice is connected to server 7 and Bob to server 31. Now a set of questions appears, and none of them has a local answer:
- Where is Bob? Server 7 needs to know which server holds Bob's connection. Someone must maintain the mapping of users (or user shards) to servers, and every server must see the same mapping.
- Is server 31 still alive? If it crashes, its users must be reassigned, and nobody should keep sending messages into a dead socket. Something has to detect failure and tell everyone.
- Who is in charge? Some jobs must run exactly once: rebalancing shards, sending the daily digest, compacting old messages. If two servers both believe they're the coordinator, they'll fight. If none does, the job never runs.
- What's the config? Feature flags, rate limits and the list of shards must change at runtime without a redeploy, and the change must reach every server consistently.
- Who may touch this resource? Two servers mustn't migrate the same shard at the same time.
You could try to answer these with a regular database. But you'd immediately hit the hard parts:
- How do you notice a server died, rather than just being slow?
- How do you avoid two leaders during a network partition?
- How do you push changes instead of having 50 servers poll every second?
- How do you keep the database itself from being a single point of failure?
These problems need consensus: getting a group of machines to agree on a value despite crashes and message delays. As Consensus: Raft and Paxos explains, consensus is notoriously easy to get subtly wrong.
The industry's answer, starting with Google's Chubby lock service (Mike Burrows, "The Chubby lock service for loosely-coupled distributed systems", OSDI 2006), was to implement consensus once, in a dedicated service, and give applications simple primitives on top. Chubby was used by GFS and Bigtable for master election and for storing small bootstrap metadata.
Yahoo! built ZooKeeper in the same spirit. It was released around 2008 and became an Apache project. It's described in "ZooKeeper: Wait-free coordination for Internet-scale systems" (Patrick Hunt, Mahadev Konar, Flavio Junqueira and Benjamin Reed, USENIX ATC 2010). ZooKeeper deliberately didn't expose locks as its API. Instead it offered a small set of wait-free building blocks: znodes, ephemeral and sequential nodes, watches, and ordered operations. Clients build locks, elections, barriers and queues out of these as recipes. Hadoop, HBase, Kafka, Solr, Storm, Druid and many others adopted it, and it remains central to the Apache ecosystem.
etcd came from CoreOS in 2013 as a simpler, HTTP- and later gRPC-based store built on the then-new Raft algorithm. It's best known as the store that holds all state of every Kubernetes cluster. HashiCorp's Consul occupies the same niche with a service-discovery focus.
Even if you never run ZooKeeper, learning it teaches the universal coordination toolkit: sessions and leases, ephemeral membership, watches, sequence-ordered elections, fencing tokens and quorum math. These show up everywhere, from Kafka's KRaft to Kubernetes controllers to the leader election inside your database.
How It Works#
We'll build up from the data model to the guarantees, using ZooKeeper as the main example and then mapping each idea to etcd. The two systems solve the same problem with different vocabularies.
Data Model: ZNodes#
ZooKeeper stores data in a hierarchical namespace that looks like a file system. Each node in the tree is a znode, identified by a slash-separated path such as /chat/servers/server-07. Unlike a file system, every znode can hold data and have children. The data is a small byte array, typically a few bytes to a few kilobytes, and it's always read and written in full: there are no partial reads, appends or seeks. The default maximum is about 1 MB per znode, controlled by jute.maxbuffer, and in practice you should stay far below it.
Every znode also carries a stat structure, and these fields are what make the recipes safe:
- czxid / mzxid: the transaction id (zxid) that created and last modified the node. Zxids are a global, totally ordered sequence of every write in the ensemble.
- version: increments on every data change, alongside
cversion(child changes) andaversion(ACL changes). - ephemeralOwner: the session id that owns the node, if it's ephemeral.
- numChildren, dataLength, and creation and modification timestamps.
Writes can be conditional on the version. setData(path, data, expectedVersion) succeeds only if the version still matches, which gives compare-and-set (optimistic concurrency, as in Concurrency Control and Locking) without any lock. multi() applies several operations atomically: all succeed or none do. Examples are "create the assignment node AND bump the version of the config node".
There are several znode types, chosen at creation time:
| Type | Lifetime | Typical use |
|---|---|---|
| Persistent | Until explicitly deleted | Configuration, shard assignments, metadata |
| Ephemeral | Deleted automatically when the creating session ends; cannot have children | Liveness: "server-07 is alive", "I hold the lock" |
| Persistent sequential | Persistent, and ZooKeeper appends a monotonically increasing 10-digit counter to the name | Ordered queues, unique ids |
| Ephemeral sequential | Both: ordered and auto-deleted | Leader election and lock queues (the most important recipe primitive) |
| Container (3.5+) | Deleted by the server once its last child is gone | Parent nodes of lock or election queues, so empty parents don't pile up |
| TTL (3.5+, off by default) | Persistent node deleted after a TTL if it has no children and wasn't modified | Self-cleaning markers |
Here's a znode tree for the chat system:
Notice how much meaning comes from znode types alone:
- When server-31's process dies, its session expires. ZooKeeper deletes
/chat/servers/server-31and/chat/election/n_0000000017automatically. - Everyone watching those paths learns about it.
- server-07, holding the next sequence number, becomes leader and reassigns shard-0001.
No custom failure detector was written.
Data modelling for a coordination store follows different rules from Data Modeling for an application database. Each rule follows from the store's constraints:
- Paths are your schema. Group by purpose, as in
/app/<cluster>/<kind>/<id>, so you can watch a whole category through its parent's children. - Keep values tiny. Store pointers, not payloads: the S3 key of a config file rather than the 5 MB file, and the owner id of a shard rather than the shard's data.
- Bound the fan-out. A single parent with 1 million children makes
getChildrenreturn megabytes and can exceed the packet limit. Shard the parents instead, as in/locks/00/...through/locks/ff/.... - Store only what changes rarely, or matters greatly. Leadership, membership, assignments and configuration all qualify. Per-request or per-user data never does.
Server Roles and the Ensemble#
A ZooKeeper deployment is an ensemble, usually 3 or 5 servers. Every server holds the entire data tree in memory, so ZooKeeper's capacity is limited by one machine's RAM. Servers play three roles:
- Leader (one): orders and proposes every write, and assigns zxids.
- Followers: serve reads locally, forward writes to the leader, and vote on proposals and in leader elections.
- Observers (optional, 3.3+): receive committed writes and serve reads, but don't vote. They add read capacity, or a presence in a remote data centre, without slowing the write quorum.
Quorum math. A write commits once a majority of voting servers has persisted it. With n voters the ensemble tolerates ⌊(n − 1)/2⌋ failures:
| Voters | Majority | Failures tolerated | Notes |
|---|---|---|---|
| 1 | 1 | 0 | Dev only |
| 3 | 2 | 1 | Common default |
| 4 | 3 | 1 | No better than 3, and slower: avoid even sizes |
| 5 | 3 | 2 | Survives one failure during maintenance of another |
| 7 | 4 | 3 | Rarely worth it; writes get slower |
Even sizes add cost without adding tolerance. Bigger ensembles make writes slower, because the leader must wait for more acks, and they don't make reads much faster: use observers for reads. Spread voters across three availability zones, so that losing one zone still leaves a majority. The same arithmetic is covered in Quorums and Leaderless Replication, and it applies to etcd identically.
The standard ports are 2181 for clients, 2888 for follower-to-leader traffic, and 3888 for leader election. The configuration lists every voter (server.1=zk1:2888:3888, and so on). Since 3.5, membership can be changed at runtime with dynamic reconfiguration.
Watches: Knowing When Things Change#
Polling is wasteful. 50 servers checking /chat/config every second is 50 reads per second that almost always return the same data, and it still gives up to a second of staleness. A watch lets a client say "tell me when this changes":
getData(path, watch=true)returns the data and registers a data watch. It fires on a change to that node's data or on its deletion.getChildren(path, watch=true)registers a child watch. It fires when a child is created or deleted.exists(path, watch=true)works even when the node doesn't exist yet. It fires on creation.
Classic watches have three properties that every user must internalise:
- They're one-shot. A watch fires once and is then gone. To keep watching, you re-read and re-register in the handler. Changes that happen between the notification and your re-read aren't delivered as separate events. You'll see the latest state, but not every intermediate one. Watches are for state convergence, not event logs. Since 3.6,
addWatchsupports persistent and persistent recursive watches. They stay registered and cover a whole subtree, which removes the re-register gap. - They carry no data. The notification says "
/chat/configchanged", and you read the new value yourself. - They're ordered. A client sees the watch event before it sees the new data, and events arrive in zxid order. A client can never read a value newer than an event it hasn't been told about yet.
Watches are kept in memory on the server the client is connected to. If the client reconnects to another server, the library re-registers them, and the server checks the zxid so that no change is silently missed.
Mapping it to etcd#
etcd provides the same capabilities with a flatter, more database-like design:
- Flat key space with prefixes. Keys are byte strings such as
/chat/servers/server-07. "Directories" are just prefix ranges:Range(prefix)lists children, and you can watch a prefix. - MVCC with revisions. Every write increments a cluster-wide revision (the analogue of the zxid). Each key records
create_revision,mod_revisionandversion. Old versions are kept until compaction, so you can read a key as of a past revision. - Leases instead of sessions. A client grants a lease with a TTL (say 10 s) and keeps it alive with periodic keep-alives. Keys attached to the lease are deleted when it expires. One lease can cover many keys, which gives the same effect as ephemeral nodes.
- Watches are streams.
Watch(key or prefix, start_revision)is a long-lived gRPC stream that delivers every change from the given revision onwards, with no gaps and no re-registering. Resuming after a disconnect is easy (resume from the last seen revision plus 1). If the revision has been compacted away, the watch fails with a "compacted" error, and the client must re-list and restart. Kubernetes' list-then-watch pattern withresourceVersionis exactly this. - Transactions.
Txn(If(compare...), Then(ops...), Else(ops...))atomically evaluates conditions on versions, revisions or values, then applies one branch. This is the CAS (compare-and-swap) primitive every recipe uses. - Linearizable reads by default. A read is confirmed with the leader through a quorum check (ReadIndex), so it reflects every write that has completed. A cheaper serializable read option serves from the local replica and may be stale. This is the opposite default from ZooKeeper.
| Concept | ZooKeeper | etcd (v3) |
|---|---|---|
| Namespace | Tree of znodes | Flat keys; prefixes act as directories |
| Ordering id | zxid (epoch + counter) | Revision (cluster-wide counter) plus Raft term |
| Liveness | Session (heartbeats) and ephemeral nodes | Lease (TTL + keep-alive) and attached keys |
| Ordering primitive | Sequential znodes | create_revision of keys under a prefix |
| Change notification | One-shot watch (persistent since 3.6) | Streaming watch from a revision |
| Atomic multi-op | multi() with version checks | Txn with compares |
| History | Current state only | MVCC history until compaction |
| Default read | Local replica (sequentially consistent) | Linearizable (quorum-confirmed) |
| Consensus | ZAB | Raft |
| API | Custom binary protocol (Java and C clients, Curator) | gRPC (and a JSON gateway) |
| Value limit | About 1 MB per znode | About 1.5 MiB per request by default |
| Total data | RAM of one server | Default quota 2 GB, 8 GB suggested maximum |
Key Capabilities: the Recipes#
ZooKeeper's designers chose not to build "lock" or "election" commands into the server. Instead, the primitives above are combined into well-known recipes. These are implemented once, carefully, in client libraries: Apache Curator for Java (originally built at Netflix), and the concurrency package in etcd's Go client. Use the library recipes. Hand-written versions are a classic source of subtle bugs.
Configuration Management
Problem. 200 servers need the same runtime configuration (feature flags, rate limits, the list of upstream shards), and changes must take effect within a second or two, everywhere, without a deploy.
Recipe.
- Store the config at
/app/config, as JSON or as a pointer to a versioned file in object storage if it's large. - Each server calls
getData("/app/config", watch)at startup, applies the config, and keeps the watch, re-arming it on each event. - An admin tool writes with
setData(path, newConfig, expectedVersion). If two admins edit at once, one gets aBadVersionerror instead of silently overwriting the other's change. - On a watch event, each server re-reads the config, validates it, and applies it atomically. If validation fails, it keeps the old config and raises an alert.
Why it works. The ensemble totally orders writes, and watch notifications precede new data. So every server converges to the same latest version, and none applies versions out of order. Within roughly a few hundred milliseconds of the write, all servers have been notified.
Gotchas.
- A config push is a global, simultaneous change, which is the most dangerous kind. Stage it with a canary key (
/app/config-canaryread by 1% of servers) or a percentage field. Validate the schema before writing. - Many outages trace back to a bad config pushed instantly everywhere. The practices in CI/CD and Deployment Strategies apply to config too.
- With 10,000 watchers on one node, each change triggers 10,000 notifications and 10,000 reads. Use observers or a fan-out layer at that scale.
Service Discovery
Problem. Clients need the current list of healthy instances of a service, which keeps changing as instances scale, deploy and crash.
Recipe.
- Each instance, on startup, creates an ephemeral node
/services/chat/instance-<id>with itshost:port, zone and version as data. Many systems also use the ephemeral-sequential variant. - Clients (or a load balancer or sidecar) call
getChildren("/services/chat", watch), read each child's data, and cache the list. - When an instance shuts down cleanly, it closes its session and the node disappears at once. When it crashes or is partitioned, the node disappears after the session timeout (say 10–30 s). Either way, the child watch fires and clients refresh.
Nuances.
- Liveness isn't health. A process whose session is alive may still be returning 500s, or be stuck behind a deadlocked thread pool while a separate heartbeat thread keeps the session up. Combine registry membership with active health checks or outlier ejection in the client or mesh. This is covered under Microservices Patterns.
- The timeout window. Between a crash and the session expiry, clients may route to a dead instance. Client-side retries and fast failure detection paper over this.
- Don't put discovery on the hot path. Clients cache the list and keep working from the cache if ZooKeeper is briefly unreachable. A coordination outage should freeze membership, not take down traffic. Netflix's Eureka made the opposite CAP choice for this reason. It's an AP registry that prefers stale-but-available answers. Discovery data can tolerate brief staleness far better than lock or leader data can.
- Modern alternatives. In Kubernetes, discovery comes from the API server, whose state is in etcd, through Services and EndpointSlices, plus DNS. Consul combines a Raft-replicated catalog with gossip-based health checking and a DNS interface. Using ZooKeeper directly for discovery today is mostly done within the Apache ecosystem, for example by Kafka clients of old, HBase, Solr and Dubbo.
Leader Election
Problem. Exactly one instance of a component should act as the leader (the scheduler, the shard rebalancer, the primary of a database pair). A new one must take over quickly if it dies, and two leaders must never act at the same time.
The naive recipe has every candidate try create("/app/leader", myId, EPHEMERAL). Exactly one succeeds, because creation is atomic. Losers set an exists watch on /app/leader, and when the node is deleted (the leader's session ended), all of them retry. This works, but it has a herd effect: with 100 candidates, every leader change wakes all 100, and they all hammer the ensemble at once.
The standard recipe uses ephemeral sequential nodes:
- Each candidate creates
/app/election/n_as EPHEMERAL_SEQUENTIAL and receives, say,n_0000000018. - It calls
getChildren("/app/election")and sorts the result. - If its node has the lowest sequence number, it's the leader.
- Otherwise, it sets an
existswatch on only the node immediately before it (n_0000000017) and waits. - When that predecessor disappears, it repeats step 2. It doesn't assume it's leader, because the predecessor may have been a non-leader that simply quit.
Each leader change wakes exactly one waiter, and candidates line up in FIFO order. Leadership changes after a crash take about one session timeout plus one round trip. Curator's LeaderLatch and LeaderSelector implement this recipe. In etcd, concurrency.Election does the same thing using a lease plus keys ordered by create_revision. Each candidate watches the key with the next-lower revision.
The part people forget: knowing when you've lost leadership. A leader's session can expire while it's paused, for example in a 20-second GC pause, a VM migration or a network partition. A new leader is elected, but the old one wakes up still believing it's the leader. Two mitigations are needed:
- Listen for connection state. Curator reports
SUSPENDEDwhen the connection drops andLOSTwhen the session expires. OnSUSPENDED, a correctness-critical leader should stop acting until the connection is confirmed again. - Fence every side effect. A paused process can't notice anything until it resumes, so state listening can never be enough on its own. Every downstream write must carry a fencing token, and the downstream system must reject stale ones. That's the next recipe.
The broader theory is in Leader Election and Coordination.
Distributed Locks
Problem. Only one worker at a time may perform an operation on a resource: migrate shard 12, run the nightly billing job for tenant 7, or compact a particular file.
Recipe. This is the election recipe applied to a lock path:
- Create
/locks/shard-12/lock-as EPHEMERAL_SEQUENTIAL. - If your node is the lowest, you hold the lock. Otherwise, watch your predecessor and wait.
- Release the lock by deleting your node. If you crash, your session expires and the node disappears.
Shared and exclusive read-write locks extend the recipe. Readers wait only on the nearest lower write node, while writers wait on the nearest lower node of any kind. Curator provides InterProcessMutex, InterProcessReadWriteLock and InterProcessSemaphoreV2. etcd provides concurrency.Mutex and a server-side Lock API.
Fencing tokens. A lock held through a session or lease is only as safe as its owner's awareness that it still holds it. In this classic failure:
- Worker A acquires the lock, then pauses for 30 s in GC.
- Its session expires, and worker B acquires the lock.
- A wakes up and writes to the storage system, corrupting B's work.
The fix is for the lock service to hand out a monotonically increasing token with each acquisition. A natural choice is the zxid that created the lock node (czxid), or the etcd revision of the lock key. The protected resource then remembers the highest token it has seen and rejects lower ones:
This scheme was popularised by Martin Kleppmann's 2016 essay "How to do distributed locking". It also argues that locks used for correctness need consensus-backed services plus fencing, whereas locks used only for efficiency (avoiding duplicate work) can use something cheaper like a Redis SET NX PX. If the storage system can't check tokens, no lock service can make the scheme fully safe. In that case, design the operation to be idempotent or to use the storage system's own conditional writes. Distributed Locking covers the full spectrum.
Other recipes
- Group membership: ephemeral children under a group node, watched by everyone. This is the service-discovery recipe used for "which workers are in my cluster", and it's the input to shard assignment.
- Barriers and double barriers: wait until N participants have created nodes under
/barrierbefore starting, and until all have deleted theirs before finishing. They're used for coordinated phases in batch jobs. - Two-phase commit coordination: a coordinator node with a child per participant for votes.
- Counters and unique ids: sequential nodes, or CAS on a counter node. This is fine for low rates, but the methods in Unique ID Generation scale far better.
- Queues: sequential children consumed in order. This works, but it's an anti-pattern at any real volume. Every enqueue and dequeue is a consensus write, and a large child list is costly. Curator's own documentation discourages using ZooKeeper as a queue. Use a real queue (Message Queues) instead.
How ZooKeeper Works Inside#
Consensus with ZAB
Every ZooKeeper write goes through ZAB, the ZooKeeper Atomic Broadcast protocol, described in "Zab: High-performance broadcast for primary-backup systems" (Flavio Junqueira, Benjamin Reed and Marco Serafini, DSN 2011). ZAB is a primary-backup protocol. One leader turns each client request into an idempotent state change (a transaction) and broadcasts these in order. All replicas apply the same transactions in the same order, so they end up with identical trees.
The zxid is a 64-bit number:
- High 32 bits: the epoch, which increments each time a new leader is established.
- Low 32 bits: a counter within that epoch.
Comparing zxids therefore orders every transaction ever committed, across leader changes.
ZAB runs in two modes:
- Broadcast (normal operation). The leader assigns the next zxid and sends a PROPOSAL to the followers. Each follower appends the proposal to its transaction log and fsyncs it, then sends an ACK. When a majority (counting the leader) has acked, the leader sends COMMIT. Every server applies committed transactions to its in-memory tree, in zxid order. It's essentially a two-phase commit that needs only a majority, with no aborts, because the leader is the only proposer.
- Recovery (after leader failure). Servers run Fast Leader Election. Each votes for the server with the most up-to-date history, meaning the highest last-logged zxid (ties broken by server id), and a server wins once a quorum agrees. The new leader then:
- discovers the latest epoch among a quorum and proposes epoch + 1;
- synchronises followers, sending missing transactions (DIFF), telling them to truncate uncommitted ones from older epochs (TRUNC), or sending a full snapshot (SNAP) to followers that are far behind;
- begins broadcasting only after a quorum is in sync.
ZAB guarantees two key properties:
- Primary order. Transactions proposed by one leader are delivered in the order proposed. A new leader's transactions are delivered only after all of the previous leader's committed transactions.
- Agreement and durability of commits. A committed transaction (acked by a quorum) is in the log of at least one member of every future quorum, and the election picks a server holding it. So it can never be lost.
A transaction that was proposed but acked by only a minority before the leader crashed may be either committed or discarded by the new leader. The client never got an "ok" for it, so either outcome is consistent.
Here's the write path:
The latency of a write is about one network round trip from the leader to the fastest quorum member, plus an fsync on each, plus the client's hop to its server. In one data centre with SSDs, that's typically 2–10 ms. Disk latency dominates, which is why operators put the transaction log on a dedicated disk.
Raft (etcd), and how it compares
etcd uses Raft ("In Search of an Understandable Consensus Algorithm", Diego Ongaro and John Ousterhout, USENIX ATC 2014). Raft was explicitly designed to be easier to understand and implement than Paxos (Leslie Lamport, "The Part-Time Parliament", 1998). In practice it's remarkably close to ZAB. Each server is a follower, a candidate or the leader:
The core mechanics are:
- Terms are numbered epochs, like ZAB's epoch. Each term has at most one leader.
- Election. A follower that hears no heartbeat within a randomised election timeout becomes a candidate. The paper suggests 150–300 ms, and etcd's default is 1 s with a 100 ms heartbeat. The candidate increments the term and requests votes. A voter grants its vote only if the candidate's log is at least as up to date as its own (the election restriction), so a leader always holds every committed entry. Randomised timeouts make split votes rare.
- Log replication. The leader appends an entry, sends
AppendEntriesto the followers, and marks the entry committed once a majority has persisted it. The log matching property ensures that if two logs share an entry with the same index and term, they're identical up to that point. A follower whose log diverges is overwritten from the leader's log. - Membership changes use joint consensus or single-server changes. etcd adds learners (non-voting members, 3.4+), which catch up before being promoted, so adding a node never stalls the quorum. Learners are the analogue of ZooKeeper's observers, though they're intended to be temporary.
- PreVote and CheckQuorum stop a partitioned node from disrupting the cluster with ever-higher terms when it rejoins.
ZAB vs Raft, briefly. Both are leader-based, majority-quorum, log-replication protocols with epochs and terms. Both elect the most up-to-date server. Both are crash-fault tolerant but not Byzantine fault tolerant. The differences are in detail:
- ZAB's recovery has an explicit synchronisation phase (DIFF, TRUNC, SNAP). Raft repairs logs lazily through AppendEntries consistency checks.
- ZAB was designed around primary-backup with state-change transactions. Raft replicates commands to a state machine.
- Raft came with a much clearer specification and has many independent implementations: etcd's
raftlibrary, HashiCorp's raft, TiKV's raft-rs, NuRaft, and Kafka's KRaft (a Raft variant adapted to Kafka's pull-based log).
For a design interview, saying "ZooKeeper uses ZAB, which is essentially a Raft-like leader-based atomic broadcast" is accurate enough. Consensus: Raft and Paxos goes deeper.
Strong Consistency Guarantees
ZooKeeper's guarantees are subtle, and they're a favourite senior interview probe. ZooKeeper promises:
- Linearizable writes. All writes are totally ordered by zxid, and every server applies them in that order.
- FIFO client order. A single client's operations, reads included, execute in the order it issued them. Since a client sticks to one server, it never sees state go backwards, even across reconnects: the server it reconnects to must have seen at least the client's last zxid.
- Sequentially consistent reads, not linearizable ones. A read is served by the client's own server from its local memory, and that server may lag the leader by a few milliseconds. Client B, connected to a lagging follower, may briefly read an old value after client A has received "ok" for a newer write.
sync()gives up-to-date reads. Callingsync(path)before a read makes the client's server catch up with the leader as of that moment.sync+ read then behaves (almost) linearizably, at the cost of a round trip through the leader.- Atomicity and durability. Updates either fully succeed or fail. Once acknowledged, an update survives as long as a quorum of servers survives.
- Timeliness. A client's view is guaranteed to be up to date within a bounded time (tens of seconds), or the client is disconnected.
Why make reads weaker? Speed. Local reads need no network round trip and no quorum. They scale linearly with the number of servers (add observers for more), and the ZooKeeper paper's benchmarks showed read-dominated workloads reaching hundreds of thousands of operations per second across an ensemble. The paper reports this, but your mileage depends heavily on hardware and payload. For most recipes, sequential consistency is enough, because they rely on writes (create, delete, CAS) for correctness and use reads plus watches only to learn when to re-check.
The classic pitfall is the "hidden channel" problem. Client A updates the config and then tells client B "go read it" through some other channel, such as a message queue. B may read the old value from a lagging server. B must call sync() first. etcd sidesteps this by making reads linearizable by default, using Raft's ReadIndex: the leader confirms it's still leader with a heartbeat round, and the replica waits until it has applied up to that index before answering.
These terms are defined precisely in Consistency Models.
Read and Write Operations
Reads are getData, getChildren, exists and getACL. They're answered from memory by the connected server, typically in under a millisecond plus a network hop, with optional watch registration.
Writes are create, delete, setData, setACL and multi. They're forwarded to the leader and committed through ZAB, at a few milliseconds each. Conditional versions make them safe under concurrency.
The throughput shape follows directly:
- Reads scale with the number of servers. Write throughput doesn't scale with servers at all, because every write goes through one leader and must be persisted by a quorum. It actually decreases as you add voters.
- Writes depend on value sizes, disks and the number of concurrent clients. A well-provisioned ensemble sustains roughly 10,000–20,000 small writes per second, and less with larger values or slow disks. etcd's published benchmarks are in the same order of magnitude, a few tens of thousands of small writes per second with many concurrent clients.
That's tiny compared with a database or Kafka, and it's by design. This is exactly where the guidance from Numbers to Know about not over-engineering for write throughput cuts the other way. If your plan needs more than a few thousand coordination writes per second, the plan is probably using the coordinator for data it shouldn't hold.
Sessions and Connection Management
A client opens a session with a requested timeout. The server negotiates it to between 2× and 20× tickTime, and tickTime defaults to 2,000 ms, so typical values are 6–40 s. The client library:
- connects to one server from a connection string listing the whole ensemble (
zk1:2181,zk2:2181,zk3:2181); - sends heartbeats (pings) when idle, about every third of the timeout;
- on losing the connection, reconnects to another server with the same session. Ephemeral nodes and watches survive if the reconnect happens before the timeout.
The leader tracks session expiry. If no heartbeat arrives within the timeout, it expires the session (a committed transaction, so every server agrees), deletes all its ephemeral nodes, and fires the corresponding watches.
The essential client discipline follows:
- Disconnected isn't expired. While disconnected, the client doesn't know whether its session (and therefore its locks, leadership and ephemeral registrations) still exists. Safe code treats Disconnected (Curator's SUSPENDED) as "possibly lost". It pauses leader or lock-holder work until it either reconnects (the session is still valid) or learns of expiry.
- An expired session is gone forever. The client must create a new session, re-create its ephemeral nodes, re-register its watches, and re-enter elections. Libraries do some of this. Your application must handle the rest, such as reconciling the work it was doing.
- Choosing the timeout trades failover speed against false positives. A 5 s timeout detects crashes quickly, but a 6 s GC pause or a brief network blip will expire healthy sessions and cause churn. 10–30 s is common for infrastructure. Combine it with fencing, so that false positives are safe, merely disruptive.
- Session storms. If the ensemble is overloaded (a slow disk, or a huge snapshot transfer), heartbeats are delayed, and thousands of sessions may expire at once. Every client then reconnects and re-registers, which overloads the ensemble further. This is a well-known cascade, and it's another reason to keep coordination workloads small and isolated. The general patterns are in Failure Detection, Heartbeats and Gossip.
etcd leases behave the same way: a TTL, keep-alives over a gRPC stream, and keys attached to a lease deleted on expiry. The leader grants and revokes leases through Raft. One subtlety is that when a leader changes, etcd extends remaining leases, so that clients aren't punished for the election time.
Storage Architecture
Each ZooKeeper server keeps:
- The in-memory data tree: the complete current state, serving all reads.
- A transaction log on disk. Every proposal is appended and fsynced before acking, and the log is pre-allocated in blocks to avoid file-growth overhead. This is the durability path, so put it on its own fast disk (an SSD, separate from snapshots and from the OS). A slow disk directly stalls the whole ensemble's writes.
- Fuzzy snapshots, taken periodically after a configurable number of transactions (
snapCount). The snapshot is written while the tree keeps changing, so it doesn't correspond to any single moment. That's fine, because transactions are idempotent: on recovery, the server loads the latest snapshot and replays the log from just before the snapshot began. Re-applying an already-reflected transaction is harmless. - Cleanup. Old snapshots and logs accumulate. Set
autopurge.snapRetainCountandautopurge.purgeInterval, or disks fill up, which is a common operational outage.
etcd stores its Raft WAL (write-ahead log) and periodic Raft snapshots on disk. Its key-value state lives in bbolt, an embedded B+tree database (a fork of BoltDB) with MVCC: each key's versions are indexed by revision in an in-memory B-tree, and the values are in bbolt. Two maintenance tasks matter:
- Compaction discards history older than a chosen revision. Kubernetes' API server compacts about every 5 minutes. Without it, history grows forever.
- Defragmentation returns freed pages to the filesystem.
The default backend quota is 2 GB. When it's exceeded, etcd raises a NOSPACE alarm and rejects all writes until you compact, defragment and disarm it. This is a famous way to take down a Kubernetes control plane.
Handling Failures
| Failure | What happens | Impact |
|---|---|---|
| Follower crash | Leader continues with the remaining quorum; clients connected to it reconnect elsewhere within their session timeout | None visible beyond reconnects |
| Leader crash | Followers stop receiving heartbeats, run election (~hundreds of ms to a few seconds), new epoch, sync, resume | Writes unavailable during election; reads continue on servers that are up (ZK), or wait for the leader (etcd linearizable reads) |
| Minority partition | Servers in the minority can't form a quorum; they stop serving (ZK servers stop serving clients when they lose the leader) | Clients there reconnect to majority-side servers if reachable |
| Majority lost (2 of 3 down) | No quorum: no writes, no elections, no session expiry | Coordination frozen; well-written clients keep running with cached state but can't change leadership or locks |
| Slow disk on leader | Every write waits for fsync; heartbeats may be delayed | Latency spikes, possible session storm; move the txn log to a dedicated disk |
| Client GC pause beyond timeout | Session expires, ephemeral nodes deleted, another client takes the lock or leadership | Safe only with fencing; otherwise split-brain on the protected resource |
| Snapshot or data dir full | Server can't write, crashes or stalls | Purge old snapshots and logs; monitor disk |
The critical design insight is that coordination services trade availability for consistency (CP in CAP Theorem and PACELC terms). During a partition, the minority side refuses to act rather than risk two leaders. Systems that depend on ZooKeeper must decide what to do when it's unreachable. Usually the answer is "keep doing what you were doing with the last known state, but don't make new coordination decisions".
ZooKeeper in the Modern World#
Current usage in major distributed systems
ZooKeeper's design shows up in a lot of well-known infrastructure. Some systems still depend on it, and some have replaced it with built-in consensus:
- Apache Kafka (before KRaft). ZooKeeper stored broker registrations (ephemeral), topic configs, partition assignments, ISR (in-sync replica) state, ACLs, and the controller election, where the first broker to create the ephemeral
/controllerznode won. Kafka 4.0 removed ZooKeeper entirely (see below). - Apache HBase. It's used for active-master election, RegionServer liveness (ephemeral nodes), and the location of the
hbase:metatable. Clients bootstrap by asking ZooKeeper where meta lives. - HDFS NameNode high availability. A ZKFailoverController next to each NameNode holds an ephemeral lock znode to decide which NameNode is active, and fences the old one during failover.
- Apache Solr (SolrCloud), Apache Druid and Apache Storm use it for cluster state, leader election and assignments.
- Apache Pulsar and BookKeeper use it for metadata and ledger management. Newer Pulsar versions offer a pluggable metadata store that can use etcd.
- Apache Flink HA uses ZooKeeper or Kubernetes ConfigMaps for JobManager leader election and checkpoint metadata pointers, as covered in Apache Flink and Stream Processing.
- ClickHouse Keeper is a ZooKeeper-compatible service written in C++ on top of a Raft library (NuRaft). It was built to replace ZooKeeper for ClickHouse replication metadata with lower resource usage. It speaks the ZooKeeper wire protocol, which shows how influential the API remains.
etcd's footprint is anchored by Kubernetes, where every object (pods, services, config maps, secrets, leases) lives in etcd behind the API server. Other users include:
- Patroni, the PostgreSQL HA manager, which uses etcd, Consul or ZooKeeper as its "DCS" (distributed configuration store) for leader keys;
- Vitess, whose topology service can be etcd, ZooKeeper or Consul;
- TiDB's Placement Driver, which embeds etcd;
- M3, Uber's metrics platform, which uses etcd for placement.
Why Kafka moved to KRaft
Kafka's migration from ZooKeeper to its own Raft-based metadata quorum, KRaft (proposed in KIP-500 in 2019, production-ready in 3.3, and the only mode in 4.0), is the best case study of a coordination service's limits:
- Two distributed systems to run. Operators had to deploy, secure, monitor, upgrade and tune ZooKeeper and Kafka. These were two configuration models, two security models (SASL and TLS in each), and two sets of failure modes. For many teams, ZooKeeper caused a disproportionate share of Kafka's incidents.
- Metadata scalability. In ZooKeeper mode, the controller (one elected broker) loaded all cluster metadata from ZooKeeper whenever it took over. For clusters with hundreds of thousands of partitions, a controller failover could take tens of seconds to minutes, during which no leader elections for failed partitions could happen. Practical guidance capped clusters at roughly 200,000 partitions. KRaft aims for millions.
- Two sources of truth. The controller kept an in-memory copy of metadata and pushed updates to brokers by RPC, while ZooKeeper held the durable copy. Keeping the controller's memory, ZooKeeper, and every broker's cache consistent was a recurring source of bugs (for example, brokers acting on stale metadata).
- Metadata is naturally a log. Kafka is the world's most popular log. Storing cluster metadata as an event log, the internal
__cluster_metadatatopic, replicated by a Raft quorum of controllers, lets brokers simply consume the log. Brokers stay up to date by fetching from an offset, exactly like consumers, and snapshots bound the replay time. - Instant failover. In KRaft, standby controllers are hot, because they're already replicating the metadata log in memory. When the active controller fails, a new one is elected through Raft and takes over almost immediately. It has no bulk reload.
After the migration, the controllers form their own Raft quorum, and brokers pull metadata the same way consumers pull records:
The lesson isn't that ZooKeeper is bad. External coordination is a good starting point, but systems with heavy, growing metadata eventually benefit from embedding consensus and treating metadata as a replicated log. Elasticsearch followed a similar path. It never used ZooKeeper by default, and in 7.0 it replaced its older Zen discovery with a new cluster-coordination subsystem whose design draws on Raft-style quorums and terms. The master-eligible nodes elect a master that publishes cluster state to the data nodes, as described in Elasticsearch and Search Systems.
Apache Kafka in Practice covers the rest of Kafka's architecture.
Alternatives to consider
| Option | What it is | Fits when |
|---|---|---|
| etcd | Raft KV store, gRPC, leases, streaming watches, MVCC | Kubernetes-adjacent systems; new infrastructure needing a coordination store; Go ecosystems |
| ZooKeeper | ZAB, znode tree, sessions, one-shot (or persistent) watches, Curator recipes | Apache/JVM ecosystem (HBase, Solr, Pulsar, Druid); existing ZK operational expertise |
| Consul | Raft-replicated catalog + KV, gossip (Serf, SWIM-based) membership, health checks, DNS interface, service mesh | Service discovery and health checking across VMs and containers, multi-datacenter |
| Embedded Raft (etcd/raft, hashicorp/raft, raft-rs, KRaft) | Consensus inside your own system | You're building a database or broker whose metadata is large or performance-critical |
| Kubernetes primitives | Lease objects, ConfigMaps, the API server's watch | Your workloads already run on Kubernetes: leader election via coordination.k8s.io/Lease without running anything new |
| Managed DB conditional writes | DynamoDB conditional puts with TTL, Spanner, a PostgreSQL row with SELECT ... FOR UPDATE or advisory locks | Low-rate locks or leases in an app that already has a strongly consistent database |
Redis (SET NX PX) | Single-node lock with expiry | Efficiency locks, rate-limit-style mutual exclusion where an occasional double execution is tolerable, as in Redis in Practice |
| Chubby (Google-internal) | The original Paxos-based lock service | Not available outside Google, but it's the conceptual ancestor |
Two families aren't alternatives, though they're often mentioned alongside these:
- Gossip systems such as Cassandra's membership. They provide eventually consistent failure detection without consensus. Cassandra is leaderless, using gossip for membership and consistent hashing for placement, and needs no ZooKeeper at all, as covered in Apache Cassandra in Practice. Gossip can't give you a single leader or a safe lock.
- Message queues. They don't give you shared state.
Limitations
- Small data only. The whole dataset must fit in RAM on every server (ZooKeeper), or within a few GB of quota (etcd). Values are limited to about 1 MB, and should be far smaller. Store references, not payloads.
- Limited write throughput. Writes are serialised through one leader and fsynced by a quorum, giving roughly thousands to tens of thousands per second, and adding servers doesn't help. A design that sends per-request or per-user writes to ZooKeeper will melt it.
- Write latency includes an fsync and a quorum round trip. That's milliseconds in one region. A cross-region ensemble pays inter-region RTT on every write (say 70 ms or more), so coordination is usually kept regional, with a separate ensemble per region.
- Watch fan-out costs. Thousands of watchers on a hot node mean a notification storm plus a read storm on each change. A huge child list (100k children) makes each
getChildrenexpensive. - Operational sharp edges:
- JVM tuning for ZooKeeper (GC pauses cause session expiry);
- disk latency;
- snapshot and log purging;
- etcd compaction, defragmentation and quota alarms;
- version skew;
- the need to run an odd-sized ensemble across zones;
- TLS and ACL setup.
- CP by design. Losing a quorum freezes coordination. Your system must behave sensibly, keeping its last known state, when the coordinator is unavailable.
- Locks aren't magic. Session- or lease-based locks can't protect against paused processes without fencing tokens checked by the resource. Jepsen's analysis of etcd 3.4.3 (Kyle Kingsbury, 2020) found its key-value operations strictly serializable, but it demonstrated exactly this limitation in the lock API.
So when should you use ZooKeeper (or etcd)?
In modern designs, the answer is usually "indirectly". Your Kafka, Kubernetes, HBase or Flink cluster uses one internally, and you name the component rather than the coordination service. Interviewers rarely want "use ZooKeeper" as a step in a product design such as a news feed, where it adds nothing. It earns a place in three kinds of problems.
Smart routing. When requests must reach the specific server that holds some state, a coordination service can hold the routing table at the granularity of shards or servers, never individual users. Examples are the WebSocket server holding a user's connection, the cache node owning a key range, or the stateful game server hosting a match. For the chat example:
- Hash users into, say, 4,096 virtual shards.
- Store the
shard → serverassignment (a few hundred KB) in ZooKeeper, or the hash-ring membership itself with Consistent Hashing. - Let every gateway cache it and watch for changes.
- When a server dies (its ephemeral node vanishes), a leader-elected assigner moves its shards to others and writes the new assignment with CAS.
The per-message routing decision is a local lookup in the cached table, with no ZooKeeper call on the hot path. Per-user presence ("Bob is on server 31"), which changes with every connect and disconnect, belongs in a fast store like Redis, or in the shard-based scheme above. Never put it in ZooKeeper.
Infrastructure design problems. When the interview is about building infrastructure, the coordination layer is a first-class component, and you should name it and explain its role:
- a distributed message queue (broker membership, partition leadership, controller election);
- a distributed cache or key-value store (cluster membership, partition map, rebalancing);
- a job scheduler (a single active scheduler through leader election, worker registration);
- a metrics or storage system (shard placement).
The strongest answers also mention the KRaft-style alternative of embedding Raft once metadata grows. See Design a Distributed Message Queue and Design a Distributed Key-Value Store.
Durable distributed locks. Use a consensus-backed lock when correctness depends on mutual exclusion and the lock may be held for a long time (seconds to hours). Examples are a single writer for a partition of a file system, an exclusive schema migration runner, or a controller that must never act twice. ZooKeeper and etcd locks survive the failure of a single coordination server (unlike single-node Redis), are released automatically when the holder dies (unlike a database row someone forgot to delete), and provide fencing tokens through zxids or revisions.
They're the wrong tool for high-volume, fine-grained locks. Consider ticket booking with millions of seats, each briefly reserved:
- Holding database row locks open for the 10-minute checkout window is a known bad design. It ties up connections and transactions, and abandoned sessions hold the lock until the timeout.
- Moving those millions of locks into ZooKeeper would be just as wrong, since every acquire and release is a consensus write.
- The right pattern there is a reservation record with an expiry: a status column with
reserved_until, set by a conditional update, or a Redis key with a TTL. The final purchase is validated by the database.
This is covered in Dealing with Contention and Design a Ticket Booking System.
When to Use It#
Reach for a coordination service, or for a system that embeds one, when you see these signals:
- Exactly-one semantics for a role: one active scheduler, controller, primary or compaction leader. Failover must take seconds, not a human page, and split-brain would corrupt data.
- Membership must be authoritative: "the set of live brokers" or "which nodes own which partitions" must be a single agreed answer, not each node's opinion from gossip.
- Small, critical, rarely changing metadata: a shard map of a few hundred KB, feature flags, cluster topology, schema versions. It's read by hundreds of processes and changes a few times per minute at most.
- Change notification: processes must react within about a second when this metadata changes, without polling.
- Correctness-critical locks held for seconds to hours, with automatic release on holder death and fencing tokens available.
- You're building infrastructure (a queue, a database, a scheduler, a cache cluster) and need a control plane.
- Your platform already provides one. On Kubernetes, a
Leaseobject gives you leader election backed by etcd, with no new system to run.
Pick something else instead when:
- The data is large or write-heavy (user sessions, presence, counters, events, queues). Use Redis, a database or Kafka.
- You need efficiency locks only (avoid duplicate cache rebuilds). Redis
SET NX PXis simpler and faster. - Your database can do it. A conditional update or advisory lock in a database you already run is fine for a handful of low-rate leases.
- You need discovery with rich health checks across VMs. Consul, or the platform's own discovery (Kubernetes Services, cloud service registries).
- You need workflow orchestration with retries and timers. That's a durable workflow engine (Temporal and Workflow Engines), not a lock service.
When NOT to Use It#
- As a database. ZooKeeper isn't a KV store for application data. A design that writes each order, message or user status to it caps the system at a few thousand writes per second, and a session storm takes it down.
- As a message queue. Sequential-node queues are a documented anti-pattern. Every enqueue and dequeue is a consensus write, and large child lists are slow.
- On the request hot path. A request should never synchronously call ZooKeeper. Cache the coordination data, watch it for changes, and keep serving from the cache if the ensemble is briefly unavailable.
- For product-level designs where it adds nothing. Mentioning ZooKeeper for a URL shortener or a news feed signals pattern-matching rather than reasoning.
- Across regions for low-latency writes. One global ensemble puts inter-region RTT on every write and couples regional availability. Use per-region coordination plus asynchronous replication of what must be global.
- When you'd be the first to operate it. If nothing else in your stack needs ZooKeeper, adding a JVM cluster you must tune and patch just for a single leader election is a poor trade. Use a Kubernetes
Lease, a managed store, or a database lease instead.
How to Implement It#
- Decide whether you need it at all. List the exact facts that need consensus (who leads X, which nodes own which shards, config version Y). If the list is empty, or the data is large or write-heavy, stop here and use a database or Redis.
- Pick the system.
- Kubernetes-native or Go: etcd, or the Kubernetes API itself.
- Apache and JVM ecosystem: ZooKeeper with Curator.
- VM fleets needing discovery and health checks: Consul.
- Building a new database or broker: consider embedding Raft.
- Size the ensemble. Use 3 voters across 3 AZs (tolerates 1 failure), or 5 for critical clusters (tolerates 2, survives maintenance plus a failure). Add observers (ZooKeeper) for read-heavy or remote clients rather than more voters. Use SSDs, with a dedicated disk for the transaction log or WAL, and give memory enough headroom that the tree or bbolt file plus the JVM heap fit comfortably.
- Design the namespace. Use clear, per-purpose prefixes (
/svc/<cluster>/members/,/svc/<cluster>/leader/,/svc/<cluster>/config), small values, and bounded fan-out. Use chroot or per-application roots with ACLs (ZooKeeper) or RBAC users and roles (etcd). - Use library recipes, not hand-rolled ones: Curator
LeaderLatchorLeaderSelector,InterProcessMutex,NodeCacheandCuratorCache, or etcdconcurrency.Electionandconcurrency.Mutex. Handle the connection-state callbacks explicitly. - Choose session and lease timeouts. Typical values are 10–30 s. Shorter gives faster failover but more false expiries during GC or network blips. Tune GC on clients, since long pauses cause most false expiries.
- Fence every side effect a leader or lock-holder performs. Pass the zxid or revision as a token, and make downstream systems reject stale tokens, or use conditional writes keyed on the token.
- Cache and degrade. Clients cache everything they read, keep serving if the ensemble is unreachable, and avoid making new coordination decisions until it's back.
- Operate it.
- Enable autopurge (ZooKeeper), or compaction plus periodic defragmentation (etcd).
- Monitor quota usage, fsync latency, leader changes, outstanding requests, session counts and watch counts.
- Back it up: etcd
snapshot save, or ZooKeeper snapshots. - Rehearse restoring from backup.
- Test failure modes. Kill the leader, partition a voter, pause a client for longer than its session timeout, and fill the disk. Verify that exactly one leader acts and that fencing rejects the stale one.
Here's a leader-election loop with fencing, as TypeScript-flavoured pseudo-code (etcd-style):
// Pseudo-code: leader election with lease + fencing (etcd-style API shape)
async function runAsLeader(etcd: Etcd, id: string, work: (token: bigint) => Promise<void>) {
while (true) {
const lease = await etcd.grantLease({ ttlSeconds: 15 });
lease.keepAliveInBackground(); // heartbeats ~every 5 s
const myKey = `/svc/scheduler/election/${lease.id}`;
await etcd.put(myKey, id, { lease: lease.id });
const myRev = (await etcd.get(myKey)).createRevision; // my place in the queue
// Wait until no key under the prefix has a lower createRevision
await waitUntilLowest(etcd, "/svc/scheduler/election/", myRev); // watches predecessor only
const token = myRev; // monotonically increasing fencing token
const lost = lease.onLostOrExpired(); // resolves if keep-alive fails
try {
await Promise.race([work(token), lost]); // work() passes token on every write
} finally {
await etcd.delete(myKey).catch(() => {}); // resign; lease expiry is the fallback
lease.revoke().catch(() => {});
}
}
}
// Downstream store: accept a write only if token >= highest seen (conditional update)
// UPDATE jobs SET state = $1, fence = $2 WHERE id = $3 AND fence <= $2;| Technology | Fits when |
|---|---|
| Apache ZooKeeper 3.8+/3.9 | You run Kafka (legacy ZK mode), HBase, Solr, Pulsar or Druid, or a JVM shop with Curator expertise |
| Apache Curator | Any Java or JVM client of ZooKeeper; use its recipes instead of raw API calls |
| etcd 3.5+ | Kubernetes control planes; Go services needing leases, elections and watches; new coordination needs outside the Apache ecosystem |
| Kubernetes Lease API | Leader election for controllers and operators already on Kubernetes, with nothing new to operate |
| HashiCorp Consul | Service discovery, health checks and KV across VMs and data centres; DNS-based discovery |
| ClickHouse Keeper | A ZooKeeper-compatible replacement for ClickHouse replication metadata |
| Embedded Raft (etcd/raft, hashicorp/raft, raft-rs) | Building your own replicated database, queue or metadata service |
| Managed: cloud KV with conditional writes (e.g. DynamoDB) | Low-rate leases or locks when you'd rather not run a quorum cluster; add fencing via conditional versions |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| ZooKeeper | Mature (since ~2008); rich recipes via Curator; fast local reads; observers; huge Apache ecosystem | JVM to tune; custom protocol; one-shot watch semantics (pre-3.6); reads not linearizable without sync | Existing Apache stack; JVM teams |
| etcd | Simple gRPC API; linearizable reads by default; MVCC history; streaming watches from a revision; Kubernetes standard | 2–8 GB data ceiling; compaction and defragmentation chores; watch history lost after compaction | Kubernetes or Go; new systems |
| Consul | Discovery, health checks and DNS built in; multi-DC; service mesh option | Larger surface; KV is secondary; another HashiCorp product to run | VM-heavy fleets needing discovery |
| Embedded Raft | No external dependency; metadata as a log; instant failover (KRaft) | You own a consensus implementation's correctness and operations | Building a database, broker or scheduler at scale |
| Redis lock | Very fast; simple; already deployed | No consensus: failover can lose locks; TTL-based with no fencing unless added | Efficiency locks; duplicate work is tolerable |
| Database lease or lock | No new system; transactional with your data | Couples locks to DB health; long-held row locks block and exhaust connections | Few low-rate leases in an app already on a strong DB |
Common Pitfalls#
- Using the coordinator as a database or queue, whether per-user presence, job queues or counters. Writes saturate the leader, and memory fills.
- Ignoring connection-state events. A leader that keeps acting while SUSPENDED or after expiry causes split-brain.
- No fencing. Session and lease locks without tokens checked by the resource are unsafe against GC pauses and partitions.
- The herd effect. Everyone watches the same node, so every change wakes thousands of clients. Watch your predecessor, or use one watcher that fans out.
- Even-sized ensembles, or all voters in one AZ. You pay more for no added fault tolerance, and an AZ outage kills the quorum.
- A slow or shared disk for the transaction log or WAL. fsync latency becomes ensemble latency, and then you get session storms.
- Forgetting autopurge (ZooKeeper) or compaction and defragmentation (etcd). The disk fills or the
NOSPACEalarm fires, and all writes stop. This has caused real Kubernetes control-plane outages. - Assuming ZooKeeper reads are linearizable. The hidden-channel bug: call
sync()when you need read-after-another-client's-write. - Large values or huge child lists. You hit
jute.maxbufferor the gRPC limits, and slowgetChildrencalls stall everything. - Putting a coordination call on every request. Latency and availability then become coupled to the ensemble. Cache, and watch.
Real-World Examples#
- Google Chubby (Burrows, OSDI 2006): a Paxos-based lock service used by GFS and Bigtable for master election and for storing small metadata. Its paper noted that, in practice, Chubby was heavily used as a name service, which influenced how ZooKeeper was designed for reads.
- Yahoo! ZooKeeper (Hunt et al., USENIX ATC 2010): built to give many Yahoo! services a common coordination kernel. It became the coordination layer for Hadoop-ecosystem projects (HBase, HDFS HA via ZKFC, Solr, Storm, Druid) and for Kafka until KRaft.
- Netflix created Curator, a high-level ZooKeeper client with battle-tested recipes, and contributed it to Apache, where it became a top-level project.
- Apache Kafka replaced ZooKeeper with KRaft. KIP-500 proposed it in 2019, it was production-ready in 3.3 in 2022, and ZooKeeper was removed in 4.0 in 2025. The motivations were operational simplicity and metadata scalability.
- Kubernetes stores all cluster state in etcd. Controllers and schedulers run leader election through
Leaseobjects, and the API server's list-and-watch builds on etcd's revisioned watches. - ClickHouse built ClickHouse Keeper, a Raft-based, ZooKeeper-protocol-compatible coordinator, to replace ZooKeeper for its replicated tables.
Case studies that use this pattern#
- Design a Distributed Message Queue (Kafka): controller election, broker membership and the KRaft metadata log.
- Design a Distributed Job Scheduler: a single active scheduler through leader election, worker registration, and fencing of job claims.
- Design a Distributed Key-Value Store (Dynamo-style): the contrast between gossip-based membership and consensus-based coordination.
- Design a Distributed Cache: cluster membership and the partition map pushed to clients.
- Design a Chat System (WhatsApp): routing to the server holding a user's connection.
In the Interview#
Deep Dive: ZooKeeper's design choices, ZAB's ordering guarantee and the performance mathShow
Wait-free, not blocking. Chubby exposed locks directly: a client asked to lock a file and blocked until it was granted. ZooKeeper's designers judged that blocking primitives in the server would couple clients' progress to each other. A slow or faulty client holding a server-side blocking request ties up server resources and complicates the implementation. So ZooKeeper exposes only wait-free operations. Every call completes independently of other clients' behaviour, and coordination (waiting) is built in the client from watches. The same small kernel then implements locks, read-write locks, barriers, elections, membership and configuration. That's why the paper calls it a coordination kernel.
Pipelining and A-linearizability. Clients can issue many asynchronous operations without waiting for each response. The ensemble guarantees that one client's operations execute in issue order (FIFO client order). Combined with linearizable writes, the paper calls this A-linearizability (asynchronous linearizability). A practical consequence is that a newly elected leader can, for example:
- issue a delete of the old config marker;
- issue many writes for the new config;
- create a "ready" znode.
It can do all of this pipelined, without waiting, and any client that sees "ready" (and watched for it) is guaranteed to see all the earlier writes. That is the paper's well-known ready-znode pattern for atomic configuration changes, and it works only because of FIFO order plus watch-before-data ordering.
Why ZAB rather than plain Paxos? Multi-Paxos agrees on each log slot independently. With many proposals in flight (pipelined) across a leader change, a new leader could commit a later proposal from the old leader's batch without an earlier one, if the earlier one hadn't reached a quorum. For a primary-backup system, where each transaction is a state delta computed from the previous state, that's unacceptable: applying delta 7 without delta 6 corrupts the state. ZAB's primary order guarantees that if a transaction from a leader is delivered, every transaction that leader proposed before it is also delivered. A new leader delivers nothing new until the previous epoch's history is settled. Raft achieves the same effect structurally, because commitment is by log index (prefix commitment), and a leader only commits entries from its own term directly, committing earlier entries implicitly. That's part of why the two protocols ended up so similar.
Idempotent transactions make fuzzy snapshots safe. The leader converts each request into an idempotent transaction before proposing it. For example, setData(path, data, version=5) becomes "set path to data, version to 6, mzxid to Z". Re-applying it gives the same result. That's what lets snapshots be taken without stopping writes: replaying the log from the snapshot's start zxid over a snapshot that already reflects some of those transactions converges to the right state.
Performance math, worked.
- Write latency. The client sends the request to its follower (0.3 ms in the same AZ), the follower forwards it to the leader (0.5 ms across AZs), and the leader sends the proposal to the followers (0.5 ms). Each follower fsyncs (an NVMe SSD with a log on a dedicated disk takes about 0.5–2 ms, while a busy shared cloud disk can take 5–20 ms) and acks (0.5 ms). Then come the commit and the reply (about 1 ms). The total is roughly 3–5 ms on good disks and 10–25 ms on poor ones. The disk term is the one you can control.
- Write throughput. The leader batches proposals, and group commit amortises fsyncs across many transactions, so throughput is far higher than 1/latency. Roughly 10k–20k small writes per second is a realistic, hardware-dependent ceiling for one ensemble. A design needing 50k coordination writes per second is a design problem, not a tuning problem.
- Read capacity. Each server can answer tens of thousands of in-memory reads per second, and reads scale with servers. A 5-voter ensemble with 4 observers serves well over 100k reads per second. Because reads are local, a read-heavy load doesn't slow writes much, except through the CPU it consumes on the leader, so keep clients off the leader where possible.
- Watch notification fan-out. Suppose a config node watched by 5,000 clients changes. Each server sends notifications to its connected watchers (5,000 small packets in total), then gets 5,000
getDatareads within about 100 ms. If the value is 50 KB, that's 250 MB of reads in a burst, enough to cause visible latency on the ensemble. The remedy is to keep values small, use a version-number node that clients watch with the payload in object storage, and add observers. - Memory. The whole tree is held on the heap, plus watch tables and session state. 500,000 znodes averaging 1 KB, with overhead, need a few GB of heap. Size the JVM to keep GC pauses short (G1 or ZGC with a fixed heap), because a long GC pause on the leader delays heartbeats for everyone.
Deep Dive: etcd internals at Kubernetes scaleShow
MVCC layout. etcd's store keeps two structures:
- An in-memory B-tree index from each key to its list of revisions (generations). A generation starts at creation and ends at deletion with a tombstone.
- The bbolt B+tree file, keyed by
(main revision, sub revision), which holds the actual key-value records.
A read at revision R looks up the key in the index, finds the latest revision ≤ R, and fetches it from bbolt. A write appends a new record at revision + 1. Nothing is updated in place, which is what makes watch-from-revision and consistent multi-key reads at a revision cheap.
Compaction and defragmentation.
- Compaction at revision R removes all superseded versions older than R from both the index and bbolt. Watchers that try to resume before R get
ErrCompacted. Kubernetes runs compaction from the API server, about every 5 minutes by default. etcd can also auto-compact by retention period or revision count. - bbolt doesn't shrink its file after deletions. Freed pages are reused, but the file stays large. Defragmentation rewrites the file compactly, but it blocks reads and writes on that member while it runs, so you defragment members one at a time, never all at once.
- The quota. The backend quota (
--quota-backend-bytes, 2 GB by default, 8 GB the suggested maximum) applies to the file size. A cluster with heavy churn can hit the quota even with little live data, if defragmentation never runs. Hitting it raises theNOSPACEalarm, which turns the cluster read-only until an operator compacts, defragments and disarms it.
Why Kubernetes doesn't flatten etcd. Thousands of controllers and kubelets watch pods, nodes and endpoints. If each opened its own etcd watch, etcd would be flooded. The kube-apiserver instead keeps a watch cache per resource type. It holds one watch on etcd per resource prefix, maintains a sliding window of recent events in memory, and serves many client watches and list calls from that cache. Clients use list-then-watch with resourceVersion, which is the etcd revision. They list at revision R, watch from R + 1, and re-list after "410 Gone" (compacted).
Scale guidance for large clusters (about 5,000 nodes is Kubernetes' documented upper scalability target) includes:
- keeping the very high-churn Events resource in a separate etcd cluster;
- limiting object sizes (ConfigMaps and Secrets are capped around 1 MiB);
- avoiding unbounded custom resources.
A worked capacity example. A cluster has 3,000 nodes, 60,000 pods, 10,000 services and other objects totalling about 200,000 objects of about 5 KB, or roughly 1 GB of live data. Churn from rolling deploys is around 200 writes per second sustained, with bursts to about 2,000 per second during mass rollouts. Node heartbeats are Lease updates every 10 s per node, adding 300 writes per second. Compaction every 5 minutes retains about 5 minutes × 500 writes per second × 5 KB ≈ 750 MB of history. This fits comfortably within an 8 GB quota and well within etcd's write capacity on NVMe disks. But it shows why Kubernetes moved node heartbeats from full Node-status updates (large objects) to small Lease objects (in 1.14+): it cut the write volume and size substantially.
Linearizable reads, ReadIndex and lease reads. To serve a linearizable read, a replica must be sure no newer write has committed elsewhere. etcd uses ReadIndex:
- The leader records its commit index.
- It confirms it's still leader with a heartbeat round to a quorum.
- The serving member waits until it has applied up to that index.
This costs a heartbeat round trip but no log write. Lease-based reads, where a leader assumes it's still leader for an election timeout after the last successful heartbeat, avoid the round trip but depend on bounded clock drift. etcd's default is the safe ReadIndex path, and clients can opt into serializable (local, possibly stale) reads for speed.
Timing parameters across distance. The defaults are a heartbeat interval of 100 ms and an election timeout of 1,000 ms, which suit a single region (RTT under 10 ms). For members in different regions with 80 ms RTT, set the heartbeat to around the RTT and the election timeout to at least 5–10× that. Otherwise, normal latency jitter triggers spurious elections. Even so, every write pays a cross-region round trip, so most deployments keep etcd regional.
Disaster recovery.
- Periodic
etcdctl snapshot save, stored off-cluster, is the backup. - If quorum is permanently lost (2 of 3 members destroyed), you restore a snapshot into a new cluster with new member ids. Anything after the snapshot is lost, which for Kubernetes means objects created since then must be reconciled.
- ZooKeeper's equivalent is restoring snapshots and transaction logs to a new ensemble. Its newer versions also support admin-server and snapshot tooling.
Rehearse this. Teams usually discover in an incident that their control-plane backup was never tested.
Deep Dive: Why coordination is hard: FLP, partial synchrony, leases and the limits of locksShow
The impossibility result. Fischer, Lynch and Paterson ("Impossibility of Distributed Consensus with One Faulty Process", JACM 1985) proved that in a fully asynchronous system, where message delays are unbounded and there are no clocks, no deterministic algorithm can guarantee consensus terminates if even one process may crash. The reason is that a slow process is indistinguishable from a dead one.
Practical systems escape through partial synchrony (Dwork, Lynch and Stockmeyer, "Consensus in the Presence of Partial Synchrony", JACM 1988). They are always safe: never two decisions, never two leaders in the same term. They're live (they make progress) only during periods when messages arrive within bounds. ZAB and Raft both follow this pattern. Timeouts trigger elections, and quorum intersection keeps safety regardless of timing.
Leases are where time sneaks back in. Consensus guarantees that the service never believes two clients hold the same lock in the same epoch. It can't guarantee that a client knows when its lease has ended, because the client measures time with its own clock and may be paused. There are three defences, in increasing strength:
- Conservative local expiry. The client assumes it lost the lease at
start + TTL − margin, measured with a monotonic clock from the moment before it sent the request. That handles clock drift, but not process pauses after the check. - Lock-delay. Chubby's paper describes a lock-delay: when a holder's session dies without a clean release, the server refuses to grant the lock to anyone else for a short period, up to a minute. That gives an in-flight request from the old holder time to drain. It reduces the risk but doesn't eliminate it.
- Sequencers, or fencing tokens. Chubby also issued sequencers, opaque strings encoding the lock name, mode and generation, which clients pass to servers that verify them. ZooKeeper's
czxidand etcd's revision fill the same role. This is the only defence that is correct under arbitrary pauses, because the check happens at the resource, at the time of the write.
A proof sketch of fencing. Tokens are issued in strictly increasing order, since zxids and revisions are totally ordered by consensus. The resource accepts a write with token t only if t ≥ the maximum token it has accepted, and records the new maximum atomically with the write. Suppose holder A (token a) and holder B (token b > a) both try to write after B has acquired the lock. If B writes first, A's write is rejected, because a < b. If A writes first, that write happened while the resource hadn't yet seen b, which is indistinguishable from A writing before B acquired the lock, a legitimate history. After B's write, A can never write again. So the resource's history is always equivalent to one where the lock was respected.
Two conditions are required:
- The check-and-write must be atomic at the resource: a conditional update, a compare-and-set, or a transaction.
- Every path that mutates the resource must carry a token.
The orphan-node problem. A client calls create("/locks/x/lock-", EPHEMERAL_SEQUENTIAL). The server creates lock-0000000042, but the connection drops before the client receives the response. On reconnect (same session), the client doesn't know its node's name. If it simply retries, it creates lock-0000000043, and now its own orphan ...42 sits ahead of it in the queue. It waits on itself forever, or blocks others until the session ends. Curator's protection mode fixes this by embedding a client GUID in the node name (_c_<guid>-lock-). On retry, it first lists the children to find a node carrying its GUID. etcd recipes avoid the problem by keying the node on the lease id, so a retry finds the same key. This is a good example of why hand-written recipes go wrong.
Lost and coalesced events. One-shot watches deliver "something changed", not a log of changes. A client that needs every transition, such as auditing each leadership change, must read the state on each event and compare. Even then, it can miss transitions that happened between reads (A → B → A looks like no change). Systems needing complete histories should use etcd's revisioned watch (until compaction), or record transitions in a real log such as Kafka.
Testing. Jepsen, Kyle Kingsbury's distributed systems testing project, has analysed both ZooKeeper (2013) and etcd (2014, and 3.4.3 in 2020). In the 2013 ZooKeeper analysis, ZooKeeper behaved as specified under partitions. The 2014 etcd analysis found stale reads, since addressed by making reads quorum-based. The 2020 analysis found etcd's KV operations strictly serializable, and stressed that its locks, like all lease-based locks, need fencing. Two lessons follow. Coordination services from mature projects are among the most rigorously tested software in distributed systems. And most production bugs live in the clients: ignored connection states, missing fencing, hand-written recipes, and the coordinator put on the hot path.
A checklist for a correct lock-protected operation:
- Acquire through a library recipe that has protection against orphans.
- Read the fencing token.
- Perform every mutation with a conditional write that checks the token.
- Treat SUSPENDED or keep-alive failure as "stop now".
- Make the operation idempotent, so a retry after an uncertain outcome is harmless.
- Release explicitly, relying on expiry only as the fallback.
- Alert on lock hold-time outliers.
Key Takeaways#
- ZooKeeper and etcd are small, strongly consistent coordination stores. They're for leaders, membership, configuration, shard maps and locks: kilobytes of data and thousands of writes per second, never application data.
- The core primitives are few. ZooKeeper has znodes (persistent, ephemeral, sequential) with versioned CAS and watches. etcd has keys with revisions, leases, transactions and streaming watches. Elections, locks, discovery and config are all recipes built on these.
- Ephemeral nodes and leases turn liveness into data. When a process's session or lease expires, its entries vanish and watchers are notified, so failure detection comes for free, bounded by the session timeout.
- Writes go through one leader and a majority quorum, ZAB for ZooKeeper and Raft for etcd. Use 3 or 5 voters across 3 AZs. Bigger ensembles slow writes, and reads scale with observers or learners.
- ZooKeeper reads are local and sequentially consistent (use
sync()for the latest value). etcd reads are linearizable by default through ReadIndex. - Lease- or session-based locks are safe only with fencing tokens checked atomically by the protected resource. Treat a suspended connection as lost leadership.
- Kafka replaced ZooKeeper with KRaft to run one system instead of two, and to make controller failover instant by storing metadata as a Raft-replicated log with hot standby controllers.
- Use a coordination service directly for smart routing (shard maps, not per-user data), infrastructure designs (queues, KV stores, schedulers, caches) and durable correctness-critical locks. Otherwise, name the component that embeds one, or use a Kubernetes Lease, a database lease, or Redis for efficiency locks.