Most Kafka questions come down to six behaviours: where a keyed message lands, how a consumer group shares partitions, what happens when a broker dies, when an offset gets committed, how a consumer survives a duplicate, and where a message goes when it can never be processed. This post builds one small lab on a laptop and runs each of those against a real cluster. All the files are in huseyinbabal/kafka-on-kubernetes, and every output below was copied from that lab.
The lab
| Part | Version / shape |
|---|---|
| Kubernetes | kind, 1 control plane + 3 workers (Kubernetes 1.36.1) |
| Operator | Strimzi 1.3.1, installed with Helm |
| Kafka | 4.3.2, KRaft, 3 nodes that are each controller and broker |
| Apps | One Spring Boot 4.1.2 image (Java 25), three roles: analytics, mailer, ledger |
| Database | PostgreSQL 17, used by the mailer to record what it sent |
| UI | kafka-ui v0.1.1 |
Install Strimzi and a KRaft cluster
Strimzi is an operator. You describe a Kafka cluster as Kubernetes resources and it creates the pods, services and certificates, then keeps them in that state.
kind create cluster --config kind.yaml
kubectl create namespace kafka
helm install strimzi oci://quay.io/strimzi-helm/strimzi-kafka-operator --version 1.3.1 -n kafka
kubectl -n kafka rollout status deploy/strimzi-cluster-operator
The cluster itself is two resources. A KafkaNodePool says how many nodes and which roles they have, and the Kafka resource holds the version, listeners and broker config:
apiVersion: kafka.strimzi.io/v1
kind: KafkaNodePool
metadata:
name: dual
namespace: kafka
labels:
strimzi.io/cluster: orders-cluster
spec:
replicas: 3
roles:
- controller
- broker
storage:
type: ephemeral
---
apiVersion: kafka.strimzi.io/v1
kind: Kafka
metadata:
name: orders-cluster
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
entityOperator:
topicOperator: {}
Kafka 4 has no ZooKeeper mode. Cluster metadata lives in a Raft log kept by the controller nodes. With three nodes that each hold both roles, you can ask the quorum who leads it:
kubectl apply -f kafka.yaml
kubectl -n kafka wait kafka/orders-cluster --for=condition=Ready --timeout=600s
kubectl -n kafka exec -i orders-cluster-dual-0 -- \
bin/kafka-metadata-quorum.sh --bootstrap-server localhost:9092 describe --status
ClusterId: dic1xG9XQViqju2FSsHhfw
LeaderId: 1
LeaderEpoch: 1
HighWatermark: 50469
MaxFollowerLag: 0
MaxFollowerLagTimeMs: 410
CurrentVoters: [{"id": 0, ...}, {"id": 1, ...}, {"id": 2, ...}]
CurrentObservers: []output
Three voters, node 1 leads. A Raft quorum of three keeps working with one voter down.
Two lines in this file are lab shortcuts. storage: ephemeral loses all data when a pod restarts, so a real cluster uses persistent-claim. The listener has no TLS and no authentication, which is fine inside a kind cluster and nowhere else.
Topics as Kubernetes resources
The topicOperator entry turns KafkaTopic resources into real topics, so topics live in Git next to everything else:
apiVersion: kafka.strimzi.io/v1
kind: KafkaTopic
metadata:
name: clicks
namespace: kafka
labels:
strimzi.io/cluster: orders-cluster
spec:
partitions: 4
replicas: 3
kubectl apply -f topics.yaml
kubectl -n kafka get kafkatopics
NAME CLUSTER PARTITIONS REPLICATION FACTOR READY
clicks orders-cluster 4 3 True
emails orders-cluster 1 3 True
orders orders-cluster 1 3 True
payments orders-cluster 1 3 Trueoutput
Keys pick the partition
The producer hashes the key and takes it modulo the partition count. The same key always lands on the same partition while that count stays the same, which is what keeps one user’s events in order. Six keyed messages, then user-1 again, into a 4-partition topic:
alias kx='kubectl -n kafka exec -i orders-cluster-dual-0 --'
B='--bootstrap-server localhost:9092'
for i in 1 2 3 4 5 6; do echo "user-$i:click-$i"; done |
kx bin/kafka-console-producer.sh $B --topic keydemo \
--reader-property parse.key=true --reader-property key.separator=:
echo "user-1:click-7" | kx bin/kafka-console-producer.sh $B --topic keydemo \
--reader-property parse.key=true --reader-property key.separator=:
kx bin/kafka-console-consumer.sh $B --topic keydemo --from-beginning --timeout-ms 6000 \
--formatter-property print.key=true --formatter-property print.partition=true \
--formatter-property print.offset=true | sort
Partition:0 Offset:0 user-1 click-1
Partition:0 Offset:1 user-2 click-2
Partition:0 Offset:2 user-1 click-7
Partition:1 Offset:0 user-6 click-6
Partition:2 Offset:0 user-5 click-5
Partition:3 Offset:0 user-3 click-3
Partition:3 Offset:1 user-4 click-4output
click-7 went to partition 0 next to click-1. The spread is uneven: partition 0 got three messages and partition 1 one. With a handful of keys that is normal, so don’t expect an even split until there are many keys.
Ordering holds only inside a partition. Adding partitions later changes the modulo, and from then on existing keys can map to a different partition.
Consumer groups split the partitions
analytics runs as three pods in one group named analytics. Kafka gives each partition to exactly one member of the group:
kx bin/kafka-consumer-groups.sh $B --describe --group analytics
TOPIC PARTITION CONSUMER-ID
clicks 0 consumer-analytics-1-3633fab3-...
clicks 3 consumer-analytics-1-3633fab3-...
clicks 1 consumer-analytics-1-3d907b02-...
clicks 2 consumer-analytics-1-bdb84e14-...output
Four partitions, three consumers, so one pod holds two. A fifth pod would sit idle, because a partition never has two readers in the same group.
When a pod joins or leaves, the group rebalances. The app sets the cooperative sticky assignor:
spring:
kafka:
consumer:
properties:
partition.assignment.strategy: org.apache.kafka.clients.consumer.CooperativeStickyAssignor
With it, only the partitions that change owner are revoked. The older eager protocol stopped every member and took all partitions back before handing them out again. Scaling analytics from 3 to 2 and back to 3 moved partitions around while clicks kept flowing:
kubectl -n kafka scale deploy/analytics --replicas=2
kubectl -n kafka scale deploy/analytics --replicas=3
Losing a broker
orders has one partition with three replicas and min.insync.replicas: 2. Write 1000 records with acks=all, then delete the leader’s pod:
kx bin/kafka-producer-perf-test.sh --topic orders --num-records 1000 --record-size 100 \
--throughput -1 --producer-props bootstrap.servers=localhost:9092 acks=all
kx bin/kafka-topics.sh $B --describe --topic orders
kubectl -n kafka delete pod orders-cluster-dual-2 --wait=false
sleep 6
kx bin/kafka-topics.sh $B --describe --topic orders
kx bin/kafka-get-offsets.sh $B --topic orders
1000 records sent, 7299.270073 records/sec (0.70 MB/sec), 22.84 ms avg latency, ...
Partition: 0 Leader: 2 Replicas: 1,2,0 Isr: 0,1,2
pod "orders-cluster-dual-2" deleted from kafka namespace
Partition: 0 Leader: 1 Replicas: 1,2,0 Isr: 0,1
orders:0:1000output
Node 1 took over as leader and node 2 dropped out of the ISR (in-sync replicas). The partition still ends at offset 1000, so nothing that had been acknowledged was lost. When the pod came back and caught up, it rejoined the ISR as 0,1,2.
The two settings work together. acks=all makes the leader wait for every replica in the ISR before it acknowledges. min.insync.replicas: 2 makes it reject writes when the ISR shrinks below two. With three replicas you can lose one broker and keep writing. Lose a second and producers get NotEnoughReplicas errors instead of writes that only one disk holds.
When the offset is committed
The mailer reads emails, records each mail in PostgreSQL, and commits offsets by hand (enable-auto-commit: false, ack-mode: manual-immediate). The only thing that changes between the two modes is the order of two calls:
if (mode.equals("at-most-once")) {
commit(ack, email); // commit first
crashOnce(msgId);
sendMail(msgId); // then do the work
} else {
sendMail(msgId); // do the work first
crashOnce(msgId);
commit(ack, email); // then commit
}
crashOnce is lab code: it halts the JVM the first time it sees promo-8. Kubernetes restarts the container, and the new consumer continues from the last committed offset. Three messages go in: welcome-7, promo-8, news-9.
At-least-once: the mail is sent, the pod dies before the commit, and the restarted pod reads promo-8 again.
id | msg_id
----+-----------
1 | welcome-7
2 | promo-8
3 | promo-8
4 | news-9
(4 rows)output
At-most-once: the commit happens first, the pod dies before sending, and the restarted pod starts after promo-8.
id | msg_id
----+-----------
1 | welcome-7
2 | news-9
(2 rows)output
The first mode can send a mail twice, and the second can lose one. Most systems choose at-least-once and make the consumer safe to run twice.
An idempotent consumer
enable.idempotence: true on the producer (the default since Kafka 3.0) stops the broker from writing the same batch twice when a producer retries. It does nothing for the duplicate above, because the second promo-8 was a consumer reading again, not a producer retrying. That needs a check on the consumer side. Here it is a unique key in PostgreSQL:
if (idempotent && db.update(
"INSERT INTO processed (msg_id) VALUES (?) ON CONFLICT (msg_id) DO NOTHING", msgId) == 0) {
log.info("{} already processed, skipping", msgId);
return;
}
The same crash, in at-least-once mode with MAILER_IDEMPOTENT=true:
$ kubectl -n kafka logs deploy/mailer | grep already
07:32:15 INFO MailerListener - promo-8 already processed, skipping
id | msg_id
----+-----------
1 | welcome-7
2 | promo-8
3 | news-9
(3 rows)output
One gap is still open. In this lab code the processed insert and the mail_log insert are two statements. A crash between them would mark a mail as processed without logging it. In production, put both in one database transaction, or use a message ID that the downstream system deduplicates itself.
Retry topic and dead letter queue
ledger parses id;amount from payments. pay-77;12,50 has a comma where BigDecimal expects a dot, so it fails every time. Retrying it in place would block the partition behind it. Spring Kafka’s @RetryableTopic moves it aside instead:
@RetryableTopic(
attempts = "3",
backOff = @BackOff(delay = 2000),
retryTopicSuffix = "-retry",
dltTopicSuffix = "-dlq",
sameIntervalTopicReuseStrategy = SameIntervalTopicReuseStrategy.SINGLE_TOPIC)
@KafkaListener(topics = "payments", groupId = "ledger")
public void onPayment(ConsumerRecord<String, String> payment) {
String[] parts = payment.value().split(";");
log.info("{} read from {}", parts[0], payment.topic());
BigDecimal amount = new BigDecimal(parts[1]);
log.info("{} posted to ledger: {}", parts[0], amount);
}
@DltHandler
public void onDeadLetter(ConsumerRecord<String, String> payment,
@Header(KafkaHeaders.EXCEPTION_MESSAGE) String error) {
log.error("DLQ <- {} ({})", payment.value(), error);
}
printf 'pay-76;10.00\npay-77;12,50\npay-78;8.75\n' |
kx bin/kafka-console-producer.sh $B --topic payments
kubectl -n kafka logs deploy/ledger | grep -E "pay-7|DLQ"
21:32:02 INFO LedgerListener - pay-76 read from payments
21:32:02 INFO LedgerListener - pay-76 posted to ledger: 10.00
21:32:02 INFO LedgerListener - pay-77 read from payments
21:32:02 INFO LedgerListener - pay-78 read from payments
21:32:02 INFO LedgerListener - pay-78 posted to ledger: 8.75
21:32:04 INFO LedgerListener - pay-77 read from payments-retry
21:32:06 INFO LedgerListener - pay-77 read from payments-retry
21:32:06 ERROR LedgerListener - DLQ <- pay-77;12,50 (Listener failed; Character , is neither a decimal digit number, decimal point, nor "e" notation exponential mark.)output
pay-78 was posted right after pay-77 failed, without waiting for it. pay-77 was tried three times in total, two seconds apart, then parked in payments-dlq. The record in the DLQ carries headers saying where it came from and why it failed:
kx bin/kafka-console-consumer.sh $B --topic payments-dlq --from-beginning --timeout-ms 5000 \
--formatter-property print.headers=true
kafka_original-topic:payments
kafka_dlt-original-consumer-group:ledger
kafka_exception-fqcn:org.springframework.kafka.listener.ListenerExecutionFailedException
kafka_exception-cause-fqcn:java.lang.NumberFormatExceptionoutput
That is enough to fix the data and send the record back to payments by hand. A retry topic only helps with errors that can go away, such as a timeout or a database that is down for a moment. A parse error like this one will fail on every attempt, so in a real service, mark that exception as not retryable and send it straight to the DLQ.
What this lab leaves out
- Persistent storage, rack awareness and pod disruption budgets for the brokers.
- TLS and authentication on the listener (Strimzi can manage both with
KafkaUserresources). - Transactions and exactly-once processing between topics.
- Monitoring: Strimzi ships example Prometheus and Grafana configs for broker and consumer lag metrics.
- Schemas. The values here are plain strings, so nothing stops a producer from sending
12,50.