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.
See it run
Watch a change become official, a session run out, and leadership pass to exactly one candidate.
Operations
Write
A client sets x to 2 through a follower. Three servers, majority two.
Step 1 of 6
Send
The client is connected to follower 1 and asks for x = 2.
Step 1: Send
def write(change): # any server if not leader: return forward(change) zxid = next_zxid() log.append_and_sync(zxid, change) broadcast("PROPOSAL", zxid, change) wait_until(acks >= majority) # leader counts too broadcast("COMMIT", zxid) apply_in_order(zxid)- Cost
- majority + disk sync
- Guarantee
- linearizable
The leader's own log write counts as one of the votes.
In the real world
The same apache zookeeper doing real jobs. Pick one and step through it.
The leader is cut off from both followers.
Step 1 of 4
Before
Three servers, one leader.
Step 1: Before
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Everyone watches the leader
majorWhen it goes, all candidates wake and list all children at once.
Wrongexists(leader_node, watch=me)Rightexists(node_just_before_mine, watch=me)Acting on a lock without fencing
criticalA paused holder continues after its session expired.
Wrongwith lock: storage.write(data)Rightwith lock as token: storage.write(data, token=token) # refuses smaller tokensStoring data in znodes
majorThe whole tree lives in each server's memory and every change is a majority write.
Wrongzk.set("/report", five_megabytes)Rights3.put("report-7", five_megabytes)zk.set("/report", b"report-7")New session on every disconnect
majorThe library reconnects and keeps your session. A new one adds load and loses your place.
Wrongif state == DISCONNECTED: zk = ZooKeeper(...)Rightif state == DISCONNECTED: pause_leader_work()if state == EXPIRED: zk = ZooKeeper(...)
Interview tips
How to explain it
- A small ordered tree on several servers.
- Majority for writes, local reads.
- Sessions make claims vanish.
Memory trick
- Ephemeral exits with its maker.
- Sequential stands in line.
- Watch the one in front of you.
Reach for it when
- A system you run needs it.
- One leader must exist.
- Reads far outnumber writes.
Be careful with
- Short timeouts and long pauses.
- Voting servers far apart.
- Disks shared with other work.