Skip to main content

Autoscaling Spring Boot Kafka Consumers on Kubernetes with KEDA: Lag, Partitions and Graceful Scale-Down

How KEDA turns Kafka consumer lag into replicas for a Spring Boot 4.2 consumer, and what it does to your pods: the partition ceiling, hot keys, rebalance cost, SIGTERM versus SIGKILL and Spring’s graceful shutdown, all run against a real Kafka 4.4 broker. KEDA itself and the manifests were not run on a cluster, and the post says so.

A consumer group on Kafka falls behind at nine in the morning, the pods are mostly waiting on a database, and the CPU graph is flat. A CPU-based autoscaler sees nothing wrong, because nothing is wrong with the CPU. The number that says “too slow” is consumer lag: how many records are sitting in the topic that the group has not acknowledged yet. KEDA is the Kubernetes component that turns that number into a replica count. The scaling arithmetic is the easy part. What this post is really about is what happens to your Spring Boot consumer when something else decides how many copies of it exist: a hard ceiling on useful pods, a rebalance on every scale event, and a shutdown path that decides how many records are processed twice. Each of those was run against a real Kafka broker for this article, and the post says plainly where that stops.
Versions and what was actually run. JDK Temurin 25.0.5.1 (LTS), Spring Boot 4.2.0 (on Maven Central since 2026-11-19), Spring for Apache Kafka 4.2.0, Apache Kafka 4.4.0 clients and an embedded KRaft broker. KEDA: the 2.21 documentation, and the source of the Kafka scaler at tag v2.21.1 (I could not retrieve the release date of that tag from here).

No Kubernetes cluster and no KEDA were run. The sandbox that built the companion module has no Docker daemon, so there was nothing to host kind. The consumer, the lag, the rebalances, SIGTERM versus SIGKILL and Spring’s graceful shutdown all ran against a real broker. The step from lag to replica count is a small model, KedaMath, written from the documentation and the scaler source and fed with real broker lag. The two YAML manifests are checked for syntax only. Wherever a claim rests on documentation or on my reading of source rather than on a run, it is marked that way.

A consumer group can use at most one pod per partition

Kafka splits a topic into partitions, and inside one consumer group each partition is read by exactly one consumer at a time. That single rule is the whole scaling story: the group can never do more parallel work than there are partitions. Give a group of eight pods a six-partition topic and two of them have nothing to read.
Topic "cap": 6 partitions, one consumer group of 8 pods P0 P1 P2 P3 P4 P5 c1 c2 c3 c4 c5 c6 c7 c8 no partition, no records Pods 7 and 8 are scheduled, billed and healthy, and receive nothing. The number of partitions is the ceiling on useful consumers in one group, whatever any autoscaler asks for.
The picture is what the broker did when I started 1, 3, 6 and then 8 consumers in one group on a six-partition topic (the test is KedaExperimentsTest.java, the transcript is 01-partition-cap.txt). With three consumers each got two partitions; with eight, the last two got an empty list:
N=3 consumers:
  c1 -> partitions [0, 1]
  c2 -> partitions [2, 3]
  c3 -> partitions [4, 5]
  idle consumers: 0
N=8 consumers:
  c1 -> partitions [0]
  c2 -> partitions [1]
  c3 -> partitions [2]
  c4 -> partitions [3]
  c5 -> partitions [4]
  c6 -> partitions [5]
  c7 -> partitions []
  c8 -> partitions []
  idle consumers: 2
This is why the module’s listener runs one thread per pod (spring.kafka.listener.concurrency=1). Threads inside a pod and pods in a Deployment both draw from the same pool of partitions, so adding both only multiplies the same ceiling. Let KEDA add pods, and keep each pod simple. The consumer itself is ordinary (OrderListener.java); the sleep stands in for a database write or an HTTP call:
@Component
public class OrderListener {

    private final Processed processed;
    private final long workMs;

    public OrderListener(Processed processed, @Value("${app.work-ms:0}") long workMs) {
        this.processed = processed;
        this.workMs = workMs;
    }

