Lesson 05 of 17 · Foundations
Lab: Kafka on your Kubernetes cluster
Run the same Kafka lab on a Kubernetes cluster you already have. Install the Strimzi operator with Helm, create a three-node KRaft cluster from one YAML file, create topics as KafkaTopic resources and with the CLI, produce and consume from pods, write a small Python producer and consumer that run as pods, and delete a broker pod to watch Kafka keep working and the pod come back with the same identity and disk. Every output shown comes from a real run on Strimzi 1.3.1 with Kafka 4.3.2.
What you will build
Lesson 4 ran Kafka in Docker. Here you run the same ideas on a Kubernetes cluster you already have, the way most platforms run Kafka: through an operator.
Running Kafka by hand on Kubernetes is like looking after three fish tanks yourself. Strimzi is the aquarium keeper: you write on a card "three tanks, this big, this water", and the keeper sets them up, checks them, and replaces a broken tank with one that has the same fish in it.
Before you start
| You need | Check with | Why |
|---|---|---|
| A cluster you may change (test or lab, not production) | kubectl config current-context |
You install an operator and cluster-wide CRDs |
| A default StorageClass | kubectl get storageclass (one marked (default)) |
Each broker gets a PersistentVolumeClaim |
| About 3–4 GB of free memory, ideally 3 worker nodes | kubectl top nodes |
Three Kafka pods; one node works too, but then a node failure can't be shown |
| Helm 3 | helm version |
To install the operator |
No cluster? Create a throw-away one with three workers:
cat > kind.yaml <<'EOF'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker
- role: worker
EOF
kind create cluster --name kafka-lab --config kind.yaml
Step 1: install the Strimzi operator
$ helm repo add strimzi https://strimzi.io/charts/
$ helm install strimzi strimzi/strimzi-kafka-operator --version 1.3.1 -n kafka --create-namespace
$ kubectl -n kafka rollout status deploy/strimzi-cluster-operator
deployment "strimzi-cluster-operator" successfully rolled out
$ kubectl get crd | grep kafka.strimzi.io
kafkabridges.kafka.strimzi.io
kafkaconnectors.kafka.strimzi.io
kafkaconnects.kafka.strimzi.io
kafkamirrormaker2s.kafka.strimzi.io
kafkanodepools.kafka.strimzi.io
kafkarebalances.kafka.strimzi.io
kafkas.kafka.strimzi.io
kafkatopics.kafka.strimzi.io
kafkausers.kafka.strimzi.io
The operator is a Deployment that watches the kafka namespace for these new resource types.
Step 2: create a three-node Kafka cluster
Save as kafka-lab.yaml:
apiVersion: kafka.strimzi.io/v1
kind: KafkaNodePool
metadata:
name: dual-role
namespace: kafka
labels: { strimzi.io/cluster: lab } # belongs to the Kafka called "lab"
spec:
replicas: 3
roles: [ controller, broker ] # each node does both jobs (KRaft)
resources:
requests: { cpu: 250m, memory: 1Gi }
limits: { memory: 1Gi }
storage:
type: jbod
volumes:
- { id: 0, type: persistent-claim, size: 5Gi, deleteClaim: true, kraftMetadata: shared }
---
apiVersion: kafka.strimzi.io/v1
kind: Kafka
metadata:
name: lab
namespace: kafka
spec:
kafka:
version: 4.3.2
listeners:
- { name: plain, port: 9092, type: internal, tls: false }
config:
default.replication.factor: 3
min.insync.replicas: 2
offsets.topic.replication.factor: 3
transaction.state.log.replication.factor: 3
transaction.state.log.min.isr: 2
entityOperator:
topicOperator: {}
userOperator: {}
KafkaNodePooldescribes a group of nodes: how many, which roles (controller, broker or both), disk and memory. Production usually has a pool of 3 controllers and a separate pool of brokers (lesson 13).Kafkadescribes the cluster as a whole: version, listeners, settings.- The plain internal listener keeps the lab simple. Lesson 14 and the platform project switch to mTLS with a
KafkaUserper application.
$ kubectl apply -f kafka-lab.yaml
kafkanodepool.kafka.strimzi.io/dual-role created
kafka.kafka.strimzi.io/lab created
$ kubectl wait kafka/lab -n kafka --for=condition=Ready --timeout=10m
kafka.kafka.strimzi.io/lab condition met
$ kubectl get kafka,kafkanodepool,pods,pvc,svc -n kafka
NAME READY WARNINGS KAFKA VERSION METADATA VERSION
kafka.kafka.strimzi.io/lab True 4.3.2 4.3-IV0
NAME DESIRED REPLICAS ROLES NODEIDS
kafkanodepool.kafka.strimzi.io/dual-role 3 ["controller","broker"] [0,1,2]
NAME READY STATUS RESTARTS AGE
pod/lab-dual-role-0 1/1 Running 0 105s
pod/lab-dual-role-1 1/1 Running 0 104s
pod/lab-dual-role-2 1/1 Running 0 104s
pod/lab-entity-operator-bdbfc5cc9-l7zl9 2/2 Running 0 21s
pod/strimzi-cluster-operator-78fd4f9d5c-5qcjl 1/1 Running 0 2m27s
NAME STATUS CAPACITY ACCESS MODES STORAGECLASS
persistentvolumeclaim/data-0-lab-dual-role-0 Bound 5Gi RWO standard
persistentvolumeclaim/data-0-lab-dual-role-1 Bound 5Gi RWO standard
persistentvolumeclaim/data-0-lab-dual-role-2 Bound 5Gi RWO standard
NAME TYPE CLUSTER-IP PORT(S)
service/lab-kafka-bootstrap ClusterIP 10.96.59.250 9091/TCP,9092/TCP
service/lab-kafka-brokers ClusterIP None 9090/TCP,9091/TCP,8443/TCP,9092/TCP
Some columns of the PVC and Service lists are left out above. On a kind cluster on a laptop the whole step took about two minutes.
| What appeared | What it is |
|---|---|
lab-dual-role-0..2 |
The Kafka pods, named cluster-pool-ID. The number is the Kafka node ID, kept across restarts |
data-0-lab-dual-role-N |
One PersistentVolumeClaim per node: where the log segments live |
lab-kafka-bootstrap |
The address applications use: lab-kafka-bootstrap.kafka.svc:9092 |
lab-kafka-brokers |
A headless service: one DNS name per broker, used by clients after bootstrap |
lab-entity-operator |
The Topic Operator and User Operator, which turn KafkaTopic and KafkaUser YAML into real topics and users |
Step 3: create a topic, the Kubernetes way
Save as topic-orders.yaml (this is what you would keep in Git):
apiVersion: kafka.strimzi.io/v1
kind: KafkaTopic
metadata:
name: orders
namespace: kafka
labels: { strimzi.io/cluster: lab }
spec:
partitions: 3
replicas: 3
config:
retention.ms: 604800000 # 7 days
min.insync.replicas: 2
$ kubectl apply -f topic-orders.yaml
kafkatopic.kafka.strimzi.io/orders created
$ kubectl get kafkatopic -n kafka
NAME CLUSTER PARTITIONS REPLICATION FACTOR READY
orders lab 3 3 True
Every CLI tool from lesson 4 works too; only docker exec becomes kubectl exec. A small shell function saves typing (it works in bash and zsh):
$ k() { kubectl -n kafka exec -it lab-dual-role-0 -- "$@"; }
$ k bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders
Topic: orders TopicId: d9po8xcDQICyHC90TlYlBQ PartitionCount: 3 ReplicationFactor: 3 Configs: min.insync.replicas=2,retention.ms=604800000
Topic: orders Partition: 0 Leader: 2 Replicas: 2,0,1 Isr: 2,0,1 Elr: LastKnownElr:
Topic: orders Partition: 1 Leader: 0 Replicas: 0,1,2 Isr: 0,1,2 Elr: LastKnownElr:
Topic: orders Partition: 2 Leader: 1 Replicas: 1,2,0 Isr: 1,2,0 Elr: LastKnownElr:
Three partitions, each with three replicas spread over the three nodes, and a different leader for each.
One owner per topic
When a KafkaTopic resource manages a topic, change it only through the YAML. In the test run, kafka-configs.sh --alter … retention.ms=3600000 reported success, and the Topic Operator set retention.ms back to 7 days at its next reconciliation. That's the point: Git stays the source of truth.
Step 4: produce and consume with the console tools
Run short-lived client pods with the same image as the brokers, so the tools match the cluster version:
$ IMG=$(kubectl -n kafka get pod lab-dual-role-0 -o jsonpath='{.spec.containers[0].image}')
$ echo $IMG
quay.io/strimzi/kafka:1.3.1-kafka-4.3.2
$ B=lab-kafka-bootstrap.kafka.svc:9092
$ kubectl -n kafka run producer -it --rm --restart=Never --image="$IMG" -- \
bin/kafka-console-producer.sh --bootstrap-server $B --topic orders \
--reader-property parse.key=true --reader-property key.separator=:
>A-17:{"amount":42.50}
>A-18:{"amount":10.00}
>A-17:{"status":"paid"}
Press Ctrl-D to finish. Then read them as the billing group (Ctrl-C to stop):
$ kubectl -n kafka run consumer -it --rm --restart=Never --image="$IMG" -- \
bin/kafka-console-consumer.sh --bootstrap-server $B --topic orders --group billing \
--from-beginning --formatter-property print.key=true --formatter-property print.partition=true
Partition:0 A-17 {"amount":42.50}
Partition:0 A-18 {"amount":10.00}
Partition:0 A-17 {"status":"paid"}
Processed a total of 3 messages
$ k bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
Consumer group 'billing' has no active members.
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
billing orders 0 3 3 0 - - -
billing orders 1 0 0 0 - - -
billing orders 2 0 0 0 - - -
Kafka 4.3 renamed the console tools' --property option to --reader-property (producer) and --formatter-property (consumer); the old name still works with a deprecation warning. Here both keys happened to hash to partition 0; with more keys the records spread over all three.
Step 5: your application must send the events
Installing Kafka moves no data. Kafka never connects to an application to collect anything: the application must contain a Kafka client library and send each event itself. Here is a minimal producer and consumer in Python, run as pods exactly as a real service would be.
producer.py: wherever the business action happens, the app also sends an event:
import json, os
from confluent_kafka import Producer
producer = Producer({
"bootstrap.servers": os.environ["KAFKA_BOOTSTRAP_SERVERS"], # set by the pod spec
"acks": "all", # wait until min.insync.replicas have it
"enable.idempotence": True, # retries never create duplicates
})
def delivered(err, msg):
if err:
print(f"send failed: {err}")
else:
print(f"stored {msg.key().decode()} in {msg.topic()} partition {msg.partition()} offset {msg.offset()}")
def place_order(order):
# save_to_database(order) would happen here
producer.produce(os.environ["KAFKA_TOPIC"], key=order["id"], value=json.dumps(order), callback=delivered)
producer.poll(0) # runs delivery callbacks
for i, (oid, amount) in enumerate([("A-19", 25.00), ("B-07", 99.90), ("C-31", 12.40), ("A-19", 25.00)]):
place_order({"id": oid, "amount": amount, "status": "paid" if i == 3 else "placed"})
producer.flush(10) # send whatever is still buffered before exiting
consumer.py: another application reads the events and does its work:
import json, os
from confluent_kafka import Consumer
consumer = Consumer({
"bootstrap.servers": os.environ["KAFKA_BOOTSTRAP_SERVERS"],
"group.id": "billing-py",
"auto.offset.reset": "earliest", # a new group starts from the oldest record
"enable.auto.commit": False, # commit only after the work is done
})
consumer.subscribe(["orders"])
def create_invoice(order, msg):
print(f"invoice for {order.get('id', msg.key().decode())} (partition {msg.partition()}, offset {msg.offset()})")
seen, empty = 0, 0
while empty < 10: # a real service loops forever; the demo stops when idle
msg = consumer.poll(1.0)
if msg is None:
empty += 1; continue
if msg.error():
print(msg.error()); continue
create_invoice(json.loads(msg.value()), msg)
consumer.commit(message=msg, asynchronous=False)
seen, empty = seen + 1, 0
consumer.close()
print(f"processed {seen} events")
Put the code in a ConfigMap and run each script in a pod. The address comes from an environment variable, as it would in a real Deployment. Save as producer-pod.yaml:
apiVersion: v1
kind: Pod
metadata: { name: orders-producer, namespace: kafka }
spec:
restartPolicy: Never
containers:
- name: app
image: python:3.12-slim
command: [ "sh", "-c", "pip install -q confluent-kafka==2.* && python -u /app/producer.py" ]
env:
- { name: KAFKA_BOOTSTRAP_SERVERS, value: "lab-kafka-bootstrap.kafka.svc:9092" }
- { name: KAFKA_TOPIC, value: "orders" }
volumeMounts: [ { name: code, mountPath: /app } ]
volumes: [ { name: code, configMap: { name: demo-app } } ]
consumer-pod.yaml is the same with name: billing-consumer, python -u /app/consumer.py, and without KAFKA_TOPIC. Run the producer, wait for it to finish, then the consumer:
$ kubectl -n kafka create configmap demo-app --from-file=producer.py --from-file=consumer.py
$ kubectl apply -f producer-pod.yaml
$ kubectl -n kafka wait pod/orders-producer --for=jsonpath='{.status.phase}'=Succeeded --timeout=3m
$ kubectl -n kafka logs orders-producer
stored C-31 in orders partition 0 offset 3
stored B-07 in orders partition 1 offset 0
stored A-19 in orders partition 2 offset 0
stored A-19 in orders partition 2 offset 1
$ kubectl apply -f consumer-pod.yaml
$ kubectl -n kafka wait pod/billing-consumer --for=jsonpath='{.status.phase}'=Succeeded --timeout=3m
$ kubectl -n kafka logs billing-consumer
invoice for B-07 (partition 1, offset 0)
invoice for A-17 (partition 0, offset 0)
invoice for A-18 (partition 0, offset 1)
invoice for A-17 (partition 0, offset 2)
invoice for C-31 (partition 0, offset 3)
invoice for A-19 (partition 2, offset 0)
invoice for A-19 (partition 2, offset 1)
processed 7 events
Read the output carefully:
- Same key, same partition: both
A-19events went to partition 2, one after the other, so their order is kept. - The callbacks arrived in a different order from the sends: delivery is reported per partition batch. Order is guaranteed within a partition, not across partitions.
- The new group
billing-pystarted from the earliest offset, so it also read the three records from step 4: groups are independent.
| Language | Common client library |
|---|---|
| Java, Kotlin, Spring | kafka-clients (official), Spring for Apache Kafka |
| Python | confluent-kafka |
| Go | franz-go, confluent-kafka-go |
| Node.js | @confluentinc/kafka-javascript, kafkajs |
| .NET | Confluent.Kafka |
Can't change the application? Something else can produce for it: Fluent Bit for its log lines, Debezium for the rows it writes to its database (lesson 12), a REST proxy for webhooks, or the OpenTelemetry Collector for telemetry.
Where applications connect from
| Where is the client? | How it connects |
|---|---|
| A pod in the same cluster, any namespace | lab-kafka-bootstrap.kafka.svc:9092 (unless a NetworkPolicy blocks it) |
| Your laptop, for a quick test | kubectl port-forward does not work reliably: after bootstrap the client is sent to each broker's in-cluster address. Run the client as a pod instead |
| Outside the cluster, for real | Add an external listener (nodeport, loadbalancer, ingress or route) so every broker gets a reachable address (lesson 13) |
Step 6: delete a broker and watch Kafka cope
$ kubectl -n kafka delete pod lab-dual-role-2
$ k bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders --under-replicated-partitions
Topic: orders Partition: 0 Leader: 0 Replicas: 2,0,1 Isr: 0,1 Elr: LastKnownElr:
Topic: orders Partition: 1 Leader: 0 Replicas: 0,1,2 Isr: 0,1 Elr: LastKnownElr:
Topic: orders Partition: 2 Leader: 1 Replicas: 1,2,0 Isr: 1,0 Elr: LastKnownElr:
- Node 2 dropped out of every ISR. Partition 0, which it led, got a new leader (node 0) within seconds.
- With two replicas still in sync and
min.insync.replicas: 2, producers usingacks=allkeep working.
$ kubectl -n kafka wait pod/lab-dual-role-2 --for=condition=Ready --timeout=5m
pod/lab-dual-role-2 condition met
$ kubectl -n kafka get pod lab-dual-role-2 \
-o jsonpath='{.spec.nodeName} {.spec.volumes[?(@.name=="data-0")].persistentVolumeClaim.claimName}{"\n"}'
kafka-lab-worker2 data-0-lab-dual-role-2
$ k bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders
Topic: orders TopicId: d9po8xcDQICyHC90TlYlBQ PartitionCount: 3 ReplicationFactor: 3 Configs: min.insync.replicas=2,retention.ms=604800000
Topic: orders Partition: 0 Leader: 0 Replicas: 2,0,1 Isr: 0,1,2 Elr: LastKnownElr:
Topic: orders Partition: 1 Leader: 0 Replicas: 0,1,2 Isr: 0,1,2 Elr: LastKnownElr:
Topic: orders Partition: 2 Leader: 1 Replicas: 1,2,0 Isr: 0,1,2 Elr: LastKnownElr:
The new pod has the same name, node ID and PersistentVolumeClaim, so it only fetched the records it missed and is back in every ISR. Leadership of partition 0 stays on node 0 until a preferred leader election moves it back:
$ k bin/kafka-leader-election.sh --bootstrap-server localhost:9092 --election-type preferred --all-topic-partitions
Successfully completed leader election (PREFERRED) for partitions __consumer_offsets-47, …, orders-0, …
$ k bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders | grep "Partition: 0"
Topic: orders Partition: 0 Leader: 2 Replicas: 2,0,1 Isr: 0,1,2 Elr: LastKnownElr:
| Task | Docker (lessons 4, 8) | Kubernetes (this lab) |
|---|---|---|
| Start Kafka | docker run / compose |
Helm install Strimzi, then the Kafka YAML |
| Run a CLI tool | docker exec kafka-1 … |
kubectl exec lab-dual-role-0 -- bin/… |
| Create a topic | kafka-topics.sh --create |
KafkaTopic YAML (or the CLI) |
| Kill a broker | docker stop kafka-2, then start it yourself |
kubectl delete pod lab-dual-role-2: it comes back by itself |
| Change a setting | Edit the environment, restart the container | Edit the Kafka resource: the operator restarts pods one at a time, safely |
Step 7: clean up
$ kubectl -n kafka delete pod orders-producer billing-consumer --ignore-not-found
$ kubectl delete kafkatopic --all -n kafka
$ kubectl delete -f kafka-lab.yaml # deleteClaim: true also removes the PVCs
$ helm uninstall strimzi -n kafka
$ kubectl delete namespace kafka
$ kubectl get crd -o name | grep kafka.strimzi.io # the 9 CRDs stay after helm uninstall
$ kubectl get crd -o name | grep kafka.strimzi.io | xargs kubectl delete # only if nothing else uses Strimzi
If you created the kind cluster for this lab: kind delete cluster --name kafka-lab.
Try it
- Change
spec.partitionsof theorderstopic from 3 to 6 and apply:READYstaysTrue. Then try 2:kubectl get kafkatopic orders -n kafkashowsREADY False, and its condition saysDecreasing partitions not supported. - Add
log.retention.hours: 48underspec.kafka.configand watch the operator restart the pods one at a time (kubectl get pods -n kafka -w). - Stop the consumer pod, run the producer again, and read the lag with
kafka-consumer-groups.sh. - Change the consumer into a Deployment with 3 replicas and a loop that never ends; check with
--describe --membersthat each pod got one partition. - Drain the node that runs
lab-dual-role-1(kubectl drain) and see whether the pod can move: it depends on whether your StorageClass volumes can follow it.
Going deeper
- Production shape: separate controller and broker pools, rack awareness across zones, an mTLS listener with a
KafkaUserper application, ACLs and quotas (lessons 13 and 14). - Collect metrics with the JMX exporter (
metricsConfig) into Prometheus and alert on under-replicated partitions and lag (lesson 15). - Deliver
KafkaTopicandKafkaUserresources through GitOps, as in the project Kafka as a platform service with Strimzi.
Recap
- Strimzi turns YAML (
Kafka,KafkaNodePool,KafkaTopic,KafkaUser) into broker pods, volumes, services, topics and users. - Pods are named cluster-pool-ID; each keeps its node ID and PVC across restarts.
- Applications connect to the bootstrap service; outside the cluster you need an external listener, not port-forward.
- Kafka collects nothing by itself: an application's producer code sends the events, and consumer groups read them.
- Deleting a broker pod shrinks the ISR, moves leadership, and heals automatically.
This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.