Learning pathsPricingChecking sign-in…
Key Technologies

ZooKeeper

ZooKeeper coordinates small amounts of critical shared state using an ordered replicated service and client sessions.

What, why, when and how

What is it?

ZooKeeper provides a small shared coordination namespace used for membership, configuration and leader-election protocols.

Why is it needed?

Distributed processes sometimes need a common authority for control-plane ownership and coordination state.

When should I use it?

Use it for small, carefully scoped coordination metadata when an existing system requires its session and ordering semantics.

When should I choose something else?

Do not use it as a bulk event store or assume an expired session physically stops the old process. A managed service or database condition may be simpler for a small coordination need.

How do I use it?

Keep records small, reason about sessions and watches, reread authoritative state after notifications, and use fencing at the protected resource.

Can you show a concrete example?

Leader A pauses long enough to lose ownership and B takes over. When A resumes, the destination rejects A’s older fencing epoch instead of trusting its stale belief that it is still leader.

A holds leadership, then its session expires; B gains leadership with a newer fencing token; Destination rejects A when it resumes
ZooKeeper: one concrete example
Read the diagram

A holds leadership, then its session expires; B gains leadership with a newer fencing token; Destination rejects A when it resumes

Open original
ZooKeeper: worked example
A holds leadership, then its session expires; B gains leadership with a newer fencing token; Destination rejects A when it resumes

ZooKeeper: one concrete example

Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.

ZooKeeper coordinates small amounts of critical shared state using an ordered replicated service and client sessions. It can support leader election and short-lived ownership signals, but it is not a general database or high-volume message bus. Session expiration means a client may have lost ownership even if its process has not noticed yet.

Keep coordination state small and fenced

Represent membership under /workers, configuration under /config and election candidates as ephemeral sequential children under /election. Candidate 0007 is the current eligible leader; session expiry removes its ephemeral candidate and allows 0008 under the chosen election protocol. A paused process can still wake up with old local beliefs, so the protected resource checks a monotonic fence.

Contract / pseudocode
session A: candidate 0007; resource fence=7
A expires; B wins candidate 0008; resource fence=8
A resumes write(token=7) -> resource rejects
B write(token=8) -> allowed under its contract
session A: candidate 0007; resource fence=7; A expires; B wins candidate 0008; resource fence=8; A resumes write(token=7) -> resource rejects; B write(token=8) -> allowed under its contract
Keep coordination state small and fenced
Read the diagram

session A: candidate 0007; resource fence=7; A expires; B wins candidate 0008; resource fence=8; A resumes write(token=7) -> resource rejects; B write(token=8) -> allowed under its contract

Open original
Keep coordination state small and fenced
session A: candidate 0007; resource fence=7; A expires; B wins candidate 0008; resource fence=8; A resumes write(token=7) -> resource rejects; B write(token=8) -> allowed under its contract

Keep coordination state small and fenced

Node versions support conditional changes. Watches notify according to their documented semantics; they are not a durable complete event log. After reconnect, reread authoritative state and reinstall applicable watches rather than treating every notification as one business event. Session expiry and a transient disconnected state have different consequences.

An ensemble's quorum/election protocol coordinates writes; client reads and freshness need the service's actual contract, including synchronization where appropriate. Store small configuration/membership data rather than application blobs or high-volume per-message traffic. Bound connection and watch counts and test session loss.

Show answer and explanation

Answer: Deleting A's ephemeral node cannot stop A from issuing a database write after it wakes. The fence must be enforced at the resource receiving that write. If an existing database condition already protects the business invariant, adding a coordination service may be unnecessary.

Step-by-step reasoning

1. 1 · Frame

Define the coordination problem, required ordering, number of znodes, and tolerance for session loss. Use it for membership/leader coordination or a small lock namespace, not as the main store for every job. Create ephemeral nodes for session-bound presence and sequential nodes when ordered contenders are needed.

2. 2 · Model

A lock recipe creates an ephemeral sequential contender and watches only its immediate predecessor to avoid a thundering herd. The smallest sequence holder owns the lock. On disconnect/session expiry, its ephemeral node disappears. Watch notifications are hints to re-read state; they can be missed or coalesced between disconnect and reconnect.

3. 3 · Scale

Clients must handle connection loss during create: the server may have created a node while the response was lost. Use a client identity in node data and search for an existing contender before creating another. Keep znode payloads small. Monitor quorum health, request latency, outstanding watches, and session churn. Avoid long application work while assuming a session cannot expire.

4. 4 · Recover