    @KafkaListener(topics = "${app.topic}")
    public void onMessage(ConsumerRecord<String, String> rec) throws InterruptedException {
        if (workMs > 0) {
            Thread.sleep(workMs); // stands in for a DB write or an HTTP call
        }
        processed.record(rec.topic(), rec.partition(), rec.offset());
    }
}
Choose the partition count before you choose the autoscaler. The partition count is the maximum replica count you can ever use, and adding partitions to a live topic changes which keys go where. If you expect to need 12 pods at peak, the topic needs at least 12 partitions on day one.
Going deeper: partitions, keys and why the ceiling is hard The ceiling comes from the assignment rule, not from KEDA. KEDA’s own documentation says the replica count is capped by the partition count by default and that extra consumers “will have to sit idle”; it offers allowIdleConsumers: true to lift the cap, which only makes sense if you want warm spares.

KEDA scales on lag, and lag is two offsets subtracted

Every partition is an append-only log. Producers push the log end offset forward; the group records how far it has got as its committed offset. The difference is that partition’s lag, and the scaler reports the sum over all partitions.
One partition: lag is the gap between two numbers already processed waiting: lag = 140 – 40 = 100 committed offset 40 (what the group has acknowledged) log end offset 140 (what producers have written) The scaler adds this subtraction up over every partition and reports the sum. Nothing about CPU, memory or request rate appears anywhere in it.
The module reproduces that definition with Kafka’s admin client (GroupLag.java), so the experiments read the same numbers the scaler would:
    public static Map<TopicPartition, Long> perPartition(String bootstrap, String group)
            throws ExecutionException, InterruptedException {
        Properties p = new Properties();
        p.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap);
        try (Admin admin = Admin.create(p)) {
            Map<TopicPartition, OffsetAndMetadata> committed =
                    admin.listConsumerGroupOffsets(group).partitionsToOffsetAndMetadata().get();
            Map<TopicPartition, OffsetSpec> latest = committed.keySet().stream()
                    .collect(Collectors.toMap(tp -> tp, tp -> OffsetSpec.latest()));
            Map<TopicPartition, ListOffsetsResult.ListOffsetsResultInfo> ends = admin.listOffsets(latest).all().get();
            Map<TopicPartition, Long> lag = new HashMap<>();
            committed.forEach((tp, oam) -> lag.put(tp, ends.get(tp).offset() - oam.offset()));
            return lag;
        }
    }
Two small facts about lag matter later. First, it is measured against what the group has committed, not against what a consumer has received, so a pod that processes records but crashes before committing still shows lag. Second, a group that exists but has read nothing is simply a group whose committed offsets are zero; the experiments create exactly that with Kafka.commitZero so that a known number of records is waiting.
Going deeper: lag when there is no committed offset yet For a partition with no committed offset, KEDA does not compute a difference. According to the scaler documentation and the v2.21.1 source, with offsetResetPolicy: latest (the default) it reports a lag of 1 for that partition, so one consumer stays up; scaleToZeroOnInvalidOffset: true makes it 0; with earliest it reports the retained backlog. This part was read, not run.

Three numbers turn lag into a replica count

Per the documentation, lagThreshold is the lag you are willing to carry per replica (default 10). The Kubernetes HPA then asks for roughly total lag / lagThreshold replicas, rounded up. Two limits sit on top: the partition count (the ceiling from the first section) and maxReplicaCount in the ScaledObject (default 100).
Worked example from output/02: lagThreshold 50, 6 partitions, 600 records behind total lag600 600 / 50 = 12more than 6 partitions clamp the metric6 x 50 = 300 HPA: ceil(300 / 50)6 replicas With allowIdleConsumers=true the clamp is skipped and the same lag asks for 12 replicas, six of them idle. The cap is applied to the metric before the HPA sees it, not to the HPA itself. That is why the integer division in the comparison matters (see the remainder edge case below).
KedaMath.java is those rules as code. It is a model, not KEDA, and the Javadoc at the top of the file says so:
    public static Decision decide(Map<TopicPartition, Long> lagByPartition, int topicPartitions, Config c) {
        long total = lagByPartition.values().stream().mapToLong(Long::longValue).sum();
        long withLag = lagByPartition.values().stream().filter(l -> l > 0).count();

        long reported = total;
        if (!c.allowIdleConsumers() || c.limitToPartitionsWithLag()) {
            long upperBound = c.limitToPartitionsWithLag() ? withLag : topicPartitions;
            if (total / c.lagThreshold() > upperBound) {
                reported = upperBound * c.lagThreshold();
            }
        }

        boolean active = total > c.activationLagThreshold();
        long hpa = (reported + c.lagThreshold() - 1) / c.lagThreshold();
        int desired = (int) Math.min(hpa, c.maxReplicas());
        if (!active && c.minReplicas() == 0) {
            desired = 0;
        } else {
            desired = Math.max(desired, Math.max(c.minReplicas(), active ? 1 : 0));
        }
        return new Decision(total, reported, active, desired);
    }
