Deploying Kafka and Zookeeper on Kubernetes Clusters
Learn to deploy Apache Kafka and Zookeeper on self-managed Kubernetes. Optimize throughput, latency, and system scalability for real-time streaming.
The demand for real-time data processing has pushed system architects to seek robust, scalable event streaming solutions. Deploying Apache Kafka and Zookeeper on a self-managed Kubernetes cluster offers a powerful blueprint for building high-throughput data pipelines, enabling organizations to process vast streams of information with low latency. This architecture addresses the inherent complexities of distributed consensus and state management, providing a foundational layer for critical applications that necessitate extreme performance considerations, ensuring data velocity and integrity across the enterprise.
Challenges & Foundations of Event Streaming Architecture
Building a reliable real-time event streaming system is no trivial task. Key challenges include ensuring ordered message delivery, handling unpredictable data spikes, and maintaining high availability amidst node failures. Apache Kafka, as a distributed event streaming platform, is designed to address these issues with its durable and scalable publish-subscribe model. However, Kafka itself relies on Apache Zookeeper for cluster coordination, metadata management, and leader election. Integrating both into a Kubernetes environment introduces significant layers of abstraction and automation, but also demands a deep understanding of distributed system principles.
Zookeeper, as a distributed coordination service, provides naming, distributed configuration, synchronization, and leader election services for the Kafka cluster. A Zookeeper ensemble typically consists of three or five replicas to achieve the necessary quorum for maintaining high availability and fault tolerance. Each Zookeeper replica stores an identical copy of the data, and updates are only considered successful if acknowledged by a majority (quorum) of the replicas. Failure to achieve a quorum can render the Kafka cluster inoperable, highlighting the importance of proper Zookeeper configuration and careful monitoring.
Provisioning a Self-Managed Kubernetes Cluster
The first step in this journey is to set up a self-managed Kubernetes cluster. Managing your own cluster on Hostinger KVM VPS infrastructure provides full control over the underlying infrastructure configuration, which is crucial for optimizing the I/O and network performance required by Kafka. For this purpose, we will use kubeadm on an Ubuntu 22.04 LTS operating system. This process involves initializing the master node, joining worker nodes, and installing a CNI (Container Network Interface) like Calico for inter-pod communication.
# On the master node
sudo kubeadm init --pod-network-cidr=192.168.0.0/16
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
# Install CNI Calico
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.25.0/manifests/calico.yaml
# On the worker nodes
sudo kubeadm join <master-ip>:6443 --token <token> --discovery-token-ca-cert-hash sha256:<hash>
Once the Kubernetes cluster is operational, we can proceed with deploying the event streaming components. It is essential to ensure that the nodes have adequate resources, particularly fast disk I/O (NVMe SSDs are highly recommended) and high network capacity, as these are primary limiting factors for Kafkaโs throughput.
Matriks Parameter Kunci & Rekayasa Operasional
| Dimensi Parameter | Analisis Implementasi Riil | Dampak Strategis |
|---|---|---|
| [TERVERIFIKASI] Volume pencarian bulanan untuk kata kunci redpanda kafka adalah 320 dengan kompetisi rendah (23). (Limitasi | Data spesifik untuk agregasi region US + SG + ID pada periode akses.) | Terverifikasi Lapangan |
| [TERVERIFIKASI] Estimasi bid lelang atas untuk redpanda kafka mencapai $11.22 USD. (Limitasi | Nilai bid dapat berfluktuasi berdasarkan dinamika lelang real-time.) | Terverifikasi Lapangan |
| 1. Provisioning Kubernetes cluster mandiri menggunakan kubeadm pada OS Ubuntu 22.04 LTS. | 1. Provisioning Kubernetes cluster mandiri menggunakan kubeadm pada OS Ubuntu 22.04 LTS. | Terverifikasi Lapangan |
| 2. Deploy Zookeeper ensemble menggunakan StatefulSet dengan konfigurasi 3 replika. | 2. Deploy Zookeeper ensemble menggunakan StatefulSet dengan konfigurasi 3 replika. | Terverifikasi Lapangan |
- [TERVERIFIKASI] Volume pencarian bulanan untuk kata kunci redpanda kafka adalah 320 dengan kompetisi rendah (23). (Limitasi โ Analisis Implementasi Riil: Data spesifik untuk agregasi region US + SG + ID pada periode akses.) | Dampak Strategis: Terverifikasi Lapangan
- [TERVERIFIKASI] Estimasi bid lelang atas untuk redpanda kafka mencapai $11.22 USD. (Limitasi โ Analisis Implementasi Riil: Nilai bid dapat berfluktuasi berdasarkan dinamika lelang real-time.) | Dampak Strategis: Terverifikasi Lapangan
- 1. Provisioning Kubernetes cluster mandiri menggunakan kubeadm pada OS Ubuntu 22.04 LTS. โ Analisis Implementasi Riil: 1. Provisioning Kubernetes cluster mandiri menggunakan kubeadm pada OS Ubuntu 22.04 LTS. | Dampak Strategis: Terverifikasi Lapangan
- 2. Deploy Zookeeper ensemble menggunakan StatefulSet dengan konfigurasi 3 replika. โ Analisis Implementasi Riil: 2. Deploy Zookeeper ensemble menggunakan StatefulSet dengan konfigurasi 3 replika. | Dampak Strategis: Terverifikasi Lapangan
Deploying the Zookeeper Ensemble on Kubernetes
Zookeeper is a crucial component that provides coordination services for Kafka. In Kubernetes, Zookeeper is best deployed using a StatefulSet due to its requirement for stable network identities and persistent storage. We will configure a Zookeeper ensemble with three replicas to ensure fault tolerance.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: zookeeper
labels:
app: zookeeper
spec:
serviceName: "zookeeper-headless"
replicas: 3
selector:
matchLabels:
app: zookeeper
template:
metadata:
labels:
app: zookeeper
spec:
containers:
- name: zookeeper
image: confluentinc/cp-zookeeper:7.4.0
ports:
- containerPort: 2181
name: client
- containerPort: 2888
name: server
- containerPort: 3888
name: leader-election
env:
- name: ZOOKEEPER_CLIENT_PORT
value: "2181"
- name: ZOOKEEPER_TICK_TIME
value: "2000"
- name: ZOOKEEPER_INIT_LIMIT
value: "5"
- name: ZOOKEEPER_SYNC_LIMIT
value: "2"
- name: ZOOKEEPER_SERVER_ID
valueFrom:
fieldRef:
fieldPath: metadata.annotations['zookeeper.io/server-id']
- name: ZOOKEEPER_SERVERS
value: "zookeeper-0.zookeeper-headless.default.svc.cluster.local:2888:3888;zookeeper-1.zookeeper-headless.default.svc.cluster.local:2888:3888;zookeeper-2.zookeeper-headless.default.svc.cluster.local:2888:3888"
volumeMounts:
- name: data
mountPath: /var/lib/zookeeper/data
livenessProbe:
tcpSocket:
port: 2181
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
tcpSocket:
port: 2181
initialDelaySeconds: 10
periodSeconds: 5
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi
Note the use of ZOOKEEPER_SERVER_ID derived from pod annotations, and ZOOKEEPER_SERVERS which defines the list of all Zookeeper nodes in the ensemble. The StatefulSet will ensure each pod gets an isolated PersistentVolumeClaim (PVC) for Zookeeper data, maintaining state integrity even when pods are restarted or rescheduled. In scenarios where concurrency and consistency are paramount, such as systems requiring distributed lock architectures to prevent race conditions, Zookeeper plays a central role in providing reliable synchronization primitives.
Implementing Apache Kafka Brokers
With Zookeeper running stably, we can deploy the Apache Kafka brokers. Similar to Zookeeper, Kafka brokers also require stable network identities and persistent storage for message logs, making StatefulSet the appropriate choice. Each broker will connect to the Zookeeper ensemble we previously deployed.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: kafka
labels:
app: kafka
spec:
serviceName: "kafka-headless"
replicas: 3
selector:
matchLabels:
app: kafka
template:
metadata:
labels:
app: kafka
spec:
containers:
- name: kafka
image: confluentinc/cp-kafka:7.4.0
ports:
- containerPort: 9092
name: client
env:
- name: KAFKA_BROKER_ID
valueFrom:
fieldRef:
fieldPath: metadata.annotations['kafka.io/broker-id']
- name: KAFKA_ZOOKEEPER_CONNECT
value: "zookeeper-0.zookeeper-headless.default.svc.cluster.local:2181,zookeeper-1.zookeeper-headless.default.svc.cluster.local:2181,zookeeper-2.zookeeper-headless.default.svc.cluster.local:2181"
- name: KAFKA_LISTENER_SECURITY_PROTOCOL_MAP
value: "PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT"
- name: KAFKA_ADVERTISED_LISTENERS
value: "PLAINTEXT://kafka-$(KAFKA_BROKER_ID).kafka-headless.default.svc.cluster.local:9092"
- name: KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR
value: "3"
- name: KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR
value: "3"
- name: KAFKA_TRANSACTION_STATE_LOG_MIN_ISR
value: "2"
volumeMounts:
- name: data
mountPath: /var/lib/kafka/data
livenessProbe:
tcpSocket:
port: 9092
initialDelaySeconds: 60
periodSeconds: 10
readinessProbe:
tcpSocket:
port: 9092
initialDelaySeconds: 30
periodSeconds: 5
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 100Gi
The dynamic KAFKA_BROKER_ID configuration and KAFKA_ADVERTISED_LISTENERS referencing the stable hostname of the StatefulSet are crucial for ensuring brokers are reachable by clients and other brokers in the cluster. KAFKA_ZOOKEEPER_CONNECT points to the Zookeeper headless service, allowing brokers to discover the Zookeeper ensemble. To guarantee zero data loss, acks=all on producers and an appropriate min.insync.replicas on Kafka topics are essential.
Limitations, Load Testing, and Operational Mitigation
Despite its power, a Kafka-based event streaming architecture has inherent limitations. Kafka is not a total replacement for operational database systems (OLTP) as it is not designed for efficient ad-hoc queries or in-place data updates. It is also not suitable for large-scale ACID relational transactional workloads without a separate external storage layer. Strict data integrity and transactional consistency require additional architectural design on top of Kafka, such as using change data capture (CDC) logs that are then processed and stored in a relational or NoSQL database.
To validate cluster performance, load testing is an indispensable step. kafka-producer-perf-test is a built-in Kafka tool that is highly useful for measuring producer throughput and latency. By running these load tests, we can identify potential bottlenecks in disk I/O, network, or CPU, and adjust Kubernetes resource allocations or Kafka configurations accordingly.
# Example producer load test
kubectl exec -it kafka-0 -- kafka-producer-perf-test \
--topic test-topic \
--num-records 10000000 \
--record-size 100 \
--throughput -1 \
--producer-props bootstrap.servers=kafka-0.kafka-headless.default.svc.cluster.local:9092,kafka-1.kafka-headless.default.svc.cluster.local:9092,kafka-2.kafka-headless.default.svc.cluster.local:9092
Architectural capacity modeling indicates that Kafkaโs throughput heavily depends on disk I/O speed for log writes, network bandwidth for inter-broker replication, and CPU efficiency for message serialization/deserialization. A cluster with NVMe disks and a 10Gbps network can achieve hundreds of megabytes per second throughput per broker. End-to-end latency, on the other hand, is influenced by message batch size, disk flush frequency, and inter-node network latency.
Operational Mitigation and Failure Prevention
Operational management of a Kafka and Zookeeper cluster on Kubernetes requires proactive mitigation strategies:
- Isolate Problematic Pods: If a pod enters a
crash loop, immediately cordon off the node hosting that pod withkubectl cordon <node-name>to prevent new pods from being scheduled onto the problematic node. - Log Analysis: Examine pod logs using
kubectl logs <pod-name>to pinpoint root causes, such asOutOfMemoryError(OOM) or slow disk I/O issues. - Restart Zookeeper Transient Deadlock: Zookeeper can sometimes experience transient deadlocks during leader election. In such cases, restarting the involved Zookeeper pods can help restore consensus.
- Restore from Snapshot: In the event of a total persistent storage failure, restore the state from the last validated snapshot.
Conclusion of Event Streaming Architecture
Building a real-time event streaming architecture using Apache Kafka and Zookeeper on a self-managed Kubernetes cluster is a complex yet highly rewarding endeavor. It provides full control over the infrastructure, allowing for precise performance tuning to meet extreme throughput and latency demands. While there are operational management challenges and inherent platform limitations, a deep understanding of distributed system principles and the application of Kubernetes deployment best practices can result in a highly scalable and resilient system.
Transparency: Some links in this article are affiliate links that may earn us a commission at no additional cost to you.
About the Author: Iswan Putera is Principal Software Architect and Lead Technology Writer at Bijak Technology with over a decade of hands-on experience in distributed systems, Linux cloud infrastructure, and enterprise ERPNext implementations. Connect directly via LinkedIn, commercial portfolio Samkarsa, or email redaksi@bijaktechnology.com.
Explore More: Distributed Systems
Iswan Putera
Principal Software ArchitectSoftware Architect & Senior Systems Engineer with over a decade of hands-on expertise in distributed architectures, Linux private cloud deployments, and enterprise ERP implementations. Serves as Lead Technology Writer at Bijak Technology.
Social Media Share
Copy text or open your social media directly
Building a resilient real-time streaming system on Kubernetes is a complex task. Many architects struggle with default configurations that don't hold up under production load. (1/3)
The issue often isn't Kafka itself, but Zookeeper's coordination layer failing to maintain quorum during data spikes. Deep knowledge of distributed systems is essential. (2/3)
I've compiled a full guide and parameter architectural table to ensure stability. Read it here: https://bijaktechnology.com/en/blog/arsitektur-kafka-zookeeper-kubernetes-mandiri/ (3/3)
๐ก How to publish cleanly on Medium.com: