How it works
ZooKeeper provides a hierarchical namespace of znodes with paths such as /services/payments/instance-1. Each znode holds a small byte payload, access controls, and metadata that includes a data version. Servers keep the data tree in memory and save changes through transaction logs and snapshots.
An ensemble contains voting servers, with one elected leader and the other servers as followers. Clients connect to any server. That server sends write requests to the leader. ZooKeeper uses Zab, its atomic broadcast protocol, to order transactions and replicate them through a quorum before it commits them.
Committed writes have one global order, with ZooKeeper transaction IDs called zxids. The connected server handles ordinary reads locally, so reads can miss writes that other servers committed. A client's view does not move backward across normal reconnections within a session. This does not make every read globally current.
A client session survives a temporary connection loss if the client reconnects before the negotiated session timeout expires. Ephemeral znodes belong to the session. ZooKeeper removes them when the session expires or closes. A missed heartbeat does not immediately remove them. Thus, membership changes are delayed failure signals, not proof that a process stopped.
Clients register watches to learn when a znode or its children change, then read the authoritative state again. Traditional watches give one notification, not a durable stream of every update. ZooKeeper also supports observers that do not vote. Observers serve clients and receive committed changes without a larger voting quorum.
What it gives you in a design
- Leader election
- Ephemeral sequential znodes give application leader candidates an order. Each candidate can watch the candidate immediately before it instead of all candidates watching the current leader.
- Distributed lock recipes
- Ordered ephemeral candidates support patterns for exclusive ownership. Also protect external resources with fencing tokens, because a former lock holder can remain active after its lock expires.
- Session-bound membership
- Services can publish ephemeral registration nodes that ZooKeeper removes after the session expires. Consumers must accept delayed removal and still handle connection failures to registered endpoints.
- Versioned conditional updates
- Updates and deletes can require an expected znode version for compare-and-set behavior. This prevents one controller from replacing another controller's change without notice.
- Atomic multi-operation transactions
- The multi API can combine checks and changes atomically across znodes within one ensemble. It does not extend atomicity to an application database, a message broker, or an external API.
- Change notifications
- Watches let clients keep local copies of configuration or membership without continuous polls. Clients must reconcile state after notifications and connection changes. Notifications do not give a complete history.
Scaling, replication and failure
ZooKeeper replicates the full namespace across the ensemble instead of sharding it among voting servers. Its design supports small coordination state. Namespace size, connection count, watch count, and write volume all affect capacity.
Writes pass through one leader and require a voting quorum. More voters increase failure tolerance at certain ensemble sizes. They do not divide write work and they add replication overhead. Observers can handle client connections and reads without a larger voting quorum.
With the usual majority configuration, three voters tolerate one unavailable voter and five tolerate two. A partition without a voting majority cannot commit writes. Normal service requires a functional quorum. Optional read-only mode can expose stale local data. Do not use this mode to authorize exclusive ownership.
Place voters across failure domains with reliable links that have low latency. Voters across regions increase coordination latency, and regional connection failures can disrupt service. Pause work that depends on ownership during elections or quorum loss. After session expiration, rebuild state that the session owned. Do not assume that previous locks still belong to the client.
Limits and defaults to know
Many of these values are configurable. Check the current documentation before you use an exact value.
| Payload size | Keep znode data small. The default jute.maxbuffer serialization limit is approximately 1 MiB. Request overhead also matters. Do not treat this limit as a safe application payload allowance. |
|---|---|
| Session timeout bounds | Unless configuration overrides these values, the server's minimum session timeout is 2 × tickTime and its maximum is 20 × tickTime. The client requests a timeout, and the server negotiates it within the configured bounds. |
| Majority quorum | Under the usual majority configuration, at least 2f + 1 voters are necessary to tolerate f unavailable voting servers. Observers do not count toward that quorum. |
| Ephemeral node children | Ordinary ephemeral znodes cannot have children. Their lifetime follows the session that owns them, not a separate TTL configured for each node. |
| Watch behavior | Traditional watches give one notification and require registration again. ZooKeeper 3.6.0 and later versions support persistent and persistent recursive watches. |
Use it when
- Several controllers must agree on which instance currently owns a shard, partition, or background task.
- A design needs small, shared coordination metadata with ordered writes and conditional updates.
- Service membership must follow client sessions, and the design accepts delayed failure detection.
- Applications can cache coordination state locally instead of contacting ZooKeeper for every user request.
Avoid it when
- The workload consists of application records, large objects, telemetry, or an event stream with high throughput.
- Every request requires a globally current read from any replica without extra coordination.
- Independent regions must continue to change the same ownership state during a network partition.
- An existing database transaction or a lease native to the platform already provides the required coordination with less operational complexity.
What interviewers ask about it
When ZooKeeper is on your whiteboard, expect these follow-up questions. Each answer gives the core of a strong answer.
- How does ZooKeeper prevent two application leaders from writing at once?
- ZooKeeper can select one current owner. It cannot stop a paused or partitioned former owner from continuing external work. Issue a fencing token that increases with each ownership grant. Require the protected storage or service to reject older tokens.
- Are ZooKeeper reads strongly consistent?
- ZooKeeper orders all writes globally, but ordinary reads use the connected replica and can return stale data. Explain how fresh the operation needs the data to be. Use conditional writes or a suitable synchronization protocol. Do not treat a local read as proof of current ownership.
- What happens when the client loses its connection?
- Connection loss alone does not expire the session or immediately delete its ephemeral znodes. Stop actions that depend on ownership while disconnected. If the session expires, obtain a new session and acquire ownership again before you resume.
- How do you implement a lock without a notification to every client that waits?
- Create an ephemeral sequential contender. Acquire the lock when the contender has the lowest sequence number. Otherwise, watch only its immediate predecessor. Handle the race where the predecessor disappears before you set the watch.
- What happens if a write times out and the client does not know whether it succeeded?
- A connection error can leave the result unknown. The server may have committed the write before the response was lost. Check the result with an operation identifier, known path, or expected version before you retry. A sequential create can produce duplicate contenders if you retry without this check.
- Can watches replace an event log?
- No, watches indicate a possible state change. They do not preserve every intermediate update. Read the current state again and reconcile it after notifications. Set traditional watches again. Use a durable log when you need replay or a complete event history.
Common mistakes
- The design requires ZooKeeper access for every request instead of keeping coordination separate from the path that serves data.
- The design treats a session timeout as proof that the former owner stopped and omits fencing at the protected resource.
- The design assumes that every replica read is globally current or that a watch reports every state change.
- The design adds voting servers to increase write capacity, although the ensemble still has one ordered write stream.
Alternatives
- etcd
- Choose it for a coordination key-value API with explicit linearizable reads, transactions, leases, and revision-based watches. This is especially useful when the surrounding platform already operates it.
- Consul
- Choose it when service discovery, health checks, and service network functions are the main requirements. These requirements go beyond a low-level coordination namespace.
- Relational database
- Use conditional updates, unique constraints, advisory locks, or lease rows when coordination closely relates to data already in that database. The database must have sufficient capacity.
- Kubernetes Lease objects
- Use them for controller leader election inside Kubernetes when its API and existing leader-election libraries meet the requirements. External side effects still need protection against stale leaders.
Where it is used
ZooKeeper is a good fit for these interview questions. Each line tells you why.
- Design a control plane for a distributed databaseZooKeeper can coordinate controller leadership and ownership metadata. Fencing protects databases from stale failover controllers.
- Design a distributed message log like KafkaIt can hold broker membership and partition leadership metadata. Message payloads remain in the replicated log.
- Design a distributed job schedulerIt can elect a scheduler leader. Dispatch and job side effects still require durable state and execution that remains safe after retries.
- Design a distributed cacheIt can coordinate cache membership and ownership epochs without involvement in every cache read or write.
- Design a distributed message queue like RabbitMQIt can coordinate queue-node ownership and leader election. Do not use it as the storage path for large volumes of queue messages.
Common questions
What is ZooKeeper architecture?
ZooKeeper runs as a replicated ensemble with a leader, voting followers, and optional non-voting observers. The leader orders writes through Zab and commits them through a quorum. Connected servers serve reads from their local copies of the znode tree.
Why does ZooKeeper usually use an odd number of servers?
With majority voting, an odd number provides better failure tolerance per server. Three voters tolerate one failure. Four voters still tolerate only one failure. Five voters tolerate two failures. This calculation excludes observers.
Is ZooKeeper a database or a service discovery tool?
ZooKeeper is a coordination service with a small hierarchical data store. Service discovery is one use. Instances publish ephemeral registrations, and clients watch membership. ZooKeeper is not a general-purpose database. It is not a complete system for health checks and traffic routing.