A process pauses after its session expires and later resumes believing it is leader. Ephemeral node removal helps elect a new leader but cannot stop stale external writes. Use a fencing epoch at the protected destination or downstream lease validation. Coordination membership does not magically revoke capabilities already held outside ZooKeeper.

Contracts and state

The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.

Contract / pseudocode
/locks/job-42/lock-0000000012 (ephemeral sequential)
Client identity is stored in node data
Owner = lowest live sequence
Each waiter watches predecessor and rechecks children
Protected store validates current fencing epoch

Worked example

Clients A, B, and C create sequential contenders 12, 13, and 14. A owns; B watches 12; C watches 13. When A disappears, B wakes and rechecks the child list. C does not wake yet, reducing notification load. If B’s session expires, its node disappears and C can become owner after rechecking.

Failure walkthrough

A paused A loses its session, B is elected, then A resumes and writes to a database. ZooKeeper cannot prevent that external write on its own. B receives a newer fencing epoch; the database rejects A’s stale epoch. If the destination cannot validate ownership, use another coordination protocol appropriate to the side effect.

A holds epoch 7 → A session expires → B becomes owner with epoch 8 → A resumes and writes → Destination rejects epoch 7
ZooKeeper · scenario walkthrough
Read the diagram

A holds epoch 7 → A session expires → B becomes owner with epoch 8 → A resumes and writes → Destination rejects epoch 7

Open original
ZooKeeper · scenario walkthrough
A holds epoch 7 → A session expires → B becomes owner with epoch 8 → A resumes and writes → Destination rejects epoch 7

ZooKeeper · scenario walkthrough

Decisions and trade-offs

FeatureUseful forCaution
Ephemeral nodeSession-bound membershipSession expiry can surprise paused clients
Sequential nodeOrdering contendersCreate response can be ambiguous
WatchWake up to recheck stateNot a durable event queue
Fencing epochReject stale owner effectsDestination must enforce it

Check your understanding

Why must an elected leader carry a fencing token to the database it protects?

Show answer and explanation

Answer: A former leader can pause, lose its ZooKeeper session, then resume after a new leader is elected. The database must reject writes bearing an older epoch. ZooKeeper can order ownership decisions, but the protected destination enforces that stale authority is no longer valid.

Primary documentation

Read the first-party engineering account or official technical reference. Company engineering posts describe the scope and date of that publication; the interview reconstruction and scenarios here are original teaching examples.

Continue the connection

Study Distributed Cache and explain which guarantee from this lesson carries into that topic.

Use coordination state sparingly

Coordination services are useful for membership, configuration and small ownership records. They are not a natural home for high-volume event payloads. A client session can own ephemeral state, but a network interruption and session expiry are different events; applications must handle ambiguous connectivity carefully.

A leader-election recipe can order contenders and observe a predecessor. Winning election grants a role in the coordination system, but the protected database must still reject writes from a former leader. Use an increasing epoch or fencing token accepted by the downstream resource. Without that check, a paused old leader can resume and corrupt state.

Watches notify that state may have changed; clients should reread authoritative state and reestablish watches according to the API semantics. Treat notifications as prompts to reconcile, not an unlimited durable event stream. Keep coordination payloads small and monitor session churn, request latency and ensemble health.

A decision worksheet for ZooKeeper: read the mechanism and its guarantee together.
A decision worksheet for ZooKeeper: read the mechanism and its guarantee together.
Read the diagram

Feature / Useful for / Caution; Ephemeral node / Session-bound membership / Session expiry can surprise paused clients; Sequential node / Ordering contenders / Create response can be ambiguous; Watch / Wake up to recheck state / Not a durable event queue; Fencing epoch / Reject stale owner effects / Destination must enforce it

Open original
ZooKeeper choices for this workload
A decision worksheet for ZooKeeper: read the mechanism and its guarantee together.

A decision worksheet for ZooKeeper: read the mechanism and its guarantee together.

Operational sketch

Contract / pseudocode
contender creates ephemeral sequential node
smallest sequence becomes elected owner
owner obtains monotonic fencing epoch
resource rejects stale epoch
watch event -> reread state -> restore watch

A tempting mistake

Availability of the coordination cluster does not imply availability of the protected data service. Likewise, a lease or ephemeral node cannot physically stop code already running elsewhere.

Transfer exercise

What happens if an old leader reconnects after another leader was elected?

Show answer and explanation

Answer: It must relinquish leadership and its old epoch must be rejected by the resource. Local belief or a cached election result cannot authorize a write.

Shared foundation: Consensus, Leader Election and Fencing

Consensus, Leader Election and Fencing: Trace majority authority and reject a paused obsolete worker at the protected destination. Work its failure history before extending this design.

Your study notes