Coordination services: ZooKeeper and etcd
ZooKeeper and etcd keep a small amount of critical data that every node must agree on. Learn what they give you, where they break, and what not to put in them.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 28 October 2021, Roblox engineers saw that Vault was slow and one Consul server had high CPU load. Players were still fine. 1
Roblox runs over 18,000 servers. Consul gave them service discovery, health checks, session locking and a key-value store. Nomad and Vault both depended on it. 1 So when Consul was sick, services could not find each other. No new containers could start, and no secrets could be read. Roblox wrote: "the system failed because Consul was a single point of failure, and Consul was not healthy." 1
Writes to Consul's key-value store usually took under 300 ms at the median. Now they took 2 seconds. 1 The team replaced hardware. Later they shut down the whole cluster and restored a snapshot from before the outage. Neither fixed it. Latency stayed at about 2 seconds, or came back to it once load returned. 1
There were two causes. A new Consul streaming feature caused contention under very high read and write load. And a usage pattern that arose during the incident hit a slow path in BoltDB, the store under Consul's Raft log. One log store was 4.2 GB but held only 489 MB of real data. 1
The outage lasted 73 hours. 1 Monitoring also depended on Consul, so the team was partly blind while they debugged. Afterwards they split some critical services into their own Consul clusters. They also began moving data out of the key-value store. Some services had used it "as a convenient place to store data". 1
The idea in simple words
You met consensus in Consensus and Raft. Few teams run Raft themselves. They use a coordination service such as ZooKeeper, etcd or Consul, which runs consensus for you and offers a small, strongly consistent store.
ZooKeeper lists what this store is for: configuration, naming, synchronization and group membership. 2 In practice, that means:
- Config that every node must see the same way.
- Membership: which workers are alive right now.
- Service discovery: where each service runs.
- Locks and leader election. Leader election and leases covers leases, fencing tokens and ephemeral nodes in depth. This lesson does not repeat them.
It is not a database. ZooKeeper "was not designed to be a general database or large object store". Its data is usually measured in kilobytes. 3 It works best when reads outnumber writes by about 10 to 1. 2
The key idea. A coordination service holds the few facts your whole fleet must agree on. Keep that data small and slow-changing. Every extra use you add is one more thing that breaks when it breaks.
How it works
ZooKeeper: a tree of znodes
ZooKeeper stores data in a tree of paths, like a file system. Each node in the tree is a znode. A znode holds data and can have children. Reads and writes of a znode's data are atomic. 3
Two flags make it useful for coordination. An ephemeral znode lives only as long as the session that created it. A sequential znode gets a 10-digit counter added to its name, such as lock-0000000001. 3 Locks and elections combine both. 6
A session is the client's link to the cluster. If the cluster hears nothing from the client within the session timeout, it expires the session and deletes its ephemeral znodes. 3
All writes go to one leader. The servers agree on them with an atomic broadcast protocol. 2 4 The admin guide calls it ZAB. 5 A write is committed once a quorum of servers acknowledges it. Each change gets a zxid, a number that shows its place in the total order. 4
Writes are linearizable. Reads are not. Any server answers a read from its local copy, without asking a quorum. 4 So client A can write a value, tell client B, and B can still read the old one. The guide says B should call sync() first. 3 Even sync() is not a strict guarantee, because it is not a quorum operation. 4
Standard watches fire once
A client can set a watch when it reads. A standard watch is a one-time trigger. After it fires, you must set a new one. Between the event and your next read, the znode can change again. So you cannot reliably see every change. 3 ZooKeeper 3.6 added persistent watches that stay after they fire. 3
Step through how this differs from etcd.
- The client reads /cfg and sets a watch in the same call. It gets version 1.
- Someone writes version 2. ZooKeeper sends one event. A standard watch fires once and is then removed.
- Before the client reads again and sets a new watch, a third write lands. The client reads version 3. It never sees version 2.
- In etcd you ask for every change from a revision. Events come ordered by revision, with the new values, and the watch keeps running.
- If the stream breaks, you start a new watch after the last revision you saw. If compaction removed that history, etcd cancels the watch. You must read the current state and watch from there.
etcd: flat keys and revisions
etcd has no tree. Keys sit in one flat, sorted key space. You read ranges of keys, so a prefix like /services/ works like a folder. 7
etcd keeps old versions of every key, which is MVCC. A store revision counts every change to the whole key space. Each key records the revision that created it, the revision that last changed it, and a version count. 7 The revision only goes up. 7
Revisions make watches stronger. You can watch a key or range from any revision still in history. Events arrive ordered by revision, and none are dropped inside the history window. A broken watch can resume just after the last revision you saw, if that revision is still in history. 8
A lease has a TTL and is kept alive by keepalives. When it expires, every key attached to it is deleted. 7 This plays the role of ZooKeeper's ephemeral znodes.
A Txn is an atomic if/then/else. If every compare is true, the success operations run; otherwise the failure ones do. 7 This is compare-and-swap across keys. Here is "create the key only if nobody has":
key := "/jobs/nightly/owner"
resp, err := cli.Txn(ctx).
If(clientv3.Compare(clientv3.CreateRevision(key), "=", 0)).
Then(clientv3.OpPut(key, "worker-7", clientv3.WithLease(leaseID))).
Commit()
// resp.Succeeded is false if another worker created it first.Reads are linearizable by default. You can ask for a serializable read instead. One member answers it from its local copy, which is faster but may be stale. 7 8
Limits and failure modes
- Small values only. etcd rejects any request over 1.5 MiB by default. ZooKeeper checks that a znode holds less than 1 MB. 9 3
- The size quota. etcd's default storage limit is 2 GiB, and 8 GiB is the suggested maximum. 9 Past the quota, the cluster raises an alarm and accepts only reads and deletes. 10
- History grows. Old revisions stay until you compact them. Compaction leaves gaps inside the database file, so deleting data does not shrink it on disk. Defragmentation gives the space back, but it blocks reads and writes on that member while it runs. 10 Roblox's BoltDB log store shows how far a file can drift from its data: 4.2 GB on disk for 489 MB of data. 1
- Slow disks. A majority must write every request to disk. If those writes take too long, heartbeats can time out and start an election. 11 ZooKeeper also syncs each write to its log on disk before it answers, and wants a dedicated log device. 5
- The herd effect. If many clients watch the same znode, one change wakes all of them, but only one can act. The recipes avoid this by having each client watch only the node just before its own. 6 etcd's gRPC proxy merges many watchers of one key into a single watcher on the server. 12
Why Kafka left ZooKeeper
Kafka used to keep its cluster metadata in ZooKeeper. KIP-500 listed the costs. Operators had to run a second system with its own config and tools. After an election, a new controller had to load all state from ZooKeeper, which took a long time. KIP-500 also wanted Kafka to support more partitions. 13 The fix stores metadata as a log inside Kafka. 13 Kafka calls this KRaft mode. Kafka 4.0, from March 2025, is the first major release that runs entirely without ZooKeeper. 14
Trade-offs
| Option | Strong consistency? | Extra system to run? | Use it when |
|---|---|---|---|
Row lock in your database (SELECT ... FOR UPDATE) | Yes , inside one database. 15 | No | The data you protect lives in that database. |
| Postgres advisory lock | Yes , but the app must use it correctly. 15 | No | Many processes share one Postgres and need a named lock. |
| ZooKeeper | Writes yes; reads can be stale. 4 | Yes | You already run it, or a tool you use needs it. |
| etcd | Yes by default; serializable reads are optional. 8 | Yes | You need watches that can resume from a past revision. |
| Your own Raft inside the product | Yes | No , but you own the code. | The metadata is core to your product, like KRaft. 13 |
Simple rule: if the thing you protect lives in one database, lock it there. Reach for a coordination service when many systems must agree and there is no single database between them.
At work: how a senior uses this
- Ask of every key: "Is this coordination data, or just data?" If it is large, changes often, or only one service reads it, move it to a database.
- Count who depends on the cluster. Split critical users into their own clusters before an outage forces you to, as Roblox did afterwards. 1
- Keep monitoring off the cluster it watches.
- Alert on etcd database size against the quota, and on leader changes. Set up auto-compaction and plan defragmentation one member at a time. 10
- Put the members on fast SSDs that other processes do not share. 11
- In ZooKeeper, re-read after each watch event, and design for missed middle states.
- In etcd, use a linearizable read when a decision depends on the latest value. In ZooKeeper, call
sync()first, and remember it narrows the gap but does not close it.
With AI
What to ask the agent
"List every key our services write to etcd. For each, give the size, writes per minute and readers. Flag anything that looks like application data, not coordination data."
"Here is our ZooKeeper watch code. Check that it sets a new watch after each event and reads the current value, and show what happens if the node changes twice quickly."
"We use an etcd lock to stop two workers handling the same order. The orders live in Postgres. Rewrite it with a row lock and explain what we lose and gain."
What to check yourself
- The agent did not store blobs, logs or per-request data in the coordination service.
- Watch code handles a compacted revision by reading the current state, not by crashing.
- Lock code that needs fresh data does not use serializable reads.
- The agent did not add a coordination service where a database row lock would do.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 15 sources and related lessons
- Roblox, “Roblox Return to Service 10/28-10/31 2021” (opens in a new tab)
The official postmortem. One Consul cluster held discovery, health checks, locks and KV data, and its failure took Roblox down for 73 hours. - Apache ZooKeeper documentation, “ZooKeeper: A Distributed Coordination Service for Distributed Applications” (opens in a new tab)
What ZooKeeper is for, why reads are local and writes go through the leader, and the 10:1 read-to-write sweet spot. - Apache ZooKeeper documentation, “ZooKeeper Programmer's Guide” (opens in a new tab)
Znodes, ephemeral and sequential nodes, one-time watches, sessions, the 1 MB limit, and why a client may need sync(). - Apache ZooKeeper documentation, “ZooKeeper Internals” (opens in a new tab)
The atomic broadcast protocol, zxids, and the exact consistency model. Writes are linearizable; reads are not. - Apache ZooKeeper documentation, “ZooKeeper Administrator's Guide” (opens in a new tab)
Running a ZooKeeper ensemble. Names the server-to-server protocol ZAB, and explains why the transaction log needs its own fast disk. - Apache ZooKeeper documentation, “ZooKeeper Recipes and Solutions” (opens in a new tab)
Locks and leader election built from sequential nodes, and how to avoid the herd effect. - etcd documentation (v3.5): etcd API (opens in a new tab)
Revisions, key fields, linearizable and serializable reads, Txn, Watch from a revision, and leases. - etcd documentation (v3.5): etcd API guarantees (opens in a new tab)
Linearizable by default, the serializable option, and the watch guarantees. - etcd documentation (v3.5): System limits (opens in a new tab)
The 1.5 MiB request limit, the 2 GiB default storage limit and the 8 GiB suggested maximum. - etcd documentation (v3.5): Maintenance (opens in a new tab)
History compaction, defragmentation, and what happens when the space quota is full. - etcd documentation (v3.5): Hardware recommendations (opens in a new tab)
Why the disk is the most critical part of an etcd deployment. - etcd documentation (v3.5): gRPC proxy (opens in a new tab)
A proxy that merges many watchers on the same key into one, to protect the cluster. - Apache Kafka, KIP-500: Replace ZooKeeper with a Self-Managed Metadata Quorum (opens in a new tab)
Why Kafka moved its metadata out of ZooKeeper and into its own log. - Apache Kafka, “Apache Kafka 4.0.0 Release Announcement” (March 2025) (opens in a new tab)
The first major Kafka release that runs entirely without ZooKeeper. - PostgreSQL documentation: 13.3. Explicit Locking (opens in a new tab)
Row-level locks with SELECT FOR UPDATE, and advisory locks held per session or per transaction.
Real incident: Roblox, 28 Oct 2021: Roblox outage: 73 hours down after Consul broke
Related: Consensus and Raft · Leader election and leases · Failure detection and membership · DNS and service discovery · Kafka internals · CAP, PACELC and consistency models · PostgreSQL in depth
Before this: Consensus and Raft, leader election and leases and failure detection and membership. Related: DNS and service discovery, CAP and consistency models and locks, atomics and deadlocks. For row locks and advisory locks, see PostgreSQL in depth. Kafka internals shows the KRaft controllers that replaced ZooKeeper there. See the Roblox incident page.