🌍 Networking

Zookeeper

ZooKeeper

A distributed coordination service. Configuration management, naming. Used with Kafka.

📖 Detailed Explanation

Apache Zookeeper is a centralized coordination service that provides configuration management, naming services, distributed synchronization, and group services in distributed systems. Developed at Yahoo! in 2008 and donated to the Apache project, it coordinates various distributed systems (projects named after animals) such as Hadoop, Kafka, and HBase, just as its name, "zookeeper," suggests.

The core concept of Zookeeper is the ZNode. It provides a hierarchical namespace similar to a file system, and each ZNode can have data (up to 1MB) and child nodes. An Ephemeral Node is automatically deleted when the session ends and is used for failure detection, while a Sequential Node has an auto-incrementing number appended and is used for distributed locks and Leader Election.

A Zookeeper ensemble usually consists of an odd number of servers, such as 3, 5, or 7. Because a write is completed only after obtaining the agreement of a majority (Quorum) through the ZAB (Zookeeper Atomic Broadcast) protocol, a 3-server configuration tolerates the failure of 1 server and a 5-server configuration tolerates the failure of up to 2 servers. Reads can be served by any node, but writes must always go through the Leader.

In Kafka versions 0.x to 2.x, Zookeeper was a required dependency. It was responsible for broker metadata, topic configuration, partition leader election, consumer group offset management, and more. However, starting with Kafka 3.x, KRaft (Kafka Raft) mode was introduced, making it possible to operate without Zookeeper, and it is scheduled to be removed completely in 4.0.

💻 Code Example

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

public class ZookeeperExample {
    private static final String ZK_ADDRESS = "localhost:2181";
    private static ZooKeeper zk;

    public static void main(String[] args) throws Exception {
        // Zookeeper 연결
        zk = new ZooKeeper(ZK_ADDRESS, 3000, event -> {
            System.out.println("연결 상태: " + event.getState());
        });

        // ZNode 생성 (Persistent)
        String path = zk.create("/myapp/config",
            "value".getBytes(),
            ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT);
        System.out.println("생성된 노드: " + path);

        // Ephemeral Node 생성 (세션 종료 시 자동 삭제)
        zk.create("/myapp/workers/worker-",
            "host:port".getBytes(),
            ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.EPHEMERAL_SEQUENTIAL);

        // 데이터 읽기 (Watch 설정)
        Stat stat = new Stat();
        byte[] data = zk.getData("/myapp/config", event -> {
            System.out.println("데이터 변경 감지!");
        }, stat);
        System.out.println("데이터: " + new String(data));

        // 자식 노드 목록 조회
        zk.getChildren("/myapp", false)
            .forEach(child -> System.out.println("자식: " + child));

        // Leader Election (간단한 예시)
        String leaderPath = zk.create("/election/candidate-",
            new byte[0],
            ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.EPHEMERAL_SEQUENTIAL);
        // 가장 작은 번호의 노드가 Leader
    }
}
from kazoo.client import KazooClient
from kazoo.recipe.lock import Lock
from kazoo.recipe.election import Election

# Zookeeper 연결
zk = KazooClient(hosts='localhost:2181')
zk.start()

# 노드 생성 (부모 경로 자동 생성)
zk.ensure_path("/myapp/config")
zk.create("/myapp/config/db_host", b"localhost:5432")

# 데이터 읽기/쓰기
data, stat = zk.get("/myapp/config/db_host")
print(f"값: {data.decode()}, 버전: {stat.version}")

# 데이터 업데이트 (낙관적 락)
zk.set("/myapp/config/db_host", b"newhost:5432", version=stat.version)

# Watch 설정 (데이터 변경 감지)
@zk.DataWatch("/myapp/config/db_host")
def watch_config(data, stat):
    if data:
        print(f"설정 변경됨: {data.decode()}")

# 분산 락 구현
lock = Lock(zk, "/locks/my-resource")
with lock:
    print("락 획득! 임계 영역 실행 중...")
    # 중요한 작업 수행

# Leader Election
election = Election(zk, "/election", "worker-1")

def leader_func():
    print("나는 리더다! 작업 분배 시작...")

election.run(leader_func)  # 리더가 되면 함수 실행

# Ephemeral 노드로 서비스 등록 (서비스 디스커버리)
zk.create("/services/api-server/node-",
          b"192.168.1.10:8080",
          ephemeral=True,
          sequence=True)

zk.stop()
# Zookeeper CLI 시작
bin/zkCli.sh -server localhost:2181

# 노드 생성
create /myapp ""
create /myapp/config "initial_value"

# Ephemeral 노드 생성 (세션 종료 시 삭제)
create -e /myapp/temp "session_data"

# Sequential 노드 생성 (자동 번호 부여)
create -s /myapp/seq- "data"
# 결과: /myapp/seq-0000000001

# 데이터 조회
get /myapp/config
# 출력: initial_value + stat 정보

# 데이터 수정
set /myapp/config "new_value"

# 자식 노드 목록
ls /myapp
# [config, temp, seq-0000000001]

# Watch 설정 후 조회
get -w /myapp/config  # 변경 시 알림

# 노드 삭제
delete /myapp/temp
deleteall /myapp  # 하위 포함 전체 삭제

# Zookeeper 4글자 명령어 (모니터링)
echo stat | nc localhost 2181  # 서버 상태
echo mntr | nc localhost 2181  # 상세 메트릭
echo cons | nc localhost 2181  # 연결된 클라이언트
echo srvr | nc localhost 2181  # 서버 정보

# Leader/Follower 확인
echo stat | nc localhost:2181 | grep Mode
# Mode: leader 또는 Mode: follower

🗣️ Say It Like This in Practice

💬 In a Kafka Operations Meeting
"We are currently using Kafka 2.8, so we need 3 Zookeeper servers. If we upgrade to Kafka 3.5 and switch to KRaft mode, we can remove the Zookeeper cluster, which reduces operational complexity. The migration can be done with a Rolling Upgrade without downtime."
💬 In a Distributed System Design Discussion
"If you need a distributed lock between microservices, you can use Zookeeper's Ephemeral Sequential Node. It guarantees stronger consistency than a Redis distributed lock, and because the lock is released automatically when a node fails, there is no risk of deadlock. However, its latency is higher than Redis, so if you handle thousands of requests per second or more, you should consider Redis Redlock."
💬 In an Interview
"Zookeeper Leader Election is based on the ZAB protocol. Each server compares its own zxid (transaction ID), and the server with the highest zxid becomes the Leader. It is confirmed as Leader only after obtaining the agreement of a Quorum (majority), and all write requests are replicated through the Leader. This guarantees strong consistency (Linearizability)."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Storing Large Data in a ZNode

Each ZNode can store up to 1MB only, and it is designed for configuration data and metadata. Store large data in a DB and store only a pointer in Zookeeper.

❌
Configuring an Ensemble with an Even Number of Servers

A 4-server configuration tolerates only 1 failure, the same as a 3-server configuration, because the Quorum is a majority. Always configure an odd number, such as 3, 5, or 7. 5 servers are recommended in production.

❌
Session Timeout Misconfiguration

If the Session Timeout is too short, Ephemeral nodes may be deleted unintentionally due to network latency. The default of 6 seconds is safe for most cases, and for JVM apps with long GC pauses, increase it to 30 seconds or more.

✅
The Right Way to Operate Zookeeper

Place ensemble servers on separate physical servers or in different AZs. Keep dataDir and dataLogDir separate on SSDs. Set the JVM heap to 4–8GB, and limit the number of connections with maxClientCnxns.

🔗 Related Terms

📚 Learn More