Skip to content

ZooKeeper: coordination from first principles

Phase 6 · Distributed systems · 60 min read

So, you want three copies of your scheduler for safety, but the nightly billing job must run once. Or you want a hundred chat servers that find each other without a hand-edited list. Most tutorials answer with a command: "put it in ZooKeeper". They rarely say what problem that command solves, or where it stops solving it.

This lesson builds ZooKeeper from the failures that force it to exist, then works through use cases and production problems with solutions.

1 · Why the naive answers break

You have three scheduler processes, A, B and C. Exactly one should run jobs. Try the obvious ideas first.

Attempt 1: a config flag. Write leader=A in a file. It works until A dies. Now a human must edit the file at 3 a.m.

Attempt 2: a database row. The first process to insert leader wins. When A crashes, the row stays forever. Nobody can tell a dead leader from a quiet one.

Attempt 3: a row with an expiry time. A renews every few seconds; if it stops, B takes over. Better, but the database is now a single point of failure. If you replicate it with asynchronous replication, a failover can forget that A holds the lease and hand it to B too.

Attempt 4: the processes vote by pinging each other. If the network splits A away from B and C, A cannot tell "they died" from "I am cut off". Both sides may elect a leader. This is split brain.

Each failure names a requirement:

What broke What we need
Human edits a file Automatic failure detection
Row stays after a crash Ownership that disappears with its owner
One database dies The record is replicated and survives failures
Two leaders A majority decides, so two sides cannot both win
Others do not know the leader changed Notifications
An old leader wakes up late A growing number that lets storage reject it

ZooKeeper is a small replicated store built to give you exactly these six things. Kleppmann describes it as outsourced consensus, failure detection and membership: much better than writing your own consensus algorithm.

A lease in one database: the paused owner wakes up and overwrites newer data.

2 · The registry office

Picture a town registry office. We will use this picture for the whole lesson.

Registry office ZooKeeper Why it matters
The registry book, organised in folders znode tree Small facts everyone must agree on
A panel of clerks, each with a full copy of the book ensemble The book survives a lost clerk
The chief clerk who orders all new entries leader One order for all changes
An entry is official once most clerks signed it quorum Two halves cannot both be official
A visitor badge that lapses if you stop checking in session Detects silent visitors
A pencil entry erased when your badge lapses ephemeral znode Ownership dies with the owner
A numbered ticket dispenser sequential znode A queue with no ties
"Ring my bell once if this page changes" watch No polling
The stamp number on every change zxid Tells old from new

Where the picture stops being accurate: a real clerk can check your face. ZooKeeper cannot check whether your process is still doing work. It only knows whether it heard from you recently. Most hard problems in this lesson come from that gap.

3 · Znodes: the book

ZooKeeper stores a tree of znodes. A znode looks like a file that can also have children. It holds a small blob of bytes and some metadata.

A typical tree. Dashed boxes are ephemeral: they vanish when the owner session ends.
Type Lifetime Typical use
Persistent Until someone deletes it Configuration, parent folders
Ephemeral Until the creating session ends. Cannot have children Membership, locks, leader
Persistent sequential Until deleted; name gets a counter Ordered task list
Ephemeral sequential Session; name gets a counter Lock queue, election
Container (3.5.3+) Server may delete it some time after its last child goes Parent of locks, so empty folders do not pile up
TTL (3.5.3+) Persistent node removed after a time limit. Off unless zookeeper.extendedTypesEnabled=true Rarely needed

Facts that bite later:

  • Sequence numbers are 10 digits, zero padded, and unique per parent. The counter is a signed 32-bit integer, so it can wrap around.
  • The whole data set is held in memory on every server and logged to disk. Keep each znode in the kilobyte range. The default limit (jute.maxbuffer) is just under 1 MB, and it also applies to large responses such as listing a huge folder.
  • Every znode has a version. A write can say "only if the version is still 3". That is a compare-and-set, and it is how you avoid lost updates.
  • multi (a transaction) applies several operations atomically: all succeed or none do.
