<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nezih Muzaffer Eser on Medium]]></title>
        <description><![CDATA[Stories by Nezih Muzaffer Eser on Medium]]></description>
        <link>https://medium.com/@nmeserr?source=rss-7884b50e034e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ToichqPSrLBziIva</url>
            <title>Stories by Nezih Muzaffer Eser on Medium</title>
            <link>https://medium.com/@nmeserr?source=rss-7884b50e034e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:18:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nmeserr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kubernetes Autoscaling with KEDA and Apache Kafka: A Complete Hands-On Guide]]></title>
            <link>https://medium.com/@nmeserr/kubernetes-autoscaling-with-keda-and-apache-kafka-a-complete-hands-on-guide-a70da8cbd3e9?source=rss-7884b50e034e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70da8cbd3e9</guid>
            <category><![CDATA[scaleops]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[keda]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Nezih Muzaffer Eser]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 12:04:22 GMT</pubDate>
            <atom:updated>2025-12-27T12:37:57.890Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: Why Event-Driven Autoscaling?</strong></p><p>Kubernetes’ built-in “<strong>Horizontal Pod Autoscaler (HPA)”</strong> is great for scaling based on CPU and memory metrics. But modern cloud-native applications often need more sophisticated scaling triggers:</p><p>- Scale based on “<strong>message queue depth”</strong></p><p>- React to “<strong>custom Prometheus metrics”</strong></p><p>- Handle “<strong>burst traffic”</strong> from streaming platforms</p><p>- “<strong>Scale to zero”</strong> when there’s no work (cost optimization)</p><p>Traditional HPA simply can’t do this.</p><p><strong>Real-world example:</strong> Imagine you’re running a data pipeline that processes events from Kafka. At 3 AM, there might be just 100 messages per minute. During peak hours, you might receive 100,000 messages per minute. With KEDA, your consumer pods automatically scale from 1 to 50 based on the actual message backlog — and scale back down when the storm passes.</p><p><strong>What is KEDA?</strong></p><p><strong>KEDA (Kubernetes Event-Driven Autoscaling)</strong> is an open-source project that extends Kubernetes with event-driven autoscaling capabilities. Originally developed by Microsoft and Red Hat, it’s now a “<strong>CNCF Graduated Project” </strong>the same maturity level as Kubernetes itself.</p><p><strong>KEDA Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7i6b96C8XsF7M9KYPvNFg.png" /></figure><h3><strong>Core KEDA Concepts</strong></h3><p><strong>1. ScaledObject</strong></p><p>The primary resource that defines “<strong>what”</strong> to scale, “<strong>based on what”</strong>, and “<strong>how”</strong>.</p><p><strong>2. TriggerAuthentication</strong></p><p>Securely stores credentials needed to connect to event sources (Kafka, databases, cloud services).</p><p><strong>3. Scaler</strong></p><p>A component that knows how to query a specific event source and return metrics. KEDA has 60+ built-in scalers.</p><p><strong>4. ScaledJob (Bonus)</strong></p><p>For batch workloads — creates Kubernetes Jobs instead of scaling Deployments.</p><p><strong>Apache Kafka Fundamentals</strong></p><p>Before diving into the implementation, let’s ensure we understand the Kafka concepts that KEDA uses for scaling decisions.</p><p><strong>Kafka Architecture Overview:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xh-X90oDeLjZVza6wetjQ.png" /></figure><p><strong>Key Concepts for KEDA Scaling:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qA90SLQfxbvIAeRAMbc7bg.png" /></figure><p><strong>Important:</strong> The maximum number of useful consumers equals the number of partitions. If you have 3 partitions, having more than 3 consumers means some will be idle!</p><p><strong>Our Scenario: What We’ll Build</strong></p><p>We’ll create a complete event-driven autoscaling system using Kafka and KEDA.</p><p><strong>Demo System Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWbf_4Bnr2n-lmtPg9APZw.png" /></figure><p><strong>Demo Scenario Flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXhU9yFA7AfFN8Sg8Ql9pA.png" /></figure><p><strong>Step 1: Setting Up the Kubernetes Cluster</strong></p><p>- Prepare A Kubernetes Cluster</p><p><strong>Step 2: Installing KEDA</strong></p><ul><li><strong>Add Helm Repository</strong></li></ul><pre># Add KEDA Helm repository<br>helm repo add kedacore https://kedacore.github.io/charts<br># Update repositories<br>helm repo update<br># List available KEDA charts<br>helm search repo kedacore</pre><ul><li><strong>Install KEDA</strong></li></ul><pre># Install KEDA in its own namespace<br>helm install keda kedacore/keda \<br> - namespace keda \<br> - create-namespace \<br> - wait<br># Verify installation<br>kubectl get pods -n keda<br>**Expected Output:**<br><br>NAME READY STATUS RESTARTS AGE<br>keda-admission-webhooks-xxxxxxxxxx-xxxxx           1/1       Running 0 60s<br>keda-operator-xxxxxxxxxx-xxxxx                     1/1       Running 0 60s<br>keda-operator-metrics-apiserver-xxxxxxxxxx-xxxxx   1/1       Running 0 60s</pre><p><strong>Step 3: Deploying Apache Kafka</strong></p><p>We’ll deploy Kafka in “<strong>KRaft mode”</strong> (no ZooKeeper dependency) for simplicity.</p><p><strong>3.1 Create Namespace</strong></p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>name: keda-kafka-demo<br>labels:<br>project: keda-kafka-demo<br>EOF</pre><p><strong>3.2 Deploy Kafka (KRaft Mode)</strong></p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>name: kafka-pvc<br>namespace: keda-kafka-demo<br>spec:<br>accessModes:<br>- ReadWriteOnce<br>resources:<br>requests:<br>storage: 5Gi<br>---<br>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>name: kafka<br>namespace: keda-kafka-demo<br>labels:<br>app: kafka<br>spec:<br>serviceName: kafka-headless<br>replicas: 1<br>selector:<br>matchLabels:<br>app: kafka<br>template:<br>metadata:<br>labels:<br>app: kafka<br>spec:<br>securityContext:<br>fsGroup: 1000<br>containers:<br>- name: kafka<br>image: apache/kafka:3.9.0<br>ports:<br>- containerPort: 9092<br>name: kafka<br>- containerPort: 9093<br>name: controller<br>env:<br>- name: KAFKA_NODE_ID<br>value: &quot;1&quot;<br>- name: KAFKA_PROCESS_ROLES<br>value: &quot;broker,controller&quot;<br>- name: KAFKA_CONTROLLER_QUORUM_VOTERS<br>value: &quot;1@localhost:9093&quot;<br>- name: KAFKA_LISTENERS<br>value: &quot;PLAINTEXT://:9092,CONTROLLER://:9093&quot;<br>- name: KAFKA_ADVERTISED_LISTENERS<br>value: &quot;PLAINTEXT://kafka.keda-kafka-demo.svc.cluster.local:9092&quot;<br>- name: KAFKA_LISTENER_SECURITY_PROTOCOL_MAP<br>value: &quot;CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT&quot;<br>- name: KAFKA_CONTROLLER_LISTENER_NAMES<br>value: &quot;CONTROLLER&quot;<br>- name: KAFKA_INTER_BROKER_LISTENER_NAME<br>value: &quot;PLAINTEXT&quot;<br>- name: CLUSTER_ID<br>value: &quot;MkU3OEVBNTcwNTJENDM2Qk&quot;<br>- name: KAFKA_LOG_DIRS<br>value: &quot;/var/lib/kafka/data&quot;<br>- name: KAFKA_NUM_PARTITIONS<br>value: &quot;10&quot;<br>- name: KAFKA_DEFAULT_REPLICATION_FACTOR<br>value: &quot;1&quot;<br>- name: KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR<br>value: &quot;1&quot;<br>- name: KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR<br>value: &quot;1&quot;<br>- name: KAFKA_TRANSACTION_STATE_LOG_MIN_ISR<br>value: &quot;1&quot;<br>- name: KAFKA_LOG_RETENTION_HOURS<br>value: &quot;1&quot;<br>- name: KAFKA_AUTO_CREATE_TOPICS_ENABLE<br>value: &quot;true&quot;<br>volumeMounts:<br>- name: kafka-storage<br>mountPath: /var/lib/kafka/data<br>- name: kafka-config<br>mountPath: /opt/kafka/config<br>- name: kafka-logs<br>mountPath: /opt/kafka/logs<br>resources:<br>requests:<br>memory: &quot;1Gi&quot;<br>cpu: &quot;500m&quot;<br>limits:<br>memory: &quot;2Gi&quot;<br>cpu: &quot;1000m&quot;<br>securityContext:<br>allowPrivilegeEscalation: false<br>readinessProbe:<br>tcpSocket:<br>port: 9092<br>initialDelaySeconds: 30<br>periodSeconds: 10<br>livenessProbe:<br>tcpSocket:<br>port: 9092<br>initialDelaySeconds: 60<br>periodSeconds: 20<br>volumes:<br>- name: kafka-storage<br>persistentVolumeClaim:<br>claimName: kafka-pvc<br>- name: kafka-config<br>emptyDir: {}<br>- name: kafka-logs<br>emptyDir: {}<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>name: kafka-headless<br>namespace: keda-kafka-demo<br>spec:<br>clusterIP: None<br>selector:<br>app: kafka<br>ports:<br>- port: 9092<br>name: kafka<br>- port: 9093<br>name: controller<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>name: kafka<br>namespace: keda-kafka-demo<br>spec:<br>selector:<br>app: kafka<br>ports:<br>- port: 9092<br>targetPort: 9092<br>name: kafka<br>type: ClusterIP<br>EOF</pre><p><strong>Wait for Kafka to be Ready:</strong></p><pre># Wait for Kafka pod to be ready<br>kubectl wait - for=condition=ready pod -l app=kafka \<br>-n keda-kafka-demo - timeout=180s<br># Verify Kafka is running<br>kubectl get pods -n keda-kafka-demo -l app=kafka</pre><p><strong>Expected Output:</strong></p><pre>NAME     READY   STATUS   RESTARTS   AGE<br>kafka-0   1/1    Running   0         2m</pre><p><strong>3.3 Create the Orders Topic</strong></p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>name: kafka-init-topic<br>namespace: keda-kafka-demo<br>spec:<br>template:<br>spec:<br>containers:<br>- name: kafka-init<br>image: apache/kafka:3.9.0<br>command:<br>- /bin/bash<br>- -c<br>- |<br>echo &quot;Waiting for Kafka to be ready…&quot;<br>sleep 10<br>echo &quot;Creating topic &#39;orders&#39; with 10 partitions…&quot;<br>/opt/kafka/bin/kafka-topics.sh - create \<br> - bootstrap-server kafka:9092 \<br> - topic orders \<br> - partitions 10 \<br> - replication-factor 1 \<br> - if-not-exists<br>echo &quot;&quot;<br>echo &quot;Listing topics:&quot;<br>/opt/kafka/bin/kafka-topics.sh - list - bootstrap-server kafka:9092<br>echo &quot;&quot;<br>echo &quot;Topic details:&quot;<br>/opt/kafka/bin/kafka-topics.sh - describe \<br> - bootstrap-server kafka:9092 \<br> - topic orders<br>echo &quot;&quot;<br>echo &quot; Topic &#39;orders&#39; created successfully!&quot;<br>restartPolicy: Never<br>backoffLimit: 3<br>EOF</pre><p>Wait for job completion:</p><pre>kubectl wait - for=condition=complete job/kafka-init-topic \<br>-n keda-kafka-demo - timeout=60s</pre><p>Check logs:</p><pre>kubectl logs job/kafka-init-topic -n keda-kafka-demo</pre><p><strong>Expected Output:</strong></p><pre>Creating topic &#39;orders&#39; with 10 partitions…<br>Created topic orders.<br>Listing topics:<br>orders<br>Topic details:<br>Topic: orders TopicId: xxx PartitionCount: 10 ReplicationFactor: 1<br>Topic: orders Partition: 0 Leader: 1 Replicas: 1 Isr: 1<br>Topic: orders Partition: 1 Leader: 1 Replicas: 1 Isr: 1<br>…<br>Topic: orders Partition: 9 Leader: 1 Replicas: 1 Isr: 1<br>Topic &#39;orders&#39; created successfully!</pre><p><strong>Step 4: Creating the Consumer Deployment</strong></p><p>Now let’s create the consumer application that will be scaled by KEDA.</p><p><strong>Consumer Deployment:</strong></p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>name: kafka-consumer<br>namespace: keda-kafka-demo<br>labels:<br>app: kafka-consumer<br>spec:<br>replicas: 1 # Initial replica count - KEDA will manage this<br>selector:<br>matchLabels:<br>app: kafka-consumer<br>template:<br>metadata:<br>labels:<br>app: kafka-consumer<br>spec:<br>containers:<br>- name: consumer<br>image: apache/kafka:3.9.0<br>command:<br>- /bin/bash<br>- -c<br>- |<br>CONSUMER_ID=\$(hostname)<br>echo &quot;==========================================&quot;<br>echo &quot; Kafka Consumer Started&quot;<br>echo &quot; Consumer ID: \$CONSUMER_ID&quot;<br>echo &quot; Topic: orders&quot;<br>echo &quot; Group: order-processors&quot;<br>echo &quot;==========================================&quot;<br># Start consuming messages<br>/opt/kafka/bin/kafka-console-consumer.sh \<br> - bootstrap-server kafka:9092 \<br> - topic orders \<br> - group order-processors \<br> - property print.timestamp=true \<br> - property print.key=true \<br> - property print.value=true \<br>| while read line; do<br># Simulate processing time (50–200ms per message)<br>sleep 0.\$(( RANDOM % 15 + 5 ))<br>echo &quot;[\$CONSUMER_ID] Processed: \$line&quot;<br>done<br>resources:<br>requests:<br>memory: &quot;256Mi&quot;<br>cpu: &quot;100m&quot;<br>limits:<br>memory: &quot;512Mi&quot;<br>cpu: &quot;500m&quot;<br>env:<br>- name: KAFKA_HEAP_OPTS<br>value: &quot;-Xmx256m -Xms256m&quot;<br>EOF</pre><p><strong>Verify Consumer is Running:</strong></p><pre># Check consumer pod<br>kubectl get pods -n keda-kafka-demo -l app=kafka-consumer<br># View consumer logs<br>kubectl logs -f deployment/kafka-consumer -n keda-kafka-demo<br>**Expected Output:**<br>==========================================<br>Kafka Consumer Started<br>Consumer ID: kafka-consumer-xxxxxxxxxx-xxxxx<br>Topic: orders<br>Group: order-processors<br>==========================================</pre><p><strong>Step 5: Configuring KEDA ScaledObject</strong></p><p>This is the heart of our setup — the ScaledObject tells KEDA how to scale our consumers based on Kafka lag.</p><p><strong>5.1 Create TriggerAuthentication (Optional for this demo)</strong></p><p>For this demo, we’re using plain authentication. In production, you’d use SASL/SSL:</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: keda.sh/v1alpha1<br>kind: TriggerAuthentication<br>metadata:<br>name: kafka-trigger-auth<br>namespace: keda-kafka-demo<br>spec:<br># For SASL authentication (production), you would add:<br># secretTargetRef:<br># - parameter: sasl<br># name: kafka-secrets<br># key: sasl<br># - parameter: username<br># name: kafka-secrets<br># key: username<br># - parameter: password<br># name: kafka-secrets<br># key: password<br># For this demo, we use no authentication<br>secretTargetRef: []<br>EOF</pre><p><strong>5.2 Create ScaledObject</strong></p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: kafka-consumer-scaler<br>  namespace: keda-kafka-demo<br>spec:<br>  # Target deployment to scale<br>  scaleTargetRef:<br>    name: kafka-consumer<br>  <br>  # Scaling parameters<br>  pollingInterval: 5        # Check Kafka lag every 5 seconds<br>  cooldownPeriod: 30        # Wait 30 seconds before scaling down<br>  minReplicaCount: 1        # Minimum 1 consumer<br>  maxReplicaCount: 15       # Maximum 15 consumers (we have 10 partitions)<br>  <br>  # Advanced scaling behavior<br>  advanced:<br>    horizontalPodAutoscalerConfig:<br>      behavior:<br>        scaleDown:<br>          stabilizationWindowSeconds: 60<br>          policies:<br>            - type: Percent<br>              value: 50<br>              periodSeconds: 30<br>        scaleUp:<br>          stabilizationWindowSeconds: 0<br>          policies:<br>            - type: Percent<br>              value: 100<br>              periodSeconds: 15<br>            - type: Pods<br>              value: 4<br>              periodSeconds: 15<br>          selectPolicy: Max<br>  <br>  # Kafka trigger configuration<br>  triggers:<br>    - type: kafka<br>      metadata:<br>        # Kafka connection<br>        bootstrapServers: kafka.keda-kafka-demo.svc.cluster.local:9092<br>        <br>        # Consumer group to monitor<br>        consumerGroup: order-processors<br>        <br>        # Topic to monitor<br>        topic: orders<br>        <br>        # Scale based on lag threshold<br>        # When lag &gt; lagThreshold, scale up<br>        lagThreshold: &quot;100&quot;<br>        <br>        # Activation threshold - minimum lag to start scaling from 0<br>        activationLagThreshold: &quot;10&quot;<br>        <br>        # Offset reset policy<br>        offsetResetPolicy: earliest<br>        <br>        # Allow checking all topics in consumer group<br>        allowIdleConsumers: &quot;false&quot;<br>        <br>        # Exclude persistent lag (lag from before consumer group existed)<br>        excludePersistentLag: &quot;false&quot;<br>      # Optional: authentication reference<br>      # authenticationRef:<br>      #   name: kafka-trigger-auth<br><br>EOF<br></pre><p>ScaledObject Parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPX5zMAu5_zase0JIeNExw.png" /></figure><p>Scaling Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8_WBMv44fKX4AGCNdYCdA.png" /></figure><p><strong>Verify ScaledObject:</strong></p><pre># Check ScaledObject status<br>kubectl get scaledobject -n keda-kafka-demo<br># Detailed information<br>kubectl describe scaledobject kafka-consumer-scaler -n keda-kafka-demo<br>**Expected Output:**<br>NAME SCALETARGETKIND    SCALETARGETNAME                 MIN MAX TRIGGERS AUTHENTICATION READY ACTIVE AGE<br>kafka-consumer-scaler apps/v1.Deployment kafka-consumer  1  15   kafka     True         False 30s</pre><p><strong>Check the Created HPA:</strong></p><pre>kubectl get hpa -n keda-kafka-demo<br><br>NAME                           REFERENCE                 TARGETS  MINPODS MAXPODS REPLICAS<br>keda-hpa-kafka-consumer-scaler Deployment/kafka-consumer 0/100 (avg) 1     15     1</pre><p><strong>Step 6: Running the Demo Scenario</strong></p><p>Now let’s see KEDA in action! We’ll produce messages and watch the consumers scale.</p><p><strong>6.1 Set Up Monitoring Terminals</strong></p><ul><li><strong>Open 3 separate terminal windows:</strong></li></ul><p><strong>Terminal 1 — Watch Consumer Pods:</strong></p><pre>watch -n 1 &quot;kubectl get pods -n keda-kafka-demo -l app=kafka-consumer -o wide&quot;</pre><p><strong>Terminal 2 — Watch Consumer Group Lag:</strong></p><pre>watch -n 2 &quot;kubectl exec -n keda-kafka-demo kafka-0 - \<br>/opt/kafka/bin/kafka-consumer-groups.sh - bootstrap-server localhost:9092 \<br> - describe - group order-processors 2&gt;/dev/null | tail -15&quot;</pre><p><strong>Terminal 3 — Main terminal for commands</strong></p><p><strong>6.2 Verify Initial State</strong></p><pre># Current pod count (should be 1)<br>kubectl get pods -n keda-kafka-demo -l app=kafka-consumer<br># Current consumer group lag (should be 0 or minimal)<br>kubectl exec -n keda-kafka-demo kafka-0 - \<br>/opt/kafka/bin/kafka-consumer-groups.sh - bootstrap-server localhost:9092 \<br> - describe - group order-processors</pre><p><strong>6.3 SCALE UP: Produce 10,000 Messages</strong></p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>name: kafka-producer-burst<br>namespace: keda-kafka-demo<br>spec:<br>template:<br>spec:<br>containers:<br>- name: producer<br>image: apache/kafka:3.9.0<br>command:<br>- /bin/bash<br>- -c<br>- |<br>echo &quot;╔════════════════════════════════════════════════════════════╗&quot;<br>echo &quot;║ KAFKA PRODUCER - GENERATING 10,000 MESSAGES ║&quot;<br>echo &quot;╚════════════════════════════════════════════════════════════╝&quot;<br>echo &quot;&quot;<br>echo &quot;This will trigger KEDA to scale up the consumers!&quot;<br>echo &quot;&quot;<br># Generate 10,000 messages<br>for i in \$(seq 1 10000); do<br>echo &quot;order-\$i:{\&quot;orderId\&quot;:\&quot;\$i\&quot;,\&quot;product\&quot;:\&quot;item-\$((RANDOM % 100))\&quot;,\&quot;quantity\&quot;:\$((RANDOM % 10 + 1)),\&quot;timestamp\&quot;:\&quot;\$(date -Iseconds)\&quot;}&quot;<br>done | /opt/kafka/bin/kafka-console-producer.sh \<br> - bootstrap-server kafka:9092 \<br> - topic orders \<br> - property parse.key=true \<br> - property key.separator=:<br>echo &quot;&quot;<br>echo &quot;╔════════════════════════════════════════════════════════════╗&quot;<br>echo &quot;║ 10,000 MESSAGES PRODUCED! ║&quot;<br>echo &quot;║ ║&quot;<br>echo &quot;║ Watch the consumer pods scale up: ║&quot;<br>echo &quot;║ kubectl get pods -n keda-kafka-demo -l app=kafka-consumer ║&quot;<br>echo &quot;╚════════════════════════════════════════════════════════════╝&quot;<br>restartPolicy: Never<br>backoffLimit: 1<br>EOF</pre><p>Wait for producer to finish:</p><pre>echo &quot;Waiting for producer to complete…&quot;<br>kubectl wait - for=condition=complete job/kafka-producer-burst \<br>-n keda-kafka-demo - timeout=120s<br># Show producer logs<br>kubectl logs job/kafka-producer-burst -n keda-kafka-demo</pre><p><strong>What to Observe (Terminal 1)</strong></p><pre>Every 1.0s: kubectl get pods -n keda-kafka-demo -l app=kafka-consumer -o wide<br>NAME                           READY STATUS RESTARTS AGE<br>kafka-consumer-7d9f8c6b5d-abc12 1/1 Running 0 10m<br>kafka-consumer-7d9f8c6b5d-def34 1/1 Running 0 15s ← NEW<br>kafka-consumer-7d9f8c6b5d-ghi56 1/1 Running 0 15s ← NEW<br>kafka-consumer-7d9f8c6b5d-jkl78 1/1 Running 0 15s ← NEW<br>kafka-consumer-7d9f8c6b5d-mno90 1/1 Running 0 15s ← NEW<br>…<br>(scaling up to 10–15 pods)</pre><p><strong>What to Observe (Terminal 2)</strong></p><pre>GROUP            TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG<br>order-processors orders   0       234             1000         766 ← LAG!<br>order-processors orders   1       189             1000         811<br>order-processors orders   2       312             1000         688<br>order-processors orders   3       156             1000         844</pre><p>TOTAL LAG: ~7500 messages → KEDA scales to ceil(7500/100) = 15 pods (capped)</p><p><strong>6.4 Watch the Processing</strong></p><pre># Monitor consumer logs (pick any consumer pod)<br>kubectl logs -f deployment/kafka-consumer -n keda-kafka-demo - tail=20<br># Check HPA status<br>kubectl get hpa -n keda-kafka-demo -w<br># Check ScaledObject metrics<br>kubectl describe scaledobject kafka-consumer-scaler -n keda-kafka-demo | grep -A 20 &quot;Status:&quot;</pre><p><strong>6.5 SCALE DOWN: Wait for Processing to Complete</strong></p><p>As consumers process messages, the lag decreases, and KEDA will scale down:</p><pre># Monitor lag decrease<br>watch -n 5 &quot;kubectl exec -n keda-kafka-demo kafka-0 - \<br>/opt/kafka/bin/kafka-consumer-groups.sh - bootstrap-server localhost:9092 \<br> - describe - group order-processors 2&gt;/dev/null | grep -E &#39;LAG|order-processors&#39; | tail -12&quot;</pre><p><strong>— Expected Behavior—</strong></p><p>1. Lag starts at ~10,000</p><p>2. With 15 consumers processing, lag decreases rapidly</p><p>3. When lag drops below threshold, cooldown timer starts (30 seconds)</p><p>4. Pods begin terminating</p><p>5. Eventually, only 1 pod remains (minimum)</p><p><strong>What to Observe During Scale Down</strong></p><ul><li>Terminal 1 will show:</li></ul><pre>NAME                           READY STATUS     RESTARTS AGE<br>kafka-consumer-7d9f8c6b5d-abc12 1/1 Running     0        15m<br>kafka-consumer-7d9f8c6b5d-def34 1/1 Terminating 0        5m ← SCALING DOWN<br>kafka-consumer-7d9f8c6b5d-ghi56 1/1 Terminating 0        5m<br>…<br># Eventually:<br>NAME READY STATUS RESTARTS AGE<br>kafka-consumer-7d9f8c6b5d-abc12 1/1 Running     0        20m ← ONLY 1 LEFT</pre><p><strong>6.6 Cleanup Test Jobs</strong></p><pre># Delete producer job for re-testing<br>kubectl delete job kafka-producer-burst -n keda-kafka-demo - ignore-not-found<br># Reset consumer group offsets (optional - for clean re-test)<br>kubectl exec -n keda-kafka-demo kafka-0 - \<br>/opt/kafka/bin/kafka-consumer-groups.sh - bootstrap-server localhost:9092 \<br> - group order-processors - reset-offsets - to-latest - topic orders - execute</pre><p><strong>Deep Dive: Understanding Kafka Consumer Lag</strong></p><p><strong>What is Consumer Lag?</strong></p><p>Consumer lag is the difference between the latest message offset in a partition and the consumer’s current position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qt6zifST5c199rd0DJabbA.png" /></figure><p><strong>Why Lag Matters?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_kwz9-kPNGTaXwrFRfajg.png" /></figure><p><strong>KEDA’s Lag Calculation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Kt1hGYEkOsOD05Qwj8jhQ.png" /></figure><p><strong>Partition-Consumer Assignment</strong></p><p>Remember: <strong>Maximum useful consumers = Number of partitions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nx2o5xEPUika2njWSu7U4w.png" /></figure><p><strong>Cleanup</strong></p><p><strong>Remove Demo Resources:</strong></p><pre># Option 1: Delete just the namespace (removes everything)<br>kubectl delete namespace keda-kafka-demo - force - grace-period=0<br># Option 2: Delete resources individually<br>kubectl delete scaledobject kafka-consumer-scaler -n keda-kafka-demo<br>kubectl delete deployment kafka-consumer -n keda-kafka-demo<br>kubectl delete statefulset kafka -n keda-kafka-demo<br>kubectl delete job kafka-producer-burst kafka-init-topic -n keda-kafka-demo - ignore-not-found<br>kubectl delete pvc kafka-pvc -n keda-kafka-demo<br>kubectl delete namespace keda-kafka-demo</pre><p><strong>Remove KEDA:</strong></p><pre># Uninstall KEDA<br>helm uninstall keda -n keda<br># Delete KEDA namespace<br>kubectl delete namespace keda<br># Remove CRDs (optional)<br>kubectl delete crd scaledobjects.keda.sh<br>kubectl delete crd scaledjobs.keda.sh<br>kubectl delete crd triggerauthentications.keda.sh<br>kubectl delete crd clustertriggerauthentications.keda.sh</pre><p><strong>Key Takeaways:</strong></p><p>1. <strong>Lag is King:</strong> KEDA uses consumer lag as the primary scaling metric — it directly reflects how much work is pending.</p><p>2. <strong>Partitions Matter:</strong> Your maximum parallelism is limited by partition count. Plan accordingly.</p><p>3. <strong>Tune Carefully:</strong> `lagThreshold`, `cooldownPeriod`, and `stabilizationWindow` significantly affect scaling behavior.</p><p>4. <strong>Monitor Everything:</strong> Use consumer group lag monitoring in production — it’s your early warning system.</p><p>5. <strong>Start Conservative:</strong> Begin with higher thresholds and longer cooldowns, then tune based on observed behavior.</p><p><strong>If you found this article helpful, please 👏 and follow for more Kubernetes content!</strong></p><p><em>Questions or feedback? Drop a comment below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70da8cbd3e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>