Fed with lag read from a real broker (02-lag-to-replicas.txt), it gives the numbers in the diagram above:
A) uniform: {0=100, 1=100, 2=100, 3=100, 4=100, 5=100} total=600
   lagThreshold=100                       -> total=600 metric=600 desired=6
   lagThreshold=50  (wants 12, 6 partitions) -> total=600 metric=300 desired=6
   same, allowIdleConsumers=true           -> total=600 metric=600 desired=12
A hot key defeats the arithmetic. Six partitions, 600 records, all of them on partition 0 (a hot key does this; case B in the same transcript). The sum is still 600, so the model still asks for 6 replicas, but only one partition has work and five pods would idle. The documented fix is limitToPartitionsWithLag: true, which bounds the replica count by the number of partitions that actually have lag. It needs topic to be set and cannot be combined with allowIdleConsumers.
B) skewed (hot key): {0=600, 1=0, 2=0, 3=0, 4=0, 5=0} total=600
   default                                 -> total=600 desired=6  (5 of 6 pods would sit idle)
   limitToPartitionsWithLag=true           -> total=600 desired=1
Going deeper: a remainder edge case I found in the source (modelled, not run on KEDA) Reading the scaler source at v2.21.1 (through a fetch tool that returns excerpts, so treat this as a lead to verify rather than a proven fact), the clamp compares totalLag / lagThreshold using integer division in a 64-bit integer type. My model reproduces that comparison. The consequence appears when the lag is a few records over an exact multiple: 650 records on 6 partitions with a threshold of 100 gives 650 / 100 = 6, which is not greater than 6, so the clamp is skipped, the metric stays 650, and the HPA’s round-up asks for 7 replicas on a 6-partition topic (model output, from 02-lag-to-replicas.txt):
C) remainder edge: {0=150, 1=100, 2=100, 3=100, 4=100, 5=100} total=650
   650 / 100 = 6 (integer) is not > 6, so the clamp is skipped -> metric=650 desired=7 on 6 partitions
If that is true on a real cluster the extra pod would simply idle until the lag drops. It is cheap to check: publish a known lag that is a few records over a multiple of lagThreshold × partitions and watch the desired replica count in kubectl describe hpa.
Going deeper: what the HPA adds on top (documentation, not run) The scaler only produces a number. The HPA that KEDA creates turns it into replicas with the standard Kubernetes algorithm, so the usual HPA behaviour applies: a tolerance band around the target, a scale-down stabilization window and rate-limiting policies. The ScaledObject passes advanced.horizontalPodAutoscalerConfig.behavior straight through to the HPA. None of that is modelled in KedaMath, which is why the model gives instant answers and a real cluster will not.

The ScaledObject: a few fields that matter and a few that surprise