data, stat = zk.get("/config/limits")
zk.set("/config/limits", b"rate=200", version=stat.version)   # BadVersionError if someone wrote first

Rule of thumb

Store who owns what and where to look, not the thing itself. A 50 MB model file belongs in object storage; ZooKeeper holds its address.

4 · Quorum: when is an entry official?

A single clerk can lose the book. So several servers, the ensemble, each keep a copy. One is the leader, the others are followers.

A client connects to any one server. Reads are answered by that server from its own copy. Writes are forwarded to the leader, which proposes the change, waits for a majority to log it, then commits.

Follow the numbers: a write goes through the leader and needs a majority; a read stays local.

The protocol is called ZAB (ZooKeeper Atomic Broadcast). It has two modes: leader activation, where a new leader is elected and a quorum syncs with it, and active messaging, where the leader sends proposals, collects acknowledgements and commits, in order.

Every change gets a zxid, a 64-bit number. The high 32 bits are the epoch (it increases with each new leader) and the low 32 bits count changes. A later change always has a larger zxid. Remember this; it becomes a safety tool in section 6.

Interactive 3D figure (needs WebGL and a network connection). Kill servers one at a time, then try size 4 and size 6. Watch when writes stop.
Kill servers one at a time, then try size 4 and size 6. Watch when writes stop.
Servers Majority Failures tolerated
1 1 0
3 2 1
4 3 1
5 3 2
6 4 2
7 4 3

Two consequences. First, use an odd number: the fourth server adds cost and no extra tolerance. Second, adding voters does not make writes faster, because every write needs more signatures. To serve more readers without slowing writes, add observers: servers that receive committed changes and answer reads but do not vote.

5 · Consistency: what a reader may see

The official guarantees are:

Guarantee Plain meaning
Sequential consistency One client's updates apply in the order it sent them
Atomicity An update fully happens or does not
Single system image A client does not go back in time when it reconnects to another server
Reliability An applied update stays until overwritten
Timeliness A client's view catches up within a bounded time

Notice what is missing: "every read returns the latest write". Writes are linearizable, but a read is served locally and may be stale.

Client B reads from a follower that has not applied the change yet.

Your own writes are visible to you, because your session sees changes in order. Another client may lag. If it must read fresh data, call sync on the path before reading:

zk.sync("/config/limits")            # ask my server to catch up with the leader
data, stat = zk.get("/config/limits")

sync narrows the window a lot, but the project documents note that it is not itself a quorum operation, so in rare leader-change cases it is not a strict guarantee. When a decision must be safe, do not rely on a fresh read. Make the write conditional: use the version check, or multi, so a stale view simply fails.

6 · Sessions, ephemerals and the late leader

A client opens a session and sends heartbeats (pings). The client asks for a timeout; the server negotiates it between 2 and 20 times tickTime. With tickTime=2000 ms that is 4 to 40 seconds.

The cluster decides when a session expires, not the client. When it does, all ephemeral znodes of that session are deleted and watchers are told.

Client state Meaning What your code should do
Connected Heartbeats flow Work normally
Disconnected (Curator and kazoo: SUSPENDED) Link lost. The session may still be alive Pause anything that needs ownership. Do not create a new session
Expired (LOST) The cluster ended the session. Ephemerals are gone Assume you own nothing. Rebuild: new session, re-register, compete again

The nasty detail: an expired client learns this only after it reconnects.

Now the classic disaster. A holds the lock, then freezes for 30 seconds (a garbage-collection pause, swapping, a paused virtual machine). Its session expires. B acquires the lock and starts writing. A wakes up, still believes it is leader, and writes too. A frozen process cannot check anything while frozen, and it may be halfway through a write when it wakes.

