AlgoViz

Apache ZooKeeper

medium 30 min

ZooKeeper 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

0:00 / 4:52

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

  1. 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.

  2. 2011, November

    Version 3.4.0 is released. It adds, among other things, automatic purging of old snapshots and logs.

  3. 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.

  4. 2020, March

    Version 3.6.0 is released, with watches that are not removed when they fire.

  5. 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.

Step 1 of 3

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.

Notes that vanish

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

KindLives untilTypical use
PersistentSomeone deletes it/config/database
EphemeralIts session ends; it has no children/services/api/host-1
Persistent sequentialSomeone deletes it; a counter is added to the nameOrdering
Ephemeral sequentialIts session ends; a counter is addedElections and locks
ContainerIts last child has gone, some time laterParent of a lock
TTLNot changed for its time and without childrenOff by default; needs extendedTypesEnabled
The counter has ten digits, for example 0000000001, and belongs to the parent.

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

A writer and a reader both connect to follower 1. The create request is forwarded to the leader, which proposes it to follower 2 and informs an observer outside the voting group. The read is answered by follower 1.
A client is connected to one server at a time and needs to know several addresses.

Majority

Q=⌊N2⌋+1f=N−QN=3:Q=2,f=1N=4:Q=3,f=1N=5:Q=3,f=2Q = \left\lfloor\frac{N}{2}\right\rfloor + 1 \qquad f = N - Q \qquad N{=}3: Q{=}2, f{=}1 \quad N{=}4: Q{=}3, f{=}1 \quad N{=}5: Q{=}3, f{=}2
ff is how many voting servers may fail. A fourth server adds work and no safety, which is why ensembles have 3, 5 or 7.

Inside one server

Inside one ZooKeeper server: request handling reads from the whole tree in memory. Writes go to a transaction log on its own disk and are synced before the acknowledgement, then applied to memory. Snapshots are written to a second disk now and then.
The log deserves its own device. By default a snapshot is taken after 50,001 to 100,000 changes, at random, so servers do not all do it together.

Writes

How a change is agreed: ZAB

One write

Follower 2 may be slow; the write does not wait for it. Watches fire as each server applies the change.

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

zxid=epoch⋅232+counter0x0000000100000005→epoch 1, change 5zxid = epoch \cdot 2^{32} + counter \qquad \texttt{0x0000000100000005} \rightarrow epoch\ 1,\ change\ 5
An old leader that wakes up proposes with an old epoch and is ignored. That prevents two leaders from both changing data. Compare Raft's term in etcd.

Reads

Fast, ordered and perhaps old

What ZooKeeper promises

GuaranteeMeaning
Writes are linearizableAll changes have one order that fits real time
Sequential consistencyOne client's changes apply in the order sent, and it never sees time run backwards
AtomicA change, also a multi, happens fully or not at all
Single imageThe same view whichever server a client moves to
TimelyA client's view is at most tens of seconds old, or it notices that the service is gone
Not promisedTwo clients reading at the same moment see the same thing
If A writes and then tells B by another path, B should call 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

A client that is disconnected does not know whether it has expired. It learns that only after reconnecting.

The timeout you may ask for

2⋅tick≤timeout≤20⋅ticktick=2 s⇒4 s≤timeout≤40 s2 \cdot tick \le timeout \le 20 \cdot tick \qquad tick = 2\,s \Rightarrow 4\,s \le timeout \le 40\,s
The server adjusts your request into this range. The client sends a heartbeat after a third of the timeout without traffic and tries another server after two thirds.

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

A never saw 2. It ends with the right value.

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. 1

    Create

    Make an ephemeral sequential znode under /election or /locks/order-123. Put a GUID in the name, so that after a lost reply you can find your own node.

  2. 2

    List

    Get the children without a watch and sort by number.

  3. 3

    Lowest?

    If yours is the lowest, you are the leader or hold the lock.

  4. 4

    Otherwise watch the one before you

    Only that one. If it is already gone, list again.

  5. 5

    Woken

    List again before acting: the node before you may have left without ever being in charge.

  6. 6

    Leave

    Delete your node, or let the session end.

Why not watch the leader?

Waking everybody at once is the herd effect, a relative of the thundering herd.

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)

WhatValue or advice
Versions3.9.7 is current, 3.8.8 is stable (November 2026); Java 8 or newer
Ports2181 clients, 2888 leader traffic, 3888 election, by convention
LogOwn device with dataLogDir; a warning appears when a sync takes more than 1 s
MemoryHeap above the tree, never swapping
Clean-upOff by default: set autopurge.purgeInterval (hours); 3 snapshots are kept
Connections60 per client address and server (maxClientCnxns)
Four-letter commandsOnly srvr is allowed by default; add others to 4lw.commands.whitelist
Admin serverHTTP on port 8080, path /commands
Changing membersDynamic reconfiguration exists and is off until reconfigEnabled=true

What to watch

SignalMeaning
Outstanding requests risingThe leader or a disk cannot keep up
Sync time of the logThe main part of write latency
Session expirationsPauses, network trouble or too short timeouts
Watch and znode count, tree sizeSomeone is using it as a database
Followers in syncHow 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

ZooKeeperetcdConsulRedis
AgreementZABRaftRaftAsynchronous replication
DataTree of znodesFlat, ordered keys with historyKey-value plus a service catalogueData structures
Default readLocal, may be oldLinearizableThrough the leader, rarely staleLocal
NoticesOnce, or persistentStream from a revisionBlocking queriesPub/sub, lost if you are away
LivenessSessionLeaseHealth checksKey expiry
ExtraCurator recipesBuilt into KubernetesDNS, mesh, many sitesHigh throughput, large data
For discovery in general see service discovery. A Redis lock is fine for efficiency and not for correctness.

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.

Sources