The one-line mental model
Kafka on Kubernetes works when an operator, most often Strimzi, translates declarative custom resources into correct broker configuration, StatefulSet rollouts and persistent volume claims, so the cluster reconciles toward a declared state instead of relying on hand-edited server scripts.
You will be able to explain why brokers need StatefulSets, how persistent volumes back log directories, how rolling upgrades avoid downtime, and where autoscaling helps versus where it hurts a stateful system.
Prerequisites
- !Kubernetes basics: pods, services, deployments and persistent volumes
- !Kafka fundamentals: brokers, topics, replication and ISR
What You'll Learn
- 1Map Kafka concepts onto StatefulSets and headless services correctly
- 2Configure persistent volumes and storage classes for broker logs
- 3Run zero-downtime rolling upgrades with the Strimzi operator
- 4Decide when autoscaling is safe for a stateful broker fleet
Why StatefulSets, not Deployments
A Kafka broker is identified by its position in the cluster. Its broker id maps to a log directory, that directory maps to a persistent volume, and replication factors reference specific broker ids. A Kubernetes Deployment treats pods as interchangeable and assigns random names, which is exactly wrong for a broker whose identity must survive a restart. StatefulSets give each broker a stable identity: a sequential name such as kafka-0, kafka-1, kafka-2, a stable network identity through a headless service, and a stable volume that follows the pod across restarts.
The headless service is the second half of the pattern. A normal ClusterIP service load-balances across ready pods, which would route a client to whichever broker happens to be healthy. Kafka clients need bootstrap connectivity and then direct per-broker connections based on advertised listeners, so the headless service provides individual DNS entries for each pod. The cluster IP service or a load balancer is still useful for the initial bootstrap endpoint, but the advertised listener each broker returns must resolve to something long-lived, which is where node port, load balancer per broker, or a custom DNS controller comes in.
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
name: orders-cluster
spec:
kafka:
version: 3.7.0
replicas: 3
listeners:
- name: plain
port: 9092
type: internal
tls: false
- name: tls
port: 9093
type: route
tls: true
config:
offsets.topic.replication.factor: 3
transaction.state.log.replication.factor: 3
transaction.state.log.min.isr: 2
default.replication.factor: 3
min.insync.replicas: 2
inter.broker.protocol.version: "3.7"
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 500Gi
class: fast-ssd
deleteClaim: false
zookeeper:
replicas: 3
storage:
type: persistent-claim
size: 100Gi
class: fast-ssd
deleteClaim: false
Three settings in that manifest deserve attention in an interview. deleteClaim: false keeps the volume when the Kafka custom resource is deleted, which is the difference between a recoverable decommission and a data-loss incident. min.insync.replicas: 2 paired with default.replication.factor: 3 means a single broker failure is survivable without acknowledging writes that no in-sync replica holds. And the transaction state log settings mirror the same replication discipline, because exactly-once semantics depend on those internal topics being as durable as the data they protect.
Storage: the decision that limits everything else
Kafka's performance characteristics assume sequential append to local disk. That assumption shapes the storage decision more than any other choice in the deployment. Network-attached storage that adds latency to every append will show up as elevated produce latency and reduced throughput, and the effect compounds under load. The practical hierarchy, from best to worst for Kafka, is local NVMe volumes with a local storage class, then high-performance network block storage such as EBS io2 or equivalent, then general purpose network storage, and finally object storage which is unsuitable for broker logs entirely.
Kubernetes expresses this through storage classes. A storage class named fast-ssd backed by local NVMe or premium block storage maps onto the volume claim in the Kafka custom resource. Capacity planning should account for the fact that Kafka retains log segments until retention policies delete them, and that under-replicated topics or a stuck rebalance can pin data longer than expected. A common operational rule is to provision at least as much as your largest topic's retention window implies, plus headroom for recovery.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: fast-ssd
provisioner: ebs.csi.aws.com
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
parameters:
type: gp3
iops: "6000"
throughput: "250"
reclaimPolicy: Retain
Volume expansion is worth enabling explicitly, because the alternative, decommissioning and re-provisioning a broker, involves a controlled restart that the operator can perform but that still takes the cluster through a rolling rebalance. Expansion in place, where the storage class and the CSI driver support it, turns a capacity emergency into a routine maintenance window.
Rolling upgrades without downtime
The Strimzi operator owns the rolling upgrade. When you update the Kafka version or the broker configuration in the custom resource, the operator performs a rolling restart one broker at a time, waiting for each broker to rejoin the in-sync replica set before moving to the next. The precondition for zero downtime is that every topic has a replication factor of at least three and a min.insync.replicas that tolerates one broker being unavailable. With those settings, a single broker out of service during the rollout never forces a producer to fail.
The upgrade order matters for version changes. The operator and the Kafka version in the CRD must support the target version, so upgrade the operator first when its release notes call for it, then the Kafka cluster. For protocol version changes, set inter.broker.protocol.version to the current version before the upgrade and only raise it after every broker is on the new version. This two-step dance prevents a broker that has not yet restarted from speaking a protocol its peers do not understand.
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaNodePool
metadata:
name: broker-pool
labels:
strimzi.io/cluster: orders-cluster
spec:
replicas: 3
roles:
- broker
storage:
type: jbod
volumes:
- id: 0
type: persistent-claim
size: 500Gi
class: fast-ssd
deleteClaim: false
resources:
requests:
cpu: "2"
memory: 4Gi
limits:
cpu: "4"
memory: 8Gi
Node pools let you scale brokers independently of controller roles in KRaft mode, which simplifies capacity planning: add a node pool entry to add brokers, remove one to decommission, and let the operator handle the membership changes and partition reassignment orchestration.
Networking and client connectivity
Clients reach the cluster through a bootstrap server address, and after that first connection each broker returns its advertised listener. On Kubernetes the advertised listener must be resolvable from wherever clients run, which is often a different namespace or cluster. The plain listener on port 9092 works for in-cluster clients using the headless service DNS. External clients need a route, a load balancer service, or an ingress with TLS termination, and the advertised listener for that port must point at the externally resolvable name rather than the internal pod DNS.
Network policies are the guardrail most deployments skip. A default deny policy that only allows broker-to-broker traffic on the replication port, client traffic on the listener ports, and metrics scraping from the monitoring namespace turns the cluster from an open network into an explicit graph. Pair it with TLS between brokers when the cluster spans availability zones, and with SASL authentication for clients, so that a compromised application pod cannot join the cluster and consume restricted topics.
Autoscaling: where it helps and where it does not
Horizontal pod autoscaling on brokers is rarely the right lever, because adding a broker does not add capacity to an existing topic. Partitions are fixed at creation, replicas are assigned to specific brokers, and a new broker only helps when a rebalance moves partitions onto it or when new topics are created. Vertical scaling of broker resources, which Strimzi supports through the node pool resources block, helps when the constraint is CPU or heap rather than disk or partition count.
What autoscales cleanly on Kubernetes is everything around the brokers: the Connect workers that move data in and out, the Stream applications processing it, and the schema registry serving metadata. Those are stateless or externally stateful workloads that scale horizontally without rebalancing partition assignments. A sensible platform therefore treats the broker fleet as a carefully sized stateful tier, and treats the processing tier as an elastic layer that scales on consumer lag or request rate.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: orders-connect-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: orders-connect
minReplicas: 2
maxReplicas: 12
metrics:
- type: Pods
pods:
metric:
name: kafka_consumer_lag
target:
type: AverageValue
averageValue: "5000"
Monitoring and day-two operations
A Kafka cluster on Kubernetes is only as operable as its metrics pipeline. Export broker metrics through JMX exporter or the Strimzi metrics config, scrape them with Prometheus, and build dashboards that cover the four signals that predict incidents: under-replicated partitions, offline partitions, consumer group lag, and disk utilization per broker. Alert on the first two immediately, on lag growth rather than absolute lag, and on disk before it reaches the point where log cleaning cannot keep up.
Pod disruption budgets protect against voluntary evictions during node maintenance. A budget that allows one broker down at a time, combined with the operator's rolling logic, keeps upgrades and node rotations from cascading into an outage. Pair it with topology spread constraints or anti-affinity so the three brokers do not land on the same node or the same availability zone, because a cluster that survives a broker restart but loses two brokers to a zone failure has not actually been designed for resilience.
Log shipping is the last piece. Broker logs, controller logs and operator logs should flow to a central store with enough retention to reconstruct an incident. The most common post-incident question, what changed in the minute before the leader election storm, is unanswerable if the logs died with the pods. Treat log retention as part of the recovery story rather than as a storage cost to minimize.
Common Mistakes
Using a Deployment instead of a StatefulSet for brokers
Fix: Use StatefulSets so each broker keeps a stable identity, DNS name and volume across restarts
Enabling deleteClaim on production volumes
Fix: Set deleteClaim to false so decommissioning a cluster never silently destroys log data
Placing all brokers in one availability zone
Fix: Use topology spread constraints or anti-affinity to distribute brokers across zones
Trying to autoscale the broker fleet on consumer lag
Fix: Scale the stateless processing tier instead; broker capacity changes require a planned rebalance
Best Practices
- Match min.insync.replicas to a replication factor that tolerates one broker loss
- Provision fast local or premium block storage for broker logs and enable expansion
- Set pod disruption budgets and zone anti-affinity before the first production workload
- Export metrics for under-replicated partitions, offline partitions, lag and disk, and alert on each
- Keep inter.broker.protocol.version pinned until every broker has completed the rolling upgrade
Interview Questions
Q1: Why do Kafka brokers need StatefulSets rather than Deployments?
Brokers have stable identity: broker id maps to log directories and volumes, and replication references specific ids. StatefulSets preserve name, DNS and volume identity across restarts, which Deployments deliberately do not.
Q2: How does Strimzi achieve zero-downtime rolling upgrades?
It restarts one broker at a time and waits for each to rejoin the in-sync replica set before proceeding, which requires replication factor of at least three and a min.insync.replicas that tolerates one broker being unavailable.
Q3: Why is horizontal autoscaling of brokers usually a mistake?
Adding a broker does not add capacity to existing topics. Partitions are fixed and replicas are assigned to specific brokers, so new brokers only help after a rebalance or for newly created topics.
Q4: What storage characteristics matter most for broker logs?
Low and consistent append latency. Kafka assumes sequential writes to local disk, so local NVMe or premium block storage outperforms general purpose network storage, and object storage is unsuitable entirely.
Key Takeaways
- StatefulSets provide the stable identity, DNS and volumes that Kafka replication depends on
- deleteClaim false and min.insync.replicas 2 are the two settings that turn routine operations into safe ones
- Rolling upgrades are zero-downtime only when replication and ISR settings tolerate one broker out
- Autoscale the processing tier on lag; manage broker capacity through planned rebalances
- Metrics for under-replicated partitions and offline partitions are the early warning system