Interactive 3D figure (needs WebGL and a network connection). Fencing is off: watch the old leader overwrite newer data. Then switch fencing on.
Fencing is off: watch the old leader overwrite newer data. Then switch fencing on.

The fix is a fencing token: a number that grows with each new owner. The owner sends it with every write, and the storage rejects any token lower than one it has already seen. In ZooKeeper, the czxid (creation zxid) of the lock or leader znode works well, because a later owner always created its node later.

A new owner should write its token to the resource before it does other work. From that moment every older token is blocked.

UPDATE billing_state
SET    total = :total, fence = :token
WHERE  id = :id AND fence <= :token;     -- 0 rows updated means: you are stale, stop

A lock alone is not safety

The resource must check the token. Checking "do I still hold the lock?" in the client is not enough, because the pause can happen between the check and the write.

Hardening a leader: follow the orange numbers, starting with the fencing check.

Choosing the timeout. A short timeout detects crashes fast but expires healthy clients during pauses or network hiccups. A long one is calm but slow to fail over: a crashed leader is not replaced until its timeout passes. Start from the longest pause you observe in production, add a margin, then check the resulting failover time is acceptable.

7 · Watches: the bell that rings once

Polling "who is leader?" every 100 ms from a thousand clients wastes the cluster. A watch asks the server to notify you when something changes.

Set by Fires on
exists node created, deleted, data changed
getData node deleted, data changed
getChildren node deleted, child list changed
One watch gives one notification; an expired session is learned only after reconnecting.

Rules:

  • A classic watch fires once. To keep watching, read again with a new watch.
  • Changes made between the event and your next read are not delivered one by one. You see the latest state, not the history. Design handlers to compare state, never to count events.
  • You will see the watch event before you see the new data.
  • While disconnected, no watches fire. On reconnect they are re-registered and fire if needed. A node created and deleted entirely during the gap can be missed.
  • Version 3.6 added persistent and recursive watches (addWatch) that stay registered.
def refresh(event=None):
    data, stat = zk.get("/config/limits", watch=refresh)   # read and re-arm in one call
    apply(data)

Libraries hide the re-arming: kazoo has DataWatch and ChildrenWatch, Curator has caches.

8 · Hands-on in ten minutes

8.1 Try it first, then peek: start one server and poke the tree
docker network create zknet
docker run -d --name zk --network zknet zookeeper:3.9
docker run -it --rm --name cli --network zknet zookeeper:3.9 zkCli.sh -server zk:2181

create /app ""
create -e /app/worker "w1"
create -s /app/task- "bill"
create -s /app/task- "mail"
ls /app
get -s /app
get -w /app
set /app "v2"

What you should see: the two task- nodes end in increasing 10-digit numbers. get -s prints czxid, mzxid, dataVersion and ephemeralOwner. After set, the watch prints a NodeDataChanged event once; a second set stays silent.

Break it: open a second shell with docker exec -it zk zkCli.sh and run ls /app. Type quit in the first one: worker disappears at once, because the session closed cleanly. Start the first client again, recreate worker, then crash it with docker kill cli: worker stays until the session times out.

9 · Use cases, with solutions

Examples use the Python library kazoo. On the JVM, use Apache Curator, which ships the same recipes (LeaderLatch, LeaderSelector, InterProcessMutex, service discovery). Prefer a library recipe over your own: the edge cases are real.

9.1 Leader election: three schedulers, exactly one runs jobs

Ideas to cover: ephemeral sequential nodes, watch the predecessor, suspended state, fencing.

Naive: everyone tries to create /leader and watches it. It is correct, but when the leader dies every candidate wakes up and retries at once: the herd effect.

Solution: each candidate creates an ephemeral sequential node under /election. The lowest number leads. Everyone else watches only the node just before its own.

Election with ephemeral sequential nodes. It is not yet safe against a paused leader.

import threading
from kazoo.client import KazooClient, KazooState

zk = KazooClient(hosts="zk1:2181,zk2:2181,zk3:2181", timeout=10.0)
may_work = threading.Event()
may_work.set()

def on_state(state):                      # must not block
    if state == KazooState.CONNECTED:
        may_work.set()
    else:                                 # SUSPENDED or LOST: stop touching shared data
        may_work.clear()

zk.add_listener(on_state)
zk.start()

def lead():
    while may_work.is_set():
        run_one_job()                     # keep jobs short and idempotent

while True:
    zk.Election("/election/scheduler", "host-a").run(lead)   # blocks until we are leader
    may_work.wait()

Still needed: a paused leader can resume mid-job. Pass a fencing token to the storage (use case 9.2), or make jobs idempotent with a unique job run id.

Interactive 3D figure (needs WebGL and a network connection). Watch the wake-up counter. Then switch from watching one node to watching the predecessor.
Watch the wake-up counter. Then switch from watching one node to watching the predecessor.
9.2 Distributed lock that protects a file or a table

Ideas to cover: lock queue, GUID on create, czxid as fencing token, resource-side check.

Each waiter watches only the node ahead of it, and the storage checks the token.

Algorithm: create an ephemeral sequential node; list children without a watch; if yours is lowest you hold the lock; otherwise call exists with a watch on the next lower node, wait, and list again. Unlock by deleting your node.

lock = zk.Lock("/locks/report", identifier="host-a")
with lock:
    token = zk.exists(f"/locks/report/{lock.node}").czxid    # grows with each new holder
    storage.write(report, fence=token)                       # storage rejects older tokens

Subtle bug: the server creates your node, then the connection drops before you get the name. A blind retry creates a second node, and you wait on your own orphan. The fix is to put a unique id in the node name and, after a connection error, search the children for it before creating again. Library recipes do this.

guid = uuid.uuid4().hex                  # import uuid
# create("/locks/report/" + guid + "-lock-", ephemeral=True, sequence=True)
# on ConnectionLoss: children = get_children(); reuse the child that starts with guid

Ask yourself first: is the lock for efficiency (avoid doing work twice) or for correctness (two writers corrupt data)? Correctness needs the fencing check. If your database can enforce it with a unique key or a conditional update, you may not need a distributed lock at all.

9.3 Service discovery: chat servers that find each other

Ideas to cover: ephemeral registration, client-side cache, re-register after expiry, stale reads are fine here.

Servers register ephemeral nodes; clients keep a local copy and connect directly.

import json
from kazoo.exceptions import NoNodeError, NodeExistsError

PATH = "/services/chat/" + instance_id

def register():
    payload = json.dumps({"host": host, "port": port}).encode()
    try:
        zk.create(PATH, payload, ephemeral=True, makepath=True)
    except NodeExistsError:
        stat = zk.exists(PATH)
        if stat and stat.ephemeralOwner != zk.client_id[0]:   # left over from my old session
            zk.delete(PATH)
            zk.create(PATH, payload, ephemeral=True)

lost = False
def on_state(state):
    global lost
    if state == KazooState.LOST:
        lost = True
    elif state == KazooState.CONNECTED and lost:
        lost = False
        zk.handler.spawn(register)        # ephemerals are gone, publish again

servers = []

@zk.ChildrenWatch("/services/chat")
def refresh(names):
    global servers
    found = []
    for name in names:
        try:
            found.append(json.loads(zk.get("/services/chat/" + name)[0]))
        except NoNodeError:
            pass
    servers = found                       # keep serving from this copy if ZooKeeper is unreachable

Add register() after zk.start() and attach on_state as a listener. Delete-and-recreate assumes instance ids are unique.

Design notes:

  • An ephemeral node proves the process talks to ZooKeeper, not that it can serve requests. Clients still need timeouts and health checks.
  • Discovery does not strictly need consensus; a slightly stale list is acceptable. DNS or a dedicated registry can be enough. ZooKeeper makes sense when you already run it.
  • After a network blip many servers may drop out at once. Do not let clients react by removing every backend; keep the last good list if the new one looks implausibly small.
