Apache ZooKeeper
medium 30 minZooKeeper is a small, replicated, strictly ordered tree of notes that programs use to coordinate: who is the leader, who is alive, who holds a lock, what the settings are.
Video lesson · Chapter 1 of 5
Three dispatch offices change one timetable
ZooKeeper in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Programs on several machines must agree on small facts: which one is in charge, which ones are alive, which settings apply. Apache ZooKeeper is a service that keeps such facts in a tree of small nodes, called znodes, copied to several servers that agree on every change and its order.
It gives you few operations (create, delete, exists, get data, set data, get children, sync) and leaves leader election, locks and membership to short recipes built on them. It is open source, written in Java, under the Apache 2.0 licence.
Why it exists
Agreement is hard to write. Messages are late, machines pause, and two leaders at once can destroy data. ZooKeeper solves it once, so that other systems do not have to.
Its session gives failure detection for free: a program that stops talking loses its session, and everything it claimed with ephemeral nodes is released. Many systems of the Hadoop family were built on this.
A short history
2010
Four engineers of Yahoo publish "ZooKeeper: Wait-free coordination for Internet-scale systems" at the USENIX Annual Technical Conference, describing use in Yahoo's web crawler and other services.
2011, November
Version 3.4.0 is released. It adds, among other things, automatic purging of old snapshots and logs.
2019, May
Version 3.5.5 is released. The 3.5 line brings container and TTL nodes, dynamic reconfiguration and a whitelist for the four-letter commands.
2020, March
Version 3.6.0 is released, with watches that are not removed when they fire.
2025, March
Apache Kafka 4.0 ships as the first major release that runs entirely without ZooKeeper.
Words to know
- Znode
- A node of the tree. It can hold data and have children, like a file that is also a folder.
- Ensemble
- The group of ZooKeeper servers.
- Quorum
- A majority of the voting servers. Every change needs one.
- Session
- A client's relationship with the ensemble, kept alive by messages and ended by a timeout.
- Ephemeral
- Deleted when the session that created it ends.
- Watch
- A request to be told once about a change.
- zxid
- The number of a change: 32 bits of epoch and 32 bits of counter. It gives the total order.
How it works
Step through the idea, or press Play.
Open a session. A client connects to one server of the ensemble
Understand it
Start here
The bell-tower council
Imagine a council in a bell tower. Each member keeps the same notice board, and some notes are written so that they vanish when their writer leaves the square.
The sand timer matters: nobody knows at once that the baker left. They know when the timer runs out.
The idea
What it is, and what it is not
ZooKeeper is
- A tree of small notes with strict order
- Consistent: a minority side stops (CP in CAP terms)
- Failure detection through sessions
- Change notices through watches
- Building blocks for elections and locks
ZooKeeper is not
- A database: the tree must fit in memory
- A message queue: use Kafka or RabbitMQ
- A cache or general key-value store
- A health checker beyond "the session is alive"
- Fast across distant regions: each write waits for a majority
What people build with it
Leader election
Exactly one active scheduler or primary, with automatic takeover.
Locks
One worker at a time on a resource, released when the worker dies.
Service discovery and membership
Each instance registers an ephemeral node. Dead ones vanish from the list.
Configuration
One place for settings, with a watch instead of polling.
Barriers
Wait until everyone has arrived, then start together.
Data model
Znodes
Kinds of znode
| Kind | Lives until | Typical use |
|---|---|---|
| Persistent | Someone deletes it | /config/database |
| Ephemeral | Its session ends; it has no children | /services/api/host-1 |
| Persistent sequential | Someone deletes it; a counter is added to the name | Ordering |
| Ephemeral sequential | Its session ends; a counter is added | Elections and locks |
| Container | Its last child has gone, some time later | Parent of a lock |
| TTL | Not changed for its time and without children | Off by default; needs extendedTypesEnabled |
Each read and write of a znode is whole: you get all the data or replace all of it. A znode also has a version, so you can say "set this only if the version is still 4". Data must stay just under 1 MB (jute.maxbuffer, 1,048,575 bytes), and should be far smaller, typically bytes to a few kilobytes. Store a pointer, not the file. Access is controlled by an access control list per znode, which children do not inherit.
Architecture
The ensemble
Writes meet at the leader, reads stay local
Majority
Inside one server
Writes
How a change is agreed: ZAB
One write
The protocol is ZooKeeper Atomic Broadcast. Its papers describe phases called discovery, synchronization and broadcast; the product's own guide calls them leader activation and active messaging. A new leader must have seen the highest zxid of its quorum, so it holds every committed change. It then raises the epoch.
A zxid holds the order
Reads
Fast, ordered and perhaps old
What ZooKeeper promises
| Guarantee | Meaning |
|---|---|
| Writes are linearizable | All changes have one order that fits real time |
| Sequential consistency | One client's changes apply in the order sent, and it never sees time run backwards |
| Atomic | A change, also a multi, happens fully or not at all |
| Single image | The same view whichever server a client moves to |
| Timely | A client's view is at most tens of seconds old, or it notices that the service is gone |
| Not promised | Two clients reading at the same moment see the same thing |
sync before reading. See consistency models.The original paper measured a saturated system with 1 KB requests: 3 servers did 87,000 reads a second or 21,000 writes; 13 servers did 460,000 reads or 8,000 writes. Hardware has changed since 2010, but the shape has not: voting servers add read capacity and cost write speed.
Observers
- Receive every change, do not vote
- Add read capacity without slowing commits
- Can fail without hurting the quorum
- Give a distant site local reads
Their limits
- Reads may be a little older
- Writes still travel to the voting servers
- They do not add fault tolerance
- Attached to the leader unless you set an observer master port on followers
Liveness
Sessions and ephemeral nodes
Life of a session
The timeout you may ask for
Short timeouts find failures quickly and also punish a long garbage collection pause. Long ones do the opposite. Between the crash and the expiry the ephemeral node is still there, so a caller may be sent to a dead instance: retry. A session moves to another server with its id and password, so losing one server does not end it.
Notices
Watches
A standard watch fires once and is removed. The client reads again and sets a new watch in the same call. Between the event and the new watch several changes can happen; you see only the last state. So treat a watch as "look again", never as a log of changes. The event reaches a client before that client can see the new data.
A missed change that does no harm
Since 3.6 addWatch offers persistent watches, also recursive, which stay after firing. They still report that something changed; they do not replay history as an etcd watch does. Libraries such as Curator and Kazoo hide the re-registration.
Recipes
Leader election and locks
Both recipes are the same queue
- 1
Create
Make an ephemeral sequential znode under
/electionor/locks/order-123. Put a GUID in the name, so that after a lost reply you can find your own node. - 2
List
Get the children without a watch and sort by number.
- 3
Lowest?
If yours is the lowest, you are the leader or hold the lock.
- 4
Otherwise watch the one before you
Only that one. If it is already gone, list again.
- 5
Woken
List again before acting: the node before you may have left without ever being in charge.
- 6
Leave
Delete your node, or let the session end.
Why not watch the leader?
Read-write locks use two name prefixes, read and write: a reader waits for the nearest writer before it, a writer for whatever is just before it. Curator has these ready made.
Operate
Running an ensemble
Settings and limits (3.9)
| What | Value or advice |
|---|---|
| Versions | 3.9.7 is current, 3.8.8 is stable (November 2026); Java 8 or newer |
| Ports | 2181 clients, 2888 leader traffic, 3888 election, by convention |
| Log | Own device with dataLogDir; a warning appears when a sync takes more than 1 s |
| Memory | Heap above the tree, never swapping |
| Clean-up | Off by default: set autopurge.purgeInterval (hours); 3 snapshots are kept |
| Connections | 60 per client address and server (maxClientCnxns) |
| Four-letter commands | Only srvr is allowed by default; add others to 4lw.commands.whitelist |
| Admin server | HTTP on port 8080, path /commands |
| Changing members | Dynamic reconfiguration exists and is off until reconfigEnabled=true |
What to watch
| Signal | Meaning |
|---|---|
| Outstanding requests rising | The leader or a disk cannot keep up |
| Sync time of the log | The main part of write latency |
| Session expirations | Pauses, network trouble or too short timeouts |
| Watch and znode count, tree size | Someone is using it as a database |
| Followers in sync | How far you are from losing the quorum |
Costs to accept
Single leader
All writes pass one machine and several disks.
Everything in memory
Each server holds the full tree.
Another system
A Java service with its own tuning, upgrades and on-call.
Distance
Voting servers in far regions make every write slow.
Three servers in three zones survive one loss; five survive one loss during maintenance of another. Two zones cannot work: one of them holds the majority. If the ensemble stops, systems that need it lose their ability to elect and register, so design clients to continue with what they know.
Decide
When to choose it, and when not
Choose ZooKeeper
- You run HBase, Solr, Storm, HDFS failover or an older Kafka
- You need exactly one leader with automatic takeover
- Membership and locks for a Java system, with Curator
- Reads far outnumber writes
- Consistency matters more than being writable on both sides of a split
Choose something else
- Gigabytes of data
- More than some thousands of writes a second
- Messages or streams
- You run Kubernetes: use its Lease objects
- You want DNS and health checks: Consul
- You must see every change: etcd watches
Alternatives
| ZooKeeper | etcd | Consul | Redis | |
|---|---|---|---|---|
| Agreement | ZAB | Raft | Raft | Asynchronous replication |
| Data | Tree of znodes | Flat, ordered keys with history | Key-value plus a service catalogue | Data structures |
| Default read | Local, may be old | Linearizable | Through the leader, rarely stale | Local |
| Notices | Once, or persistent | Stream from a revision | Blocking queries | Pub/sub, lost if you are away |
| Liveness | Session | Lease | Health checks | Key expiry |
| Extra | Curator recipes | Built into Kubernetes | DNS, mesh, many sites | High throughput, large data |
Summary
The whole topic in one minute.
ZooKeeper keeps a small tree in the memory of every server. Writes go through one leader and a majority writes them to disk. Reads are answered by the server you are connected to, so they are fast and may be slightly old.
Sessions, ephemeral and sequential nodes and watches build elections, locks and membership. Use it where a system you run already needs it. For new coordination needs, etcd, Consul or a feature of your platform is usually simpler. Do not store data or queues in it.
- Small replicated tree, majority for writes, local reads that may be old.
- Ephemeral nodes vanish when the session ends, which takes the timeout to notice.
- Standard watches fire once: look again, do not count events.
- Elections and locks: lowest number wins, watch only the one before you, fence the resource.
- Not a database, not a queue.