A ScaledObject points at your Deployment and lists triggers. The one in the module (scaledobject.yaml) is below. It was not applied to any cluster; field names and defaults come from the KEDA 2.21 documentation:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: orders-consumer
spec:
  scaleTargetRef:
    name: orders-consumer
  pollingInterval: 15          # seconds between scaler checks when scaling from/to zero (default 30)
  cooldownPeriod: 120          # only delays scale-to-ZERO after the last active trigger (default 300)
  minReplicaCount: 1           # 0 enables scale-to-zero (the default); 1 keeps one warm pod
  maxReplicaCount: 6           # keep <= partitions of the topic; more pods than partitions sit idle
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:                # passed straight to the HPA
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
            - type: Pods
              value: 1
              periodSeconds: 60   # remove at most one pod a minute: every removal is a rebalance
  triggers:
    - type: kafka
      metadata:
        bootstrapServers: kafka.kafka.svc.cluster.local:9092
        consumerGroup: orders-consumer
        topic: orders
        lagThreshold: "100"             # target lag PER REPLICA (default 10)
        activationLagThreshold: "10"    # lag must be strictly greater than this to wake from zero
        offsetResetPolicy: earliest
        # limitToPartitionsWithLag: "true"   # for skewed topics; needs `topic`; not with allowIdleConsumers
Three of those fields are easy to misread. cooldownPeriod (default 300 seconds) delays only the last step to zero; scaling from one pod to many and back is the HPA’s job. activationLagThreshold is compared with “strictly greater than”, so with the default of 0 a lag of exactly 0 stays asleep and a lag of 1 wakes the group, which is what the model shows in the last case of the same transcript:
D) activation (minReplicaCount=0, activationLagThreshold=0):
   lag=0 -> active=false desired=0;  lag=1 -> active=true desired=1
And minReplicaCount: 1 versus the default of 0 is a business decision, not a tuning one: scale-to-zero saves money and costs you a cold start (JVM start, Kafka join, first rebalance) before the first record is read.
Going deeper: the trigger parameters worth knowing (from the 2.21 scaler page)
ParameterDefaultWhat it does
lagThreshold10Target lag per replica
activationLagThreshold0Lag must be strictly greater to wake from zero
offsetResetPolicylatestWhich lag to report for partitions with no committed offset
allowIdleConsumersfalseLift the partition ceiling
limitToPartitionsWithLagfalseCeiling = partitions that have lag; needs topic
scaleToZeroOnInvalidOffsetfalseReport 0 instead of 1 when no offset exists (policy latest)
excludePersistentLagfalseIgnore partitions whose offset has not moved since the last poll (stuck partitions)
partitionLimitationallOnly count the listed partition ids
The ScaledObject also has a fallback block for the case where the scaler itself cannot reach Kafka: after failureThreshold consecutive failures KEDA reports a metric that makes the HPA hold fallback.replicas. Without it, an unreachable broker means the autoscaler is blind rather than wrong. Documentation only; not run.

Every scale event is a rebalance

Adding or removing a pod changes the group’s membership, and the group responds by re-dividing the partitions: a rebalance. How disruptive that is depends on the assignment protocol. The old “eager” protocol makes every member give up every partition, then hands them out again, so the whole group pauses. The cooperative protocol revokes only the partitions that actually have to move.
KEDA adds two pods: what pod A has to give up (output/03) Before: A alone P0 P1 P2 P3 P4 P5 Eager (RangeAssignor): all six are revoked first P0 P1 P2 P3 P4 P5 Cooperative: only the partitions that must move are revoked P0 P1 P2 P3 P4 P5 revoked from A: 0 revoked from A: 6 of 6 revoked from A: 4 of 6 Every pod added or removed is a rebalance; the assignor decides how much of the group pauses for it.
I measured it with the scale-out KEDA would perform: one pod owning all six partitions, then two more joining at once. The transcript is 03-rebalance-cost.txt:
classic + RangeAssignor (eager)
  final: A=[0, 1] B=[2, 3] C=[4, 5]
  partitions A had to give up: 6 of 6;  time until last assignment change: ~189 ms
classic + CooperativeStickyAssignor
  final: A=[0, 1] B=[2, 4] C=[3, 5]
  partitions A had to give up: 4 of 6;  time until last assignment change: ~3197 ms
group.protocol=consumer (KIP-848)
  final: A=[0, 1] B=[3, 4] C=[2, 5]
  partitions A had to give up: 4 of 6;  time until last assignment change: ~5120 ms