9.4 Live configuration: change a rate limit without redeploying

Ideas to cover: DataWatch, validation, last good value, version check, size limit.

current = load_defaults()

@zk.DataWatch("/config/api/limits")
def on_config(data, stat):
    global current
    if data is None:
        return                            # missing node: keep what we have
    try:
        current = validate(json.loads(data))
    except ValueError:
        log.error("bad config at version %s, keeping previous", stat.version)

def change(update):
    data, stat = zk.get("/config/api/limits")
    new = update(json.loads(data))
    zk.set("/config/api/limits", json.dumps(new).encode(), version=stat.version)

Risks and fixes:

Risk Fix
A bad value reaches every server at once Validate on write and on read; roll out through a canary path first
Two admins overwrite each other Version check, retry on BadVersionError
Several keys must change together One znode for the group, or multi
Every server reloads at the same moment Add a small random delay before applying costly changes
Config is large Store it elsewhere; keep a pointer and checksum in ZooKeeper
9.5 Assign 64 shards to a changing set of workers

Ideas to cover: membership by ephemerals, one coordinator, assignment in one znode, epoch plus compare-and-set, rebalance damping.

This is the stateful load-balancing problem: someone must decide who owns what. See also partitioning.

  1. Each worker creates an ephemeral node under /group/members.
  2. Workers elect one coordinator (use case 9.1).
  3. The coordinator watches members, computes an assignment and writes it to /group/assignment.
  4. Workers watch that node, stop shards they lost, then start shards they gained.

One coordinator publishes the plan; workers watch it and apply it.

from kazoo.exceptions import BadVersionError

def publish(plan, my_epoch):              # my_epoch = czxid of my leader node
    data, stat = zk.get("/group/assignment")   # created once with the value {}
    if json.loads(data).get("epoch", 0) > my_epoch:
        return False                      # a newer coordinator exists
    body = json.dumps({"epoch": my_epoch, "plan": plan}).encode()
    try:
        zk.set("/group/assignment", body, version=stat.version)
        return True
    except BadVersionError:
        return False                      # someone wrote between my read and my write

A new coordinator should publish as soon as it is elected, and workers should ignore any plan whose epoch is lower than one they have already seen.

Risks and fixes:

  • Rebalance storm: a restarting worker triggers two full rebalances. Wait a short grace period before reassigning, and move as few shards as possible.
  • Two owners during handover: require an acknowledgement from the old owner, or fence shard writes with the epoch.
  • Cascading failure: slow workers get expired, their load moves, more workers slow down. Limit how many shards move per step, and stop automatic moves if too many members vanish together.
9.6 Barrier: start a distributed training job only when all workers are ready

Ideas to cover: double barrier, entry and exit, worker that never arrives.

A double barrier makes N processes begin together and finish together.

barrier = zk.DoubleBarrier("/jobs/train-42", num_clients=8)
barrier.enter()          # returns once 8 workers have arrived
try:
    train_one_epoch()
finally:
    barrier.leave()      # returns once every worker has left

Risks: if the eighth worker never starts, seven wait forever. Run the job under a supervisor with a deadline. If a worker dies, its ephemeral node goes away, which can let others proceed with fewer members than expected: check the member count and the job generation before trusting the result.

Do not use ZooKeeper to synchronise every training step. That is far too frequent; use the framework's collective operations.

9.7 Task queue: can ZooKeeper be one?

Ideas to cover: recipe exists, why it scales badly, what to use instead.

The recipe: producers create sequential nodes, consumers take the lowest. kazoo offers Queue and LockingQueue.

It is fine for a handful of low-rate control tasks. It breaks down as a general queue: every write goes through one leader and a quorum, the data lives in memory, listing a huge child set can exceed the response size limit, and consumers contend on the same head.

