🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Kafka on K8s: Strimzi, Operators, Persistent Volumes

Apache KafkaKubernetes⭐ Premium

Kafka on K8s: Strimzi, Operators, Persistent Volumes

Difficulty: Senior | Asked at: Cloud-native companies, DevOps roles

â„šī¸Interview Context

Running Kafka on Kubernetes is increasingly common. Interviewers expect you to understand the challenges, operator patterns, and how to manage stateful workloads on K8s.

The Question

How do you run Kafka on Kubernetes? Explain the role of operators like Strimzi, how persistent volumes work for stateful sets, and what operational challenges exist.

This question tests whether you understand that Kubernetes schedules stateless pods well and stateful, disk-bound, connection-heavy services poorly — and what you do about the gap. A complete answer covers four things: why Kafka needs a StatefulSet rather than a Deployment, what the Strimzi operator manages on your behalf, how persistent volumes attach to individual broker pods, and which operational hazards remain even with an operator in place. Expect follow-ups about rolling upgrades, zone spreading and what happens when a node dies with a broker's volume attached. The key mental model is that the operator turns a Kafka cluster into a set of custom resources, while the storage, scheduling and networking semantics underneath are still plain Kubernetes.

Kafka on K8s Architecture

Kubernetes ClusterKubernetes Cluster┌───────────────────Strimzi Operator- Manages Kafka life- Creates StatefulSe- Handles upgrades a└───────────────────↓┌───────────────────Kafka StatefulSet┌─────────┐ ┌──────kafka-0kafka-1kafka-2┌─────┐┌─────┐┌─────┐PVCPVCPVC└─────┘└─────┘└─────┘└─────────┘ └──────└───────────────────↓┌───────────────────PersistentVolumeClaikafka-data-kafka-0 kafka-data-kafka-2└───────────────────

A Kafka deployment on Kubernetes is three layers of objects. At the bottom, a StatefulSet gives each broker a stable identity — kafka-0, kafka-1, kafka-2 — and stable network endpoints through a headless service, which is exactly what Kafka needs so partition replicas can refer to brokers by unchanging names. In the middle, each pod claims its own PersistentVolumeClaim, and the storage class decides whether that claim becomes a fast gp3 volume or a sluggish network share. At the top, the operator watches custom resources and reconciles the real cluster toward the declared spec, creating services, certificates and config maps as needed. Do not run Kafka as a plain Deployment: pods would be renamed on reschedule, partition replicas would point at names that no longer exist, and recovery would require manual log surgery.

Strimzi Operator

Strimzi Architecture

Strimzi implements the Kubernetes operator pattern: a controller process watches custom resources and continuously reconciles the cluster toward the declared state. The Cluster Operator owns the Kafka, ZooKeeper, Connect and MirrorMaker custom resources. The Topic Operator maps each Kafka topic onto a Topic custom resource, so topics become part of the same git-managed configuration as everything else — create, update and delete flow through kubectl apply. The User Operator does the same for Kafka users and their SCRAM credentials or ACLs. The practical payoff is repeatability: standing up a second identical cluster in staging is a matter of copying manifests, and a broker that dies is replaced with the same configuration and the same mounted volume claim rather than by a runbook step.

python
strimzi_components = {
    'Cluster Operator': {
        'purpose': 'Manages Kafka, Connect, MirrorMaker, etc.',
        'scope': 'Namespace or cluster-wide',
        'features': [
            'Create/delete Kafka clusters',
            'Scale brokers up/down',
            'Handle rolling upgrades',
            'Manage TLS certificates'
        ]
    },
    'Topic Operator': {
        'purpose': 'Manages Kafka topics',
        'features': [
            'Create/delete topics via CRD',
            'Validate topic configurations',
            'Monitor topic health'
        ]
    },
    'User Operator': {
        'purpose': 'Manages Kafka users',
        'features': [
            'Create/delete users via CRD',
            'Manage SCRAM credentials',
            'Handle ACLs'
        ]
    }
}

Strimzi Kafka Cluster CRD

# kafka-cluster.yaml
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
  namespace: kafka
spec:
  kafka:
    version: 3.6.1
    replicas: 3
    
    listeners:
      - name: plain
        port: 9092
        type: internal
        tls: false
      - name: tls
        port: 9093
        type: internal
        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.6"
    
    storage:
      type: persistent-claim
      size: 100Gi
      class: fast-ssd
      deleteClaim: false
    
    resources:
      requests:
        memory: 4Gi
        cpu: 2
      limits:
        memory: 8Gi
        cpu: 4
    
    rack:
      topologyKey: topology.kubernetes.io/zone
    
    metricsConfig:
      type: jmxPrometheusExporter
      valueFrom:
        configMapKeyRef:
          name: kafka-metrics
          key: kafka-metrics-config.yml
  
  zookeeper:
    replicas: 3
    
    storage:
      type: persistent-claim
      size: 20Gi
      class: fast-ssd
      deleteClaim: false
    
    resources:
      requests:
        memory: 2Gi
        cpu: 1
      limits:
        memory: 4Gi
        cpu: 2
  
  entityOperator:
    topicOperator: {}
    userOperator: {}

Strimzi Scaling

# Scale Kafka brokers
kubectl patch kafka my-cluster -n kafka --type merge -p '
{
  "spec": {
    "kafka": {
      "replicas": 5
    }
  }
}'

# Scale ZooKeeper
kubectl patch kafka my-cluster -n kafka --type merge -p '
{
  "spec": {
    "zookeeper": {
      "replicas": 5
    }
  }
}'

# Check status
kubectl get kafka my-cluster -n kafka -o yaml

Strimzi Rolling Upgrade

# Update Kafka version
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    version: 3.7.0  # Upgrade from 3.6.1
    # ... rest of config
# Strimzi handles rolling upgrade automatically
# Monitor progress
kubectl get pods -n kafka -w

# Check upgrade status
kubectl get kafka my-cluster -n kafka -o jsonpath='{.status.conditions}'

â„šī¸Strimzi Benefits

Strimzi provides:

  1. Declarative Kafka management via CRDs
  2. Automated rolling upgrades
  3. Built-in TLS and authentication
  4. Topic and user management
  5. Integration with Kubernetes ecosystem

Persistent Volumes

PV/PVC Configuration

Kafka is the rare workload where volume characteristics matter as much as the CPU limit. Each broker appends sequentially to log segments and followers fetch those segments, so sustained disk throughput sets the replication rate while fsync behaviour on segment commit sets producer latency under acks-all. On cloud volumes, gp3 gives 125 MB/s and 3000 IOPS at the base price with independent IOPS and throughput provisioning — size it for the sum of produce and replica-fetch traffic, not for capacity headroom alone. Keep volumes above 100 GB because small volumes receive proportionally less burst credit, and set the reclaim policy to Retain so deleting a pod or scaling the StatefulSet down does not take partition data with it. One claim per broker pod, bound to a single node with ReadWriteOnce: Kafka never shares a live volume between brokers.

# StorageClass for Kafka
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: fast-ssd
provisioner: kubernetes.io/aws-ebs
parameters:
  type: gp3
  iopsPerGB: "10"
  encrypted: "true"
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true

---
# PersistentVolumeClaim for Kafka broker
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: kafka-data-kafka-0
  namespace: kafka
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: fast-ssd
  resources:
    requests:
      storage: 100Gi

Volume Configuration

python
pv_config = {
    'storage_classes': {
        'fast-ssd': {
            'provisioner': 'kubernetes.io/aws-ebs',
            'parameters': {'type': 'gp3'},
            'best_for': 'Production Kafka'
        },
        'standard': {
            'provisioner': 'kubernetes.io/aws-ebs',
            'parameters': {'type': 'gp2'},
            'best_for': 'Development/testing'
        },
        'local-ssd': {
            'provisioner': 'kubernetes.io/no-provisioner',
            'best_for': 'Maximum performance'
        }
    },
    'access_modes': {
        'ReadWriteOnce': 'Single node access (Kafka brokers)',
        'ReadWriteMany': 'Multi-node access (not recommended for Kafka)'
    },
    'reclaim_policies': {
        'Delete': 'Delete PVC when Pod is deleted',
        'Retain': 'Keep PVC when Pod is deleted (recommended)'
    }
}

Volume Performance

python
def estimate_volume_performance(
    storage_type: str,
    size_gb: int,
    iops: int
) -> dict:
    """
    Estimate volume performance for Kafka.
    """
    performance = {
        'gp2': {
            'throughput_mbps': 128 + (size_gb * 0.5),
            'iops': min(16000, 3 * size_gb),
            'latency_ms': 1
        },
        'gp3': {
            'throughput_mbps': 125 + (iops * 0.25),
            'iops': min(16000, iops),
            'latency_ms': 0.5
        },
        'io2': {
            'throughput_mbps': 1000,
            'iops': min(64000, iops),
            'latency_ms': 0.1
        },
        'st1': {
            'throughput_mbps': 500,
            'iops': 500,
            'latency_ms': 5
        }
    }
    
    return performance.get(storage_type, performance['gp3'])

# Example
perf = estimate_volume_performance('gp3', 100, 3000)
print(f"Throughput: {perf['throughput_mbps']} MB/s")
print(f"IOPS: {perf['iops']}")

âš ī¸Volume Warning

Kafka requires fast, persistent storage. Avoid:

  • Network-attached storage with high latency
  • EBS volumes smaller than 100GB (IOPS scaling)
  • Storage classes with reclaimPolicy=Delete

Resource Management

Resource Requests and Limits

Sizing Kafka containers differs from sizing ordinary services because the heap should be a minority of the memory request. The JVM heap holds index structures and request buffers; the page cache holds log data, and Kafka performance depends far more on the second than on the first. A 6 GB heap inside an 8 to 10 GB memory request is the usual production shape, leaving two to four gigabytes for cache and the OS. Set requests to the steady-state need and limits to roughly twice that so brokers can burst during catch-up without being evicted. For CPU, set requests to the measured average and either omit limits entirely — letting the broker burst into spare capacity — or set them generously; a throttled broker shows up as elevated request latency long before it shows up as an OOM kill.

# Kafka broker resources
resources:
  requests:
    memory: 4Gi
    cpu: "2"
    ephemeral-storage: 10Gi
  limits:
    memory: 8Gi
    cpu: "4"
    ephemeral-storage: 20Gi

# Resource formula:
# memory.requests = JVM heap + OS overhead (30%)
# memory.limits = 2x requests for burst capacity
# cpu.requests = Expected average usage
# cpu.limits = 2x requests for burst capacity

Resource Calculation

python
def calculate_kafka_resources(
    num_partitions: int,
    avg_message_size: int,
    messages_per_sec: int,
    replication_factor: int
) -> dict:
    """
    Calculate recommended Kafka resources.
    """
    # Memory calculation
    # JVM heap: 6GB recommended for production
    jvm_heap_gb = 6
    
    # OS page cache: 50% of remaining memory
    # Total memory: JVM heap / 0.7
    total_memory_gb = jvm_heap_gb / 0.7
    
    # CPU calculation
    # Base: 2 cores for Kafka broker
    # Additional: 0.5 core per 10,000 messages/sec
    base_cpu = 2
    additional_cpu = messages_per_sec / 10000 * 0.5
    total_cpu = base_cpu + additional_cpu
    
    # Storage calculation
    # Daily data: messages_per_sec * avg_message_size * 86400
    daily_data_gb = (messages_per_sec * avg_message_size * 86400) / (1024**3)
    
    return {
        'memory_requests': f'{int(total_memory_gb)}Gi',
        'memory_limits': f'{int(total_memory_gb * 2)}Gi',
        'cpu_requests': f'{int(total_cpu)}',
        'cpu_limits': f'{int(total_cpu * 2)}',
        'storage_per_broker': f'{int(daily_data_gb * 7 * replication_factor * 1.2)}Gi'
    }

