SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

ZooKeeper and etcd

Small, highly reliable stores that other systems use for locks, leaders, config and who-is-alive.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

ZooKeeper and etcd are small, very reliable stores that a whole cluster of other machines can trust. They keep a little data (settings, who the leader is, who holds a lock) and they never lose it, because every change is agreed by a majority of their own servers.

  • ZooKeeper: a tree of small nodes called znodes. Some are ephemeral: they vanish when their owner's session dies. Clients watch nodes to be told about changes.
  • etcd: a key-value store. Keys can be tied to a lease (a timer), and clients watch keys. Used by Kubernetes.
  • They are building blocks for leader election, locks, config and service discovery. They are not databases for your business data.

02Concept: What is it?

Think of a distributed system with 100 machines. They all need to answer questions such as "who is the leader?", "which servers are alive?" and "what is the current setting?". If each machine guessed on its own, they would disagree. So we put the answers in one tiny, trusted place: a coordination service.

The coordination service is itself a small cluster (usually 3 or 5 servers). It uses a consensus protocol to keep the copies the same: ZAB (ZooKeeper Atomic Broadcast) in ZooKeeper, and Raft in etcd. A write is only accepted when a majority has stored it, so one or two failed servers do not lose anything.

The two tools offer a few simple ideas that can be combined into many recipes. Ordered, versioned data (every change gets a growing number: zxid in ZooKeeper, revision in etcd). Temporary data that disappears if its owner stops being alive (ephemeral nodes, leases). And watches, which tell you when something changes, so you do not have to keep asking.

Your servers lean on a tiny trusted cluster
Your application servers (many)
πŸ–₯️App 1
πŸ–₯️App 2
πŸ–₯️App 3
↔sessions, watches
ZooKeeper / etcd (3 or 5 servers)
πŸ‘‘Leader
πŸ—„οΈFollower
πŸ—„οΈFollower
The big cluster does the work. The small cluster only answers coordination questions.
🧠Small data, big promises
These stores hold kilobytes, not gigabytes. The reason is that every write goes through one leader and a majority vote. They give you very strong guarantees, in return for low volume.

03Real-Life Example

🍡The Notice Board with a Sign-In Sheet
A building has one notice board that everyone trusts. It has a sign-in sheet: whoever signs first is the floor manager. The sheet is written in pencil with a note "erased if this person stops showing up". If the manager leaves without telling anyone, their line is erased after a while. Everyone who was watching the sheet is told at once, and the next person on the list becomes manager. The notice board itself is copied in three offices, and a change only counts once two of the three have written it down.
Notice board
ZooKeeper / etcd
The trusted board, copied in 3 offices
The coordination cluster (3 or 5 servers)
Two of three offices must agree
Majority (quorum) for each write
The sign-in sheet
Ephemeral nodes or lease-bound keys
Erased if the person stops showing up
Session timeout or lease expiry
Being told when the sheet changes
A watch
Lowest sign-in number is the manager
Lowest sequence number is the leader
Page number written on each change
zxid (ZooKeeper) or revision (etcd)
A leader election in three lines
πŸ“Each server creates/election/n_ (ephemeral, sequential)
→↓lowest number
πŸ‘‘Is the leaderothers watch the key just below theirs
→↓leader dies, key vanishes
πŸ””Next in line is toldand becomes leader

04Why Do We Need It?

🧠Do not build consensus yourself
Paxos and Raft are very hard to get right. Use a store where someone already did.
πŸ‘‘One agreed leader
Everyone asks the same place who is in charge, so there is no split brain.
πŸ””Instant news
Watches push changes to clients, so they do not poll all day.
🧹Self-cleaning
Ephemeral nodes and leases remove the entries of dead machines for you.
πŸ”’Ordering for free
Every change has a growing number, which helps with fencing tokens and versioning.
πŸ›‘οΈSurvives failures
With 5 servers, any 2 can fail and the data is still there and still consistent.
Use a coordination service for the small facts that the whole cluster must agree on, and keep your big data somewhere else.

05Where Do We Use It?

☸️Kubernetes
etcd stores every object in the cluster: pods, services, secrets and config.
πŸ“¨Kafka (older versions)
ZooKeeper stored broker lists and picked the controller. Newer Kafka uses its own Raft (KRaft).
🧭Service discovery
Servers register themselves, and clients watch the list. Consul and etcd are common here.
βš™οΈShared config
Change a setting in one place and every server is notified.
πŸ”Distributed locks
A lock is a key. The holder owns it as long as its session or lease is alive.
πŸ—„οΈDatabases
HBase, ClickHouse, Solr and others use ZooKeeper for leaders and cluster state.

06Types / Parts / How It Works

The two tools side by side

IdeaZooKeeperetcd
Data modelA tree of znodes, like folders and filesA flat key-value space (keys can look like paths)
ConsensusZABRaft
Temporary dataEphemeral znode, tied to a client sessionKey attached to a lease with a TTL
Getting newsWatch (fires once, then you set it again)Watch (a stream of events from a revision)
Ordering numberzxidrevision
Ordered namesSequential znodes (n_0000000007)Use the revision or a lease key
Transactionsmulti() operations, version checksTxn with compare-and-swap conditions
API and languageOwn protocol, Java clientgRPC and HTTP, written in Go

What a znode tree looks like

ZooKeeper data
πŸ“/
πŸ“/configpersistent
πŸ“/servicespersistent
πŸ“/electionpersistent
πŸ“„/services/api-1ephemeral
πŸ“„/services/api-2ephemeral
πŸ“„/election/n_0001ephemeral, sequential
Ephemeral nodes (cyan) disappear with their session. Persistent nodes (green) stay.
Persistent node Ephemeral node

Common recipes

RecipeHow it works
Leader electionEveryone creates a sequential ephemeral node. The lowest number leads. Each follower watches the one just below it.
LockSame idea. The lowest number holds the lock. The rest wait by watching their predecessor.
ConfigStore settings in a node. Clients watch it and reload on change.
Service discoveryEach server creates an ephemeral node with its address. Clients list and watch the folder.
Group membershipSame as service discovery. The folder is the list of who is alive.
BarrierWait until N nodes exist, then everyone continues.
VisualizerCrash the leader and watch the watch fireCrash Server A (the leader). After the timeout its key is deleted, the next server is told, and it takes over. Change the timeout to see failover get slower or faster. Switch between ZooKeeper and etcd to see the two names for the same idea.
Which store?
Current leader
A
lowest key wins
zxid
3
grows on every change
Failover time
~6 s
until the dead key goes
The servers (click to crash or restart)
πŸ‘‘
Server A
leader
πŸ–₯️
Server B
follower, watching the key before it
πŸ–₯️
Server C
follower, watching the key before it
What the store holds right now
/election/n_0000000001Server A πŸ‘‘
/election/n_0000000002Server B
/election/n_0000000003Server C
Each key is an ephemeral, sequential znode. It lives only while its owner's session is alive.
Server A is the leader because its key has the lowest number. If it crashes, the store removes the key after about 6 s and the next server is told by its watch.

A simplified model. The real stores replicate every change to a majority of their own servers (ZAB in ZooKeeper, Raft in etcd) before saying yes.

07How to Use It / Steps / Implementation

Using one as a leader election

  1. 1
    Run 3 or 5 servers
    An odd number, in separate failure zones. Never 2 or 4: they do not help a majority.
  2. 2
    Open a session or lease
    Each app server connects, and keeps the session alive with heartbeats (ZooKeeper) or renews its lease (etcd).
  3. 3
    Create your key
    ZooKeeper: an ephemeral sequential znode. etcd: a key attached to your lease, with the revision as the order.
  4. 4
    Read all keys
    If yours is the lowest, you are the leader. Otherwise you are a follower.
  5. 5
    Watch the key just below yours
    Watch only the one before you, not all keys. Otherwise every change wakes every client (a herd).
  6. 6
    When told, check again
    The key may have vanished because its owner died. Read the list and see if you are now first.
  7. 7
    Stop leading if you lose the session
    If your session expires or your lease is lost, stop at once. Another server may already lead.
πŸ’‘Use a library for the recipe
Curator (for ZooKeeper) and the etcd client's concurrency package already implement locks and elections. Writing your own is easy to get subtly wrong.
⚠️Pair locks with fencing tokens
A session can expire while a client is paused. Give the protected resource a growing number (the zxid or revision) so it can reject the old holder.

08Key Terms to Know

TermMeaning in easy words
Coordination serviceA small, reliable cluster that other systems use for agreement and shared facts
znodeA node in ZooKeeper's tree. It holds a small piece of data
Ephemeral nodeA znode that is deleted when the session that made it ends
Sequential nodeA znode whose name gets an increasing number added by ZooKeeper
SessionA client's connection to ZooKeeper, kept alive with heartbeats
WatchA request to be told when a node or key changes
LeaseIn etcd, a timer. Keys attached to it are deleted if it is not renewed
ZABZooKeeper Atomic Broadcast, the protocol that keeps ZooKeeper servers in step
RaftThe consensus protocol that etcd uses
zxid / revisionThe growing number given to every change
QuorumA majority of the servers (3 of 5). Needed for every write
Herd effectEveryone waking up for one event, when only one needed to

09Pros, Cons and Trade-offs

βœ… Pros
  • Strong consistency and clear ordering of changes
  • Survives the loss of a minority of servers
  • Watches give instant news without polling
  • Ephemeral nodes and leases clean up after dead clients
  • Proven in production (Kubernetes, Kafka, HBase)
  • Saves you from writing consensus yourself
⚠️ Cons
  • Small data only (ZooKeeper limits a node to about 1 MB)
  • All writes go through one leader, so write volume is limited
  • Needs its own cluster to run and monitor
  • A session timeout can fire during a long pause
  • Cross-region clusters are slow
  • Easy to misuse as a general database

Trade-offs

ChoiceWe gainWe lose
Short session timeout / leaseFast failoverFalse alarms on pauses and slow networks
Long session timeout / leaseFewer false alarmsSlow failover
5 servers instead of 3Survives 2 failuresSlower writes, more to run
Read from a followerMore read capacityMay be slightly old (ask for a linearizable read if needed)
Watch one keyNo herdA little more code
Spread over 3 zonesSurvives a zone lossHigher write latency

10Common Problems and Mistakes

Common mistakes

  1. Using it as a database. Large or fast-changing data will slow the whole cluster. Keep it for small coordination facts.
  2. Believing a lock is always safe. If the client pauses, its session expires and the lock moves on. Use fencing tokens.
  3. Even number of servers. 4 servers still need 3 for a majority, so they tolerate no more failures than 3.
  4. Everyone watching the same key. When it changes, all clients wake at once and hammer the cluster.
  5. Forgetting ZooKeeper watches fire once. You must set the watch again after each event, and re-read the data in case you missed one.
  6. Too many watches or too much data. Memory and snapshots grow, and recovery gets slow.
  7. Ignoring disk speed. Every write is fsynced. A slow disk makes the whole cluster look dead.

Things to watch

πŸ’ΎDisk latency
Put the log on a fast, dedicated disk. Watch fsync time.
⏱️Session timeouts
Longer than your worst GC pause, shorter than your failover budget.
🌐Network splits
The side without a majority stops serving writes. That is intended.
πŸ“ˆCluster size
Watch the number of nodes, watches and connections.

11Real-World Examples

☸️Kubernetes
Every object lives in etcd. The API server is the only thing that talks to it. If etcd is lost, the cluster forgets what it should run.
πŸ“¨Apache Kafka
Used ZooKeeper to track brokers and elect the controller. Newer versions replaced it with KRaft, a Raft log inside Kafka.
🐘Apache HBase
Uses ZooKeeper to find the master and region servers, and to detect crashed servers.
πŸ—οΈGoogle Chubby
The original lock service that inspired ZooKeeper. Used inside Bigtable and GFS.
πŸ›°οΈConsul
A similar tool with Raft and a focus on service discovery and health checks.
🧰Patroni (PostgreSQL)
Uses etcd or ZooKeeper to pick the one primary database and avoid two primaries.
Mini case: database failover with etcd
🐘Primary DBrenews lease every 10 s
→↓crashes
⏳Lease expireskey /leader deleted
→↓watch fires
🐘Replica takes the keypromotes itself
Only one holder of the leader key can be primary at a time.

12Related Topics to Read Next

Leader Election→

The main job these tools are used for.

Distributed Locks→

Built from ephemeral nodes or leases.

Fencing Tokens→

Make a lock safe when a client can pause.

Raft→

The protocol under etcd.

Consensus Algorithms→

How a group agrees on one value.

Service Discovery→

Registering and finding services with watches.

Heartbeats→

How sessions and leases notice a dead client.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a tiny, majority-replicated store for coordination facts.
  • βœ”ZooKeeper: znode tree, ephemeral and sequential nodes, ZAB.
  • βœ”etcd: key-value, leases, streaming watches, Raft.
  • βœ”Ephemeral / lease: data that disappears when its owner stops being alive.
  • βœ”Recipes: leader election, locks, config, discovery, membership.
  • βœ”Servers: 3 or 5, odd, across zones.
  • βœ”Careful: small data only, and pair locks with fencing tokens.
  • βœ”One line: β€œA small, trusted notice board that tells everyone who is in charge.”
← Previous
Leader Election
Next β†’
Distributed Locks