Use instead: a message broker or log such as Kafka or RabbitMQ, or a database table with row locking. See queues and streams. Keep ZooKeeper for deciding who consumes, not for carrying the messages.

9.8 Chat system: should ZooKeeper store which server each user is on?

Ideas to cover: write rate, memory, slow-changing data, hybrid design.

No. With a million connected users who reconnect often, that mapping changes constantly. Every change would be a quorum write through one leader, and the whole map would sit in memory on each server. ZooKeeper is meant for data that changes on the scale of minutes or hours.

Data Changes Where it belongs
Which chat servers are alive Rarely ZooKeeper (ephemeral nodes)
Which server owns which user range Rarely ZooKeeper
User to server mapping Constantly A fast key-value store, or computed by hashing
Message history Constantly, large A durable database
Presence heartbeats Very often A presence service with its own store

10 · Production problems, with solutions

10.1 Sessions keep expiring although the servers look healthy

Ideas to cover: pauses on client and server, swap, disk, network, timeout.

Look at both ends.

Cause How to confirm Fix
Client garbage-collection pause GC logs on the client Tune memory; move heavy work off the process; raise the timeout if justified
Server swapping Swap activity on the host Do not swap: set the heap well below physical memory (about 3 GB on a 4 GB machine)
Slow disk on servers Rising latency, slow fsync warnings Put the transaction log on its own device (dataLogDir)
Client callback blocks the library Thread dump Never block in listeners; hand work to another thread
Network loss between zones Packet loss metrics Fix the path; place servers sensibly

Raising the timeout hides symptoms and slows failover. Find the pause first.

10.2 Writes became slow

Ideas to cover: fsync, leader, voters, write volume.

Every write waits for a majority to flush it to disk. Check in this order: disk latency on the leader and followers; whether the transaction log shares a device with other work; write rate (is some application using ZooKeeper as a database?); number of voters (move extra servers to observers); network latency between voters.

10.3 CPU and network spike whenever a node disappears

Ideas to cover: herd effect, watch counts, huge folders.

Thousands of clients watch the same node, so one change triggers thousands of notifications and re-reads. Watch only the predecessor for locks and elections. For shared state, add random delay before re-reading, shard large groups into several parents, or put a cache service between ZooKeeper and the crowd.

10.4 A client fails with a packet-length error when listing a folder

Ideas to cover: response size limit, design fix.

The child list or data in one response exceeded jute.maxbuffer. Raising it works only if you set the same value on all servers and clients, and it moves you further from what the system is designed for. Better: split into buckets such as /tasks/00 to /tasks/63, delete finished nodes, and store large values elsewhere.

10.5 A create call failed with ConnectionLoss. Did it happen?

Ideas to cover: unknown outcome, idempotent design.

You cannot know. The server may have applied it. For a fixed name, retry and treat NodeExists as success only after checking that the node is yours. For sequential names, include a unique id and search the children. For set, a retry with a version check may return BadVersion because your first attempt succeeded: read the data and compare.

10.6 The disk is filling up

Ideas to cover: snapshots, logs, autopurge.

Servers keep transaction logs and snapshots. Automatic purge is disabled by default (autopurge.purgeInterval=0). Enable it:

autopurge.snapRetainCount=3
autopurge.purgeInterval=24

Keep separate backups if you need history; alert on free disk space.

10.7 Two of three servers are down. What now?

Ideas to cover: no quorum, do not wipe data, restore carefully.

Without a majority there is no leader, so no writes, and by default the survivor does not serve normal reads either. This is deliberate: consistency over availability.

  1. Bring the failed servers back with their original data directories. This is by far the safest path.
  2. If one is lost for good but another returns, you have 2 of 3 again; then replace the third with an empty server that syncs from the leader.
  3. Do not start empty servers that could outvote the one holding data, and do not turn the survivor into a standalone cluster without accepting that recent writes may be missing.
  4. Afterwards, check that clients re-registered their ephemeral nodes.