Pod A gave up all six partitions under the eager protocol and four under the cooperative one; the newer KIP-848 “consumer” protocol also moved four. In that run the eager rebalance settled fastest (under a second, against several seconds for the other two) but it paused every partition while it did. Timings drift from run to run; the revoked counts are what the test asserts. This matters more under autoscaling than under manual scaling, because KEDA keeps changing the pod count. I checked ConsumerConfig in kafka-clients 4.4.0: the default partition.assignment.strategy is [RangeAssignor, CooperativeStickyAssignor] and the default group.protocol is classic. With that list, members agree on the first strategy they all support, which is Range, so the default behaves like the eager row above. The module opts in to cooperative rebalancing explicitly (application.yml):
# One consumer thread per pod; KEDA adds pods.
app:
  topic: orders
  work-ms: 0

spring:
  application:
    name: keda-consumer
  kafka:
    bootstrap-servers: ${KAFKA_BOOTSTRAP:localhost:9092}
    consumer:
      group-id: orders-consumer
      auto-offset-reset: earliest
      enable-auto-commit: false          # the container commits after each batch
      max-poll-records: 50
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      properties:
        # cooperative rebalancing: pods joining/leaving only move the partitions that must move
        partition.assignment.strategy: org.apache.kafka.clients.consumer.CooperativeStickyAssignor
        session.timeout.ms: 15000
    listener:
      concurrency: 1
      # how long a stopping container waits for the in-flight batch (Spring Kafka default 10s)
      shutdown-timeout: 20s
  lifecycle:
    # must be shorter than the pod's terminationGracePeriodSeconds
    timeout-per-shutdown-phase: 25s

server:
  shutdown: graceful

management:
  endpoint:
    health:
      probes:
        enabled: true
  endpoints:
    web:
      exposure:
        include: health
A rebalance is also the symptom of a bad scaling policy. If KEDA adds and removes a pod every few minutes, the group spends its life rebalancing and lag never drops. That is what the behavior.scaleDown block in the ScaledObject (one pod a minute, five-minute stabilization) is for. The right numbers depend on how long a rebalance takes in your group, which only a real cluster can tell you.
Going deeper: the settings behind these numbers session.timeout.ms is how long the broker waits without a heartbeat before it declares a member dead (the client default in 4.4.0 is 45 seconds; the module sets 15 seconds so a dead pod is replaced sooner). max.poll.interval.ms (300 seconds by default) is how long one batch may take between polls; if a batch of slow records exceeds it the member is kicked out and the group rebalances even though the pod is healthy. Under autoscaling the dangerous combination is a large max.poll.records with slow records, because it creates long gaps between polls exactly when the group is busy.

Scale-down is where records get processed twice

Scaling up is forgiving. Scaling down is where records are replayed, because Kubernetes terminates the pod mid-work. Kubernetes sends SIGTERM first and SIGKILL after terminationGracePeriodSeconds. What the consumer does in between decides two things: how quickly another pod takes over, and how many records are handled twice. To see both, CrashableConsumer.java runs as a separate JVM that processes records at 50 ms each and commits every 20. The test lets it process 30 (20 committed, 10 in flight), keeps a standby consumer in the same group, and then really signals the child. The transcript is 04-sigterm-vs-sigkill.txt:
SIGTERM (what Kubernetes sends on scale-down):
  child had processed 31, committed 20 at the moment of the signal
  standby's first record: offset 20 after 108 ms
  records processed twice (child processed 31, standby restarted at 20): 11
SIGKILL (pod crash, node loss):
  child had processed 30, committed 20 at the moment of the signal
  standby's first record: offset 20 after 5481 ms
  records processed twice (child processed 30, standby restarted at 20): 10
