Kubernetes Autoscaling in Depth: HPA, VPA, and KEDA 2.20 with Spring Boot

Introduction

Scaling applications in Kubernetes is deceptively simple to start and surprisingly hard to get right in production. The two most common scaling primitives — the Horizontal Pod Autoscaler (HPA) and the Vertical Pod Autoscaler (VPA) — are built into every Kubernetes cluster, yet many teams still end up over-provisioning their workloads because they never move beyond CPU-based thresholds.

The missing piece is usually event-driven scaling. For a Java microservice processing Kafka messages, the signal that matters is consumer lag — the number of messages yet to be processed — not CPU utilisation. For an API service with unpredictable bursts, the right trigger is the HTTP request queue depth, not memory usage. KEDA (Kubernetes Event-Driven Autoscaling) bridges that gap: it feeds HPA with custom metrics from over 60 event sources — Kafka, RabbitMQ, Prometheus, AWS SQS, Azure Service Bus, and more — without replacing any native Kubernetes machinery.

In this tutorial you will build a Spring Boot message-processing service, instrument it with Micrometer and Prometheus, then configure all three autoscaling mechanisms:

  1. HPA — replica-count scaling based on CPU and custom Prometheus metrics
  2. VPA — right-sizing pod resource requests using the recommendation-mode pattern
  3. KEDA 2.20 — event-driven scaling based on Kafka consumer lag and Prometheus queries

By the end you will have a production-ready autoscaling setup that responds within seconds to real workload changes rather than reacting to coarse CPU averages that often lag the real event by minutes.

Prerequisites

Before starting, make sure you have:

  • Kubernetes 1.29+ cluster (Minikube, kind, or a managed cluster)
  • kubectl 1.29+
  • Helm 3.14+
  • Java 21+
  • Apache Kafka 3.7+ running in the cluster (or accessible externally)
  • Prometheus and Grafana installed via the kube-prometheus-stack chart
  • Docker or Podman for building container images

Install KEDA 2.20

helm repo add kedacore https://kedacore.github.io/charts
helm repo update
helm install keda kedacore/keda \
  --namespace keda \
  --create-namespace \
  --version 2.20.0

Verify the KEDA operator is running:

kubectl get pods -n keda
# NAME                                               READY   STATUS    RESTARTS
# keda-operator-6b7c9c8d7f-xk4p2                    1/1     Running   0
# keda-operator-metrics-apiserver-7d9bfb4f9d-p2m9s  1/1     Running   0

Install the Vertical Pod Autoscaler

git clone https://github.com/kubernetes/autoscaler.git
cd autoscaler/vertical-pod-autoscaler
./hack/vpa-install.sh

Project Setup

Create the Spring Boot project with the following pom.xml.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.5.6</version>
    <relativePath/>
  </parent>

  <groupId>com.vimleshpandey.demo</groupId>
  <artifactId>keda-autoscaling-demo</artifactId>
  <version>1.0.0</version>
  <name>keda-autoscaling-demo</name>

  <properties>
    <java.version>21</java.version>
    <testcontainers.version>1.20.3</testcontainers.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
      <groupId>io.micrometer</groupId>
      <artifactId>micrometer-registry-prometheus</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.kafka</groupId>
      <artifactId>spring-kafka</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.kafka</groupId>
      <artifactId>spring-kafka-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.testcontainers</groupId>
      <artifactId>kafka</artifactId>
      <version>${testcontainers.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

application.yml

spring:
  application:
    name: message-processor
  kafka:
    bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:localhost:9092}
    consumer:
      group-id: message-processor-group
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      max-poll-records: 50
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer

management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus,metrics
  endpoint:
    health:
      show-details: always
  metrics:
    tags:
      application: ${spring.application.name}
      pod: ${HOSTNAME:local}

server:
  port: 8080
  shutdown: graceful

processing:
  delay-ms: ${PROCESSING_DELAY_MS:100}
  topic: messages

The Message Processing Service

The application exposes a REST endpoint for submitting messages and processes them asynchronously from Kafka. It tracks processing times and throughput via Micrometer so KEDA can query those metrics via Prometheus.

Main Application Class

package com.vimleshpandey.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class KedaAutoscalingDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(KedaAutoscalingDemoApplication.class, args);
    }
}

Message Producer (REST Controller)

package com.vimleshpandey.demo.controller;

import com.vimleshpandey.demo.service.MessageProducerService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    private final MessageProducerService producer;

    public MessageController(MessageProducerService producer) {
        this.producer = producer;
    }

    @PostMapping
    public ResponseEntity<Map<String, String>> submit(@RequestBody Map<String, String> body) {
        String messageId = UUID.randomUUID().toString();
        String payload = body.getOrDefault("payload", "empty");
        producer.send(messageId, payload);
        return ResponseEntity.accepted()
            .body(Map.of("messageId", messageId, "status", "queued"));
    }

    @PostMapping("/bulk/{count}")
    public ResponseEntity<Map<String, Object>> bulkSubmit(@PathVariable int count) {
        for (int i = 0; i < count; i++) {
            producer.send(UUID.randomUUID().toString(), "bulk-message-" + i);
        }
        return ResponseEntity.accepted()
            .body(Map.of("submitted", count, "status", "queued"));
    }
}

Message Producer Service

package com.vimleshpandey.demo.service;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class MessageProducerService {

    private static final Logger log = LoggerFactory.getLogger(MessageProducerService.class);

    private final KafkaTemplate<String, String> kafkaTemplate;
    private final String topic;
    private final Counter sentCounter;

    public MessageProducerService(
            KafkaTemplate<String, String> kafkaTemplate,
            @Value("${processing.topic}") String topic,
            MeterRegistry registry) {
        this.kafkaTemplate = kafkaTemplate;
        this.topic = topic;
        this.sentCounter = Counter.builder("messages.sent")
            .description("Total messages sent to Kafka")
            .register(registry);
    }

    public void send(String key, String payload) {
        kafkaTemplate.send(topic, key, payload)
            .whenComplete((result, ex) -> {
                if (ex != null) {
                    log.error("Failed to send message {}", key, ex);
                } else {
                    sentCounter.increment();
                    log.debug("Message {} sent to partition {}",
                        key, result.getRecordMetadata().partition());
                }
            });
    }
}

Message Consumer Service

package com.vimleshpandey.demo.service;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

@Service
public class MessageConsumerService {

    private static final Logger log = LoggerFactory.getLogger(MessageConsumerService.class);

    private final long processingDelayMs;
    private final Timer processingTimer;
    private final Counter processedCounter;

    public MessageConsumerService(
            @Value("${processing.delay-ms}") long processingDelayMs,
            MeterRegistry registry) {
        this.processingDelayMs = processingDelayMs;
        this.processingTimer = Timer.builder("message.processing.time")
            .description("Time spent processing each message")
            .publishPercentiles(0.5, 0.95, 0.99)
            .register(registry);
        this.processedCounter = Counter.builder("messages.processed")
            .description("Total messages successfully processed")
            .register(registry);
    }

    @KafkaListener(topics = "${processing.topic}", groupId = "${spring.kafka.consumer.group-id}")
    public void consume(
            String message,
            @Header(KafkaHeaders.RECEIVED_PARTITION) int partition,
            @Header(KafkaHeaders.OFFSET) long offset) {

        processingTimer.record(() -> {
            try {
                process(message, partition, offset);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
        });
    }

    private void process(String message, int partition, long offset)
            throws InterruptedException {
        log.debug("Processing message from partition={} offset={}", partition, offset);
        Thread.sleep(processingDelayMs + (long)(Math.random() * 50));
        processedCounter.increment();
    }
}

Horizontal Pod Autoscaler (HPA)

The HPA is the foundation of Kubernetes scaling. It watches a target metric and adjusts the replica count to bring that metric back toward its target value. CPU is the simplest signal, but it has well-known problems for JVM workloads: heap usage makes memory-based HPA unreliable, and JVM startup cost means HPA reacts late to sudden spikes.

CPU-Based HPA

# k8s/hpa-cpu.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: message-processor-hpa
  namespace: default
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: message-processor
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 60
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 30
      policies:
      - type: Pods
        value: 2
        periodSeconds: 60
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
      - type: Pods
        value: 1
        periodSeconds: 60

The behavior block is essential for production use. Without it, Kubernetes applies its defaults (300 seconds for scale-down, 0 for scale-up), which can cause flapping under variable load. The configuration above is aggressive on scale-up (add 2 pods per minute within 30-second decisions) but conservative on scale-down (remove 1 pod per minute after a 5-minute stabilization window).

Deployment with Proper Resource Requests

# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: message-processor
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: message-processor
  template:
    metadata:
      labels:
        app: message-processor
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/path: /actuator/prometheus
        prometheus.io/port: "8080"
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - name: message-processor
        image: vimleshpandey/message-processor:1.0.0
        ports:
        - containerPort: 8080
        env:
        - name: KAFKA_BOOTSTRAP_SERVERS
          value: kafka.kafka.svc.cluster.local:9092
        - name: JAVA_TOOL_OPTIONS
          value: "-XX:MaxRAMPercentage=75.0 -XX:+UseG1GC"
        resources:
          requests:
            cpu: "500m"
            memory: "512Mi"
          limits:
            cpu: "1000m"
            memory: "1Gi"
        readinessProbe:
          httpGet:
            path: /actuator/health/readiness
            port: 8080
          initialDelaySeconds: 20
          periodSeconds: 5
          failureThreshold: 3
        livenessProbe:
          httpGet:
            path: /actuator/health/liveness
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
          failureThreshold: 3
        lifecycle:
          preStop:
            exec:
              command: ["sh", "-c", "sleep 5"]

The preStop sleep gives Kubernetes time to remove the pod from the load balancer endpoints before the JVM begins its shutdown sequence, eliminating in-flight request failures during scale-down. The XX:MaxRAMPercentage=75.0 flag prevents the JVM from claiming more than 75% of the container's memory limit as heap, which would otherwise cause the container to exceed its memory limit and get OOM-killed.

Vertical Pod Autoscaler (VPA)

Before configuring KEDA, run the VPA in recommendation mode to see what resource requests your pods actually need under real traffic. This eliminates the guesswork that leads to either wasted capacity or unnecessary CPU throttling.

# k8s/vpa.yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: message-processor-vpa
  namespace: default
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: message-processor
  updatePolicy:
    updateMode: "Off"
  resourcePolicy:
    containerPolicies:
    - containerName: message-processor
      minAllowed:
        cpu: "250m"
        memory: "256Mi"
      maxAllowed:
        cpu: "2000m"
        memory: "2Gi"
      controlledResources:
      - cpu
      - memory

After 24 hours of real traffic, check the recommendations:

kubectl describe vpa message-processor-vpa | grep -A 20 "Container Recommendations"
# Container Recommendations:
#   Container Name:  message-processor
#   Lower Bound:
#     Cpu:     250m
#     Memory:  384Mi
#   Target:
#     Cpu:     450m
#     Memory:  512Mi
#   Upper Bound:
#     Cpu:     850m
#     Memory:  768Mi

Apply the target values to your deployment's resource requests. If you later switch VPA to Auto mode (live pod updates), always pair it with a PodDisruptionBudget — VPA in Auto mode can evict all pods simultaneously to apply its recommendations, causing a brief full outage on a small deployment:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: message-processor-pdb
spec:
  maxUnavailable: 1
  selector:
    matchLabels:
      app: message-processor

Keep HPA and VPA on different metrics to avoid conflicts. The safe combination is HPA on CPU (or KEDA event signals) and VPA on memory, or simply VPA in Off mode for recommendations only while HPA handles runtime scaling.

KEDA 2.20: Event-Driven Scaling with Kafka

The real win for a Kafka consumer is scaling on lag — the number of messages awaiting processing — rather than on CPU. When a message burst arrives, lag rises immediately, while CPU only rises after the pods start pulling and processing messages. KEDA's Kafka scaler reads consumer group lag directly from the broker, triggering new replicas before throughput degrades.

ScaledObject for Kafka Lag

# k8s/keda-kafka-scaledobject.yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: message-processor-kafka-scaler
  namespace: default
spec:
  scaleTargetRef:
    name: message-processor
  pollingInterval: 15
  cooldownPeriod: 60
  minReplicaCount: 2
  maxReplicaCount: 20
  triggers:
  - type: kafka
    metadata:
      bootstrapServers: kafka.kafka.svc.cluster.local:9092
      consumerGroup: message-processor-group
      topic: messages
      lagThreshold: "100"
      activationLagThreshold: "50"
      offsetResetPolicy: latest

The activationLagThreshold controls the minimum lag required to activate scaling from zero (or from minReplicas when minReplicas is 0). This prevents KEDA from oscillating when occasional small bursts arrive — it only activates after lag crosses 50 messages per partition, then keeps adding replicas as long as lag stays above 100 per partition.

> KEDA and HPA interaction. When KEDA creates a ScaledObject, it automatically creates a managed HPA resource and feeds it a custom metric. Do not create a separate HPA for the same deployment, as two HPAs on one target will conflict. Remove any CPU HPA once you switch to KEDA, or combine both signals in one ScaledObject by adding a second trigger.

Combining Kafka Lag and Prometheus Metrics

This is the production pattern — scale on lag AND on HTTP request queue depth simultaneously, using whichever signal calls for more replicas.

# k8s/keda-combined-scaledobject.yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: message-processor-combined
  namespace: default
spec:
  scaleTargetRef:
    name: message-processor
  pollingInterval: 15
  cooldownPeriod: 90
  minReplicaCount: 2
  maxReplicaCount: 20
  triggers:
  - type: kafka
    metadata:
      bootstrapServers: kafka.kafka.svc.cluster.local:9092
      consumerGroup: message-processor-group
      topic: messages
      lagThreshold: "100"
      activationLagThreshold: "50"
  - type: prometheus
    metadata:
      serverAddress: http://prometheus-kube-prometheus-prometheus.monitoring.svc:9090
      metricName: http_active_requests
      threshold: "50"
      query: >
        sum(http_server_requests_seconds_active_count{application="message-processor"})

KEDA uses the maximum across all triggers to determine the target replica count, which is exactly what you want: the deployment scales to whichever workload dimension needs the most capacity.

Testing Autoscaling Behaviour

Load Test with k6

// test/load-test.js
import http from 'k6/http';
import { sleep, check } from 'k6';

export const options = {
  stages: [
    { duration: '1m', target: 10 },
    { duration: '3m', target: 50 },
    { duration: '1m', target: 0 },
  ],
};

export default function () {
  const res = http.post(
    'http://message-processor.default.svc.cluster.local/api/messages/bulk/10',
    null,
    { headers: { 'Content-Type': 'application/json' } }
  );
  check(res, { 'status 202': (r) => r.status === 202 });
  sleep(0.1);
}
k6 run test/load-test.js

Watching HPA and KEDA React

In a second terminal, watch the events unfold:

kubectl get hpa,scaledobject -n default -w

kubectl describe scaledobject message-processor-combined

kubectl exec -n kafka kafka-0 -- kafka-consumer-groups.sh \
  --bootstrap-server localhost:9092 \
  --describe \
  --group message-processor-group

You should see replicas begin increasing within 15–30 seconds of a lag spike, peaking during the 3-minute burst, then dropping gradually during the 5-minute scale-down stabilization window.

Running the Application

Local Development

docker run -d \
  --name kafka \
  -p 9092:9092 \
  -e KAFKA_CFG_NODE_ID=0 \
  -e KAFKA_CFG_PROCESS_ROLES=controller,broker \
  -e KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 \
  -e KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 \
  -e KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=0@localhost:9093 \
  -e KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER \
  bitnami/kafka:3.7

docker exec kafka kafka-topics.sh \
  --bootstrap-server localhost:9092 \
  --create --topic messages --partitions 6 --replication-factor 1

./mvnw spring-boot:run

Deploy to Kubernetes

./mvnw spring-boot:build-image \
  -Dspring-boot.build-image.imageName=vimleshpandey/message-processor:1.0.0
docker push vimleshpandey/message-processor:1.0.0

kubectl apply -f k8s/

Common Pitfalls and Tips

1. Memory-based HPA almost always misfires with JVM workloads. The JVM allocates heap eagerly at startup, so an HPA targeting 70% memory utilisation will often peg the deployment at maxReplicas permanently. Use CPU for reactive scaling and KEDA for event-driven scaling. If you must track memory, query actual heap usage via jvm_memory_used_bytes{area="heap"} as a KEDA Prometheus trigger, not as an HPA memory target.

2. Partitions cap your max useful replicas. A Kafka consumer group cannot have more active consumers than there are partitions. If your topic has 6 partitions and maxReplicaCount is 20, only 6 replicas will ever do work. Align your partition count with your expected peak replica count and add headroom.

3. VPA in Auto mode evicts pods without a PDB. If you switch VPA to Auto on a deployment without a PodDisruptionBudget, VPA can evict all pods simultaneously, causing a brief full outage. Always pair VPA Auto mode with a PDB as shown above.

4. The 15-second polling interval is not free. KEDA's default polling interval queries Kafka every 15 seconds. If you have many ScaledObjects or a high-load Kafka cluster, consider raising it to 30 seconds for non-latency-sensitive consumers. KEDA 2.20 also supports a cacheMetricsTTL annotation to cache metrics at the ScaledObject level and reduce broker queries.

5. Test graceful shutdown or you will lose messages. The Spring Boot spring.lifecycle.timeout-per-shutdown-phase default is 30 seconds. If your longest message takes 60 seconds to process, messages in-flight when a scale-down evicts the pod will return to Kafka at their original offset and be reprocessed. Set a realistic terminationGracePeriodSeconds on the pod spec (at least 10 seconds more than your 95th-percentile processing time) and configure spring.kafka.consumer.shutdown-timeout to match.

6. Keep HPA and KEDA on separate targets. If you install a ScaledObject on a deployment that already has a manually created HPA, you now have two HPAs on the same target. The KEDA-managed HPA wins, but you will get warnings and confusing metrics in the control plane. Either delete the manual HPA or fold its CPU trigger into the ScaledObject as an additional Prometheus trigger.

Conclusion

Kubernetes autoscaling is most effective when you match the scaling signal to the actual bottleneck: CPU utilisation for compute-bound services, event queue depth for I/O-bound consumers, and VPA recommendations to right-size requests so that utilisation percentages are even meaningful in the first place.

KEDA 2.20 makes event-driven scaling a first-class operation — it integrates with Kafka, Prometheus, AWS SQS, Azure queues, and dozens of other sources without requiring you to write a single custom metrics adapter. The pattern shown here — minReplicas of 2 for HA, KEDA Kafka lag as the primary scale-up signal, Prometheus HTTP queue depth as a secondary trigger, and VPA in recommendation mode to calibrate requests — covers the majority of Java microservice autoscaling needs in a single composable stack.

KEDA's interaction with native HPA means you are not locked in: if you later outgrow this pattern, you can disable KEDA and return to native HPAv2 without changing your deployment or rewriting your Kubernetes manifests.