10.8 How do you add or replace a server without downtime?

Ideas to cover: one at a time, dynamic reconfiguration, myid, client list.

Each server has a unique id in its myid file and a server.N=host:2888:3888 line in the configuration. The classic method is a rolling restart: change one server at a time and wait until it has rejoined and synced before touching the next. Since 3.5 there is dynamic reconfiguration, disabled by default (reconfigEnabled=true); protect it with access control. Update client connection strings too.

10.9 What do you monitor?

Ideas to cover: liveness is not quorum, key metrics.

ruok answering imok only means the process runs, not that it joined the quorum. Use srvr or mntr, or the AdminServer. Four-letter commands must be allowed in 4lw.commands.whitelist; the AdminServer is off by default in 3.10, and it should be firewalled when on.

Metric Worry when
zk_server_state No leader, or the leader keeps changing
zk_synced_followers (leader) Fewer than expected
zk_avg_latency, zk_max_latency Rising
zk_outstanding_requests Queue keeps growing
zk_znode_count, zk_watch_count Steady growth (a leak)
zk_open_file_descriptor_count Close to the limit
10.10 You have two data centres. Where do the servers go?

Ideas to cover: majority placement, third site, observers, latency.

Five voters over three sites survive the loss of any one site.

With only two sites, one of them holds the majority; losing it stops the whole cluster. You need a third failure domain, even a small one: for example 2, 2 and 1 voters. Every write then pays cross-site latency. If a far region mostly reads, give it observers so it adds no voting delay.

11 · Security in five lines

  • Never expose the client, quorum or admin ports to the internet.
  • Access control lists apply per znode and are not inherited by children.
  • Authenticate clients (SASL or mutual TLS) and encrypt traffic.
  • Do not store raw secrets in znodes; use a secret manager.
  • Restrict who may run reconfiguration and admin commands.

12 · Alternatives: which one when

This comparison is a general guide; check current versions before deciding.

Tool Good fit Watch out for
ZooKeeper You run software that needs it, or want mature recipes on the JVM Another cluster to operate; low-level API
etcd Kubernetes-style stacks; leases, watch streams, gRPC Same quorum rules and small-data limits
Consul Service discovery with built-in health checks Broader product, more to configure
Database row lock or unique key You already have one database and moderate load Failover of the database limits safety
Redis lock Efficiency locks where a rare double run is harmless Add fencing or avoid it for correctness
Built-in consensus (Raft inside your system) The system ships its own, as Kafka does Nothing extra to run

Kafka is the best-known change here: Kafka 4.0 removed ZooKeeper mode and runs on its own KRaft quorum. Older clusters must migrate before upgrading to 4.0.

When to reach for ZooKeeper

Small, slow-changing facts that many machines must agree on, where being wrong is worse than waiting. If the data is large, changes constantly, or may safely be a bit wrong, use something else.

Program guide

Problem Concept that solves it
Nobody notices a crashed owner Session timeout and ephemeral znodes
The coordinator is a single point of failure Ensemble and majority quorum
Two sides of a network split both act Quorum writes: the minority cannot commit
Contenders tie Sequential znodes
Everyone wakes up at once Watch only the predecessor
Polling wastes capacity Watches, then read the latest state
A paused old leader writes late Fencing token checked by the resource
Two writers overwrite each other Version check and multi
A follower serves old data sync, or a conditional write
More readers slow the writes Observers
Unknown outcome after a lost connection Unique ids and idempotent retries

Your three schedulers now have a clear design. They compete in an election, the winner works only while connected, and every write carries a fencing token. When the winner dies, its pencil entry is erased, the next in line hears the bell, and nobody edits a file at 3 a.m.

Sources: Kleppmann, Designing Data-Intensive Applications, chapters 8 and 9; the Apache ZooKeeper documentation (3.10 line) and Apache Curator documentation. Code samples are teaching sketches: test them against your own cluster before relying on them.