Time until the standby pod gets its first record (output/04, same scale) SIGTERM 108 ms: the dying pod said goodbye (left the group) SIGKILL 5,481 ms: the broker waited out session.timeout.ms=6000 before reassigning Both: the standby restarted at offset 20, the last commit, and re-processed the 10 or 11 records the dead pod had already handled. Graceful stop buys speed, not exactness: records are replayed either way, so the consumer must tolerate duplicates.
Two lessons. A graceful stop is about latency: after SIGTERM the consumer closes and leaves the group, so the standby is served in about a tenth of a second (108 ms in the committed run), while a SIGKILL makes the broker wait out the session timeout (6 seconds here, the broker’s minimum; the default client value is 45). And in both cases the records that were processed but not yet committed come back (10 after the SIGKILL, 11 after the SIGTERM, because the child had got one record further when that signal landed), because Kafka consumers are at-least-once. A graceful stop does not make duplicates go away unless the code finishes and commits its batch first. That is what Spring’s listener container does. With the module’s real application, 200 records and 50 ms of work each, the test closes the Spring context while a batch is in flight (05-spring-graceful-shutdown.txt):
pod A: context.close() took ~740 ms; processed=40; committed offset=40
pod B (same group): processed=160 until lag=0
records processed twice across A and B: 0
The container completed the batch it was in, committed it, and stopped; the second pod continued from exactly that offset. For this to work on Kubernetes, the pod must be given enough time. The relevant settings are in application.yml above (shutdown-timeout and timeout-per-shutdown-phase) and the Deployment must allow longer than both (deployment.yaml, not applied to a cluster):
      # Must exceed spring.lifecycle.timeout-per-shutdown-phase (25s) plus a margin, otherwise
      # Kubernetes sends SIGKILL while the container is still finishing its batch.
      terminationGracePeriodSeconds: 60
Make the handler idempotent anyway. The graceful path removed duplicates in this test, but a SIGKILL, an out-of-memory kill or a node loss still replays the uncommitted tail, as the table above shows. If processing a record twice would charge a card twice, deduplicate on a key. The idempotency-key pattern is covered in Idempotency Keys for POST APIs in Spring Boot.
Going deeper: probes, readiness and long batches Readiness probes do not gate a Kafka consumer the way they gate an HTTP service: Kafka, not a Service, decides when a pod receives work. What they do control is when a rolling update considers the new pod healthy. The Spring Boot probe endpoints, graceful shutdown phases and resource limits for Kubernetes are covered in Deploying Spring Boot 4 on Kubernetes; a Kafka-centred design that needs the same retry and dedup discipline is System Design: Notification Service with Spring Boot and Kafka. A batch that takes longer than terminationGracePeriodSeconds to finish is killed mid-way, so size max.poll.records and per-record work so that one batch fits comfortably inside the grace period, or lower max.poll.records for services whose records are slow.

When it does not scale, look here first

These are the symptoms to check, in the order I would check them. Rows marked “measured” reproduce in the companion module; the rest come from the KEDA documentation and are untested here.
SymptomLikely causeWhere it comes from
Lag is high but replicas stop growingThe partition ceiling, or maxReplicaCountMeasured (output 01, 02)
Pods at the cap, but lag drains slowlyHot partition: one busy pod, the rest idleMeasured (output 02, case B)
Replicas oscillate and lag never clearsScale events are rebalances; tighten behavior.scaleDownRebalance cost measured (output 03); the oscillation itself is not
Duplicate side effects after scale-downUncommitted tail replayedMeasured (output 04)
Group never wakes from zeroactivationLagThreshold is not exceeded, or the offset policy reports 0Documentation; the activation rule is modelled (output 02, case D)
Metrics unavailable, replicas frozenScaler cannot reach Kafka; configure fallbackDocumentation only
Should you even do this? If your lag is predictable (a nightly batch, a steady stream) a fixed replica count equal to the partition count is simpler, has no rebalancing churn and is easier to reason about. KEDA earns its place when load is spiky and the cost of idle pods matters. It does not remove the two real limits: you cannot use more pods than partitions, and every scale event pauses some part of the group. I did not run KEDA for this post, so measure your own rebalance time and cold-start time on a test cluster before you set minReplicaCount to 0.

Reproduce it

Everything above regenerates with scripts/run-all.sh (JDK 25 and access to Maven Central; the tests assert the same numbers they print, so the build fails if a quoted figure stops being true). Its core is one Maven run:
mvn -B test
echo "done: $(ls output | wc -l) files in output/"
The module is in the java-devops-demo/keda repository; the README there lists each transcript.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.