# Example
resources = calculate_kafka_resources(
    num_partitions=12,
    avg_message_size=500,
    messages_per_sec=10000,
    replication_factor=3
)
print(f"Memory: {resources['memory_requests']} / {resources['memory_limits']}")
print(f"CPU: {resources['cpu_requests']} / {resources['cpu_limits']}")

Pod Disruption Budgets

# Pod Disruption Budget for Kafka
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: kafka-pdb
  namespace: kafka
spec:
  minAvailable: 2  # At least 2 brokers must be available
  selector:
    matchLabels:
      app: kafka
      strimzi.io/cluster: my-cluster

# Or use maxUnavailable
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: kafka-pdb
spec:
  maxUnavailable: 1  # At most 1 broker can be unavailable
  selector:
    matchLabels:
      app: kafka

â„šī¸PDB Importance

Pod Disruption Budgets protect against voluntary disruptions (node drains, upgrades). For Kafka, ensure at least N-1 brokers are always available to maintain replication.

Network Configuration

Service Configuration

Kafka on Kubernetes needs two services, and mixing them up is a classic interview trap. The headless service resolves to the individual pod IPs and gives StatefulSet members their stable DNS names, which brokers use for inter-broker replication. The bootstrap service is a normal ClusterIP service that load-balances client connections to healthy brokers at startup; after bootstrap, clients learn per-broker addresses from the metadata response and connect directly. If clients keep the bootstrap service as their only endpoint, every produce and fetch travels through the service proxy, adding latency and concentrating load. Network policies then restrict ingress to the client and monitoring pods you nominate, which matters because a misconfigured cluster is otherwise reachable from every namespace in the cluster.

# Headless service for StatefulSet
apiVersion: v1
kind: Service
metadata:
  name: kafka-brokers
  namespace: kafka
spec:
  clusterIP: None
  selector:
    app: kafka
    strimzi.io/cluster: my-cluster
  ports:
    - name: plain
      port: 9092
    - name: tls
      port: 9093

---
# Bootstrap service
apiVersion: v1
kind: Service
metadata:
  name: kafka-bootstrap
  namespace: kafka
spec:
  selector:
    app: kafka
    strimzi.io/cluster: my-cluster
  ports:
    - name: plain
      port: 9092
    - name: tls
      port: 9093

Network Policies

# Network policy for Kafka
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: kafka-network-policy
  namespace: kafka
spec:
  podSelector:
    matchLabels:
      app: kafka
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: kafka-consumer
        - podSelector:
            matchLabels:
              app: kafka-producer
      ports:
        - port: 9092
        - port: 9093
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: kafka
      ports:
        - port: 9092
        - port: 9093

DNS Configuration

python
dns_config = {
    'headless_service': 'kafka-brokers.kafka.svc.cluster.local',
    'broker_dns': [
        'kafka-0.kafka-brokers.kafka.svc.cluster.local',
        'kafka-1.kafka-brokers.kafka.svc.cluster.local',
        'kafka-2.kafka-brokers.kafka.svc.cluster.local'
    ],
    'bootstrap_dns': 'kafka-bootstrap.kafka.svc.cluster.local',
    'client_config': {
        'bootstrap.servers': 'kafka-bootstrap:9092',
        'security.protocol': 'SSL',
        'ssl.truststore.location': '/etc/kafka/secrets/truststore.jks'
    }
}

Operational Challenges

Common Issues and Solutions

Five failure modes account for most Kafka-on-Kubernetes incidents. Node drains are voluntary and frequent; pod disruption budgets are what keep a drain from taking two brokers at once, so set minAvailable to replicas minus one. Zone loss is the unplanned version of the same problem, handled by spreading brokers across zones with topology spread constraints or anti-affinity. Volume detachment is slower than pod restarts on most cloud providers, and a broker that starts without its volume refuses to serve until the claim reattaches — the operator handles this, but recovery can stretch into minutes, so client timeouts must tolerate it. Certificate rotation, configuration changes and version upgrades all go through the operator as rolling operations; watching the pod list during the first production upgrade is not optional. Finally, watch CPU throttling: a limit that looks generous in the dashboard can still throttle a broker during a catch-up burst.

python
k8s_challenges = {
    'StatefulSet Scaling': {
        'issue': 'Kafka requires ordered, stable network IDs',
        'solution': 'Use StatefulSet with headless service',
        'implementation': 'Strimzi handles this automatically'
    },
    'Persistent Volume Management': {
        'issue': 'PVs must survive Pod restarts',
        'solution': 'Use Retain reclaim policy',
        'implementation': 'StorageClass with reclaimPolicy: Retain'
    },
    'Pod Disruptions': {
        'issue': 'Node drains can kill brokers',
        'solution': 'Pod Disruption Budgets + node affinity',
        'implementation': 'PDB with minAvailable=N-1'
    },
    'Resource Contention': {
        'issue': 'Noisy neighbor problems',
        'solution': 'Resource requests/limits + node affinity',
        'implementation': 'Dedicated node pools for Kafka'
    },
    'Network Partitions': {
        'issue': 'K8s network can partition',
        'solution': 'Anti-affinity rules + multiple AZs',
        'implementation': 'podAntiAffinity with topologySpreadConstraints'
    }
}

Pod Anti-Affinity

# Ensure Kafka brokers spread across nodes
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: kafka
spec:
  template:
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchExpressions:
                  - key: app
                    operator: In
                    values:
                      - kafka
              topologyKey: kubernetes.io/hostname
      
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: kafka
      
      tolerations:
        - key: "dedicated"
          operator: "Equal"
          value: "kafka"
          effect: "NoSchedule"

â„šī¸Anti-Affinity

Use requiredDuringSchedulingIgnoredDuringExecution for production. It ensures brokers are on different nodes but allows scheduling to continue if nodes fail. Use topologySpreadConstraints for zone-aware distribution.

Monitoring on K8s

# Prometheus ServiceMonitor for Kafka
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: kafka-metrics
  namespace: kafka
spec:
  selector:
    matchLabels:
      app: kafka
  endpoints:
    - port: metrics
      interval: 30s
      path: /metrics

---
# Grafana dashboard ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: kafka-grafana-dashboard
  namespace: monitoring
data:
  kafka-dashboard.json: |
    {
      "dashboard": {
        "title": "Kafka on Kubernetes",
        "panels": [...]
      }
    }

âš ī¸Key Insight

Kafka on Kubernetes requires careful planning. The Strimzi operator significantly simplifies operations, but you still need to understand the underlying challenges. Always test in staging before production.

Common Mistakes

Deploying Kafka as a Deployment with a shared or ephemeral volume

Fix: Use a StatefulSet with one ReadWriteOnce PersistentVolumeClaim per broker. Stable pod names and attached storage are what keep partition replicas pointing at valid log directories after a reschedule.

Setting the container memory limit equal to the JVM heap size

Fix: Keep the heap at roughly 60 to 70 percent of the memory request so the page cache has room. A heap-equals-limit pod trades log cache for GC pressure and slower replica fetches.

Pointing clients only at the bootstrap service for the lifetime of the connection

Fix: Use bootstrap for initial metadata only, then connect directly to the per-broker DNS names from the headless service, or every request pays the proxy hop.

Key Takeaways

  • A StatefulSet plus headless service gives brokers stable names and DNS, which partition replica assignment depends on
  • Strimzi operators reconcile Kafka custom resources into clusters, topics and users, turning upgrades and scaling into declarative changes
  • One ReadWriteOnce PVC per broker with a Retain reclaim policy; size the volume class for produce plus replica-fetch throughput, not just capacity
  • Pod disruption budgets, anti-affinity and zone spreading protect against voluntary drains and zone loss, and client timeouts must cover slow volume reattachment
🔒

Premium Content

Kafka on K8s: Strimzi, Operators, Persistent Volumes

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement