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.

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

EnsembleClient AFollower 1x = 1Leaderx = 1Follower 2x = 1

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

EnsembleClient AFollower 1x = 1Leaderx = 1Follower 2x = 1

Three servers, one leader.

Step 1: Before

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Everyone watches the leader

    major

    When it goes, all candidates wake and list all children at once.

    Wrong
    exists(leader_node, watch=me)
    Right
    exists(node_just_before_mine, watch=me)
  • Acting on a lock without fencing

    critical

    A paused holder continues after its session expired.

    Wrong
    with lock:    storage.write(data)
    Right
    with lock as token:    storage.write(data, token=token)  # refuses smaller tokens
  • Storing data in znodes

    major

    The whole tree lives in each server's memory and every change is a majority write.

    Wrong
    zk.set("/report", five_megabytes)
    Right
    s3.put("report-7", five_megabytes)zk.set("/report", b"report-7")
  • New session on every disconnect

    major

    The library reconnects and keeps your session. A new one adds load and loses your place.

    Wrong
    if state == DISCONNECTED:    zk = ZooKeeper(...)
    Right
    if 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.