diff --git a/README.md b/README.md index a258bdb..69cb829 100644 --- a/README.md +++ b/README.md @@ -9,5 +9,6 @@ Runnable companion projects for build, release and DevOps posts on [ankurm.com]( | [jbang](jbang/) | JBang: Run Java Like a Script in 2026 (Dependencies, Templates, Spring Boot and Native Images) | JBang 0.132.1 on JDK 25: `//DEPS`, compact source files, `//SOURCES`, a single-file Spring Boot 4.2 app, templates and aliases, remote scripts and `jbang trust`, `--native` with GraalVM | | [jib](jib/) | Jib for Spring Boot: Container Images Without a Dockerfile (vs Buildpacks) | Spring Boot 4.2.0 built into an image with Jib 3.5.2 and with Buildpacks: layers, reproducible digests, registry push, failure modes, memory behaviour | | [gitea-actions](gitea-actions/) | Gitea Actions CI for Spring Boot: Build, Test, SBOM and Image Push | Spring Boot 4.2.0 pipeline: surefire/failsafe split, Testcontainers, Maven cache, CycloneDX SBOM, Jib push, and what breaks when Gitea runs under a URL sub-path | +| [keda](keda/) | Autoscaling Spring Boot Kafka Consumers on Kubernetes with KEDA | Spring Boot 4.2.0 consumer against a real Kafka 4.4.0 broker: partition cap, lag to replica maths, rebalance cost, SIGTERM vs SIGKILL, graceful shutdown; KEDA manifests included but not applied to a cluster | MIT licensed. diff --git a/keda/.gitignore b/keda/.gitignore new file mode 100644 index 0000000..ec10551 --- /dev/null +++ b/keda/.gitignore @@ -0,0 +1,3 @@ +target/ +.idea/ +*.iml diff --git a/keda/README.md b/keda/README.md new file mode 100644 index 0000000..e0d45c6 --- /dev/null +++ b/keda/README.md @@ -0,0 +1,56 @@ +# keda: autoscaling Spring Boot Kafka consumers + +Companion module for the ankurm.com post *Autoscaling Spring Boot Kafka Consumers on Kubernetes with KEDA*. +It answers one question with running code: **what does the consumer do when something else decides how many copies of it exist?** + +## Verified against + +| Component | Version | Source | +|---|---|---| +| JDK | Temurin 25.0.5.1 (LTS) | `output/00-versions.txt` | +| Spring Boot | 4.2.0 | Maven Central | +| Spring for Apache Kafka | 4.2.0 | `output/00-versions.txt` | +| Apache Kafka (clients and the embedded KRaft broker) | 4.4.0 | `output/00-versions.txt` | +| KEDA (documentation and scaler source read) | 2.21 / v2.21.1 | keda.sh docs, `apache_kafka_scaler.go` | + +## What was run, and what was not + +| Part | Status | +|---|---| +| Consumer app, group lag, rebalances, SIGTERM vs SIGKILL, Spring graceful shutdown | **Run** against a real in-JVM Kafka broker; output in `output/` | +| `KedaMath` (scaler + HPA arithmetic) | **A model** written from the KEDA docs and source, run against real broker lag. KEDA itself was not run | +| `k8s/*.yaml` | **Not applied to any cluster** (the build sandbox has no Docker daemon). YAML syntax checked only | + +## Run it + +```bash +export JAVA_HOME=/path/to/jdk-25 +./scripts/run-all.sh # regenerates output/*.txt; the tests assert the same numbers +``` + +Timing figures (rebalance milliseconds, the SIGKILL takeover time) drift between runs; the counts are asserted. + +## Layout + +| Path | What it is | +|---|---| +| `src/main/java/com/ankurm/keda/OrderListener.java` | The consumer: one listener thread per pod | +| `src/main/java/com/ankurm/keda/GroupLag.java` | Group lag as the KEDA Kafka scaler defines it | +| `src/main/java/com/ankurm/keda/KedaMath.java` | Model of lagThreshold, partition cap, activation, HPA ceiling | +| `src/main/resources/application.yml` | Graceful shutdown, cooperative rebalancing, manual commits | +| `src/test/java/com/ankurm/keda/KedaExperimentsTest.java` | The five experiments | +| `src/test/java/com/ankurm/keda/CrashableConsumer.java` | Child-JVM consumer that is really SIGTERMed / SIGKILLed | +| `k8s/deployment.yaml`, `k8s/scaledobject.yaml` | Manifests (not executed) | + +## Captured output + +| File | Shows | +|---|---| +| `output/00-versions.txt` | JDK, Maven and resolved Kafka artifacts | +| `output/01-partition-cap.txt` | 6 partitions, 1/3/6/8 consumers: the 7th and 8th get nothing | +| `output/02-lag-to-replicas.txt` | Real lag from the broker turned into replica counts; skew; remainder edge; activation | +| `output/03-rebalance-cost.txt` | Partitions a pod gives up when KEDA adds two pods: eager vs cooperative vs KIP-848 | +| `output/04-sigterm-vs-sigkill.txt` | Takeover time and replayed records after SIGTERM and SIGKILL | +| `output/05-spring-graceful-shutdown.txt` | Spring Boot context close mid-batch: no record processed twice | + +MIT licensed (see the repository root). diff --git a/keda/k8s/deployment.yaml b/keda/k8s/deployment.yaml new file mode 100644 index 0000000..ef6fff2 --- /dev/null +++ b/keda/k8s/deployment.yaml @@ -0,0 +1,34 @@ +# NOT EXECUTED: the sandbox that produced this module has no Docker daemon, so no cluster was +# available. These manifests are checked only for YAML syntax. Apply them to a test cluster first. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: orders-consumer +spec: + # KEDA/HPA owns the replica count once the ScaledObject exists; leave `replicas` unset. + selector: + matchLabels: + app: orders-consumer + template: + metadata: + labels: + app: orders-consumer + spec: + # 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 + containers: + - name: app + image: registry.example.com/keda-consumer:1.0.0 # build with your usual image pipeline + env: + - name: SPRING_KAFKA_BOOTSTRAP_SERVERS + value: kafka.kafka.svc.cluster.local:9092 + ports: + - containerPort: 8080 + readinessProbe: + httpGet: {path: /actuator/health/readiness, port: 8080} + livenessProbe: + httpGet: {path: /actuator/health/liveness, port: 8080} + resources: + requests: {cpu: 250m, memory: 512Mi} + limits: {memory: 512Mi} diff --git a/keda/k8s/scaledobject.yaml b/keda/k8s/scaledobject.yaml new file mode 100644 index 0000000..42b62a0 --- /dev/null +++ b/keda/k8s/scaledobject.yaml @@ -0,0 +1,32 @@ +# NOT EXECUTED: see deployment.yaml. Field names and defaults were taken from the KEDA 2.21 +# documentation (ScaledObject specification and the Apache Kafka scaler page). +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 diff --git a/keda/output/00-versions.txt b/keda/output/00-versions.txt new file mode 100644 index 0000000..91c33f3 --- /dev/null +++ b/keda/output/00-versions.txt @@ -0,0 +1,12 @@ +# environment +openjdk version "25.0.5.1" 2026-11-17 LTS +OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS) +OpenJDK 64-Bit Server VM Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS, mixed mode, sharing) +Apache Maven 3.9.11 (3e54c93a704957b63ee3494413a2b544fd3d825b) +# resolved dependencies +org.apache.kafka:kafka-clients:jar:4.4.0:compile -- module kafka.clients (auto) +org.apache.kafka:kafka-clients:jar:test-fixtures:4.4.0:test -- module kafka.clients (auto) +org.apache.kafka:kafka-clients:jar:test:4.4.0:test -- module kafka.clients (auto) +org.springframework.boot:spring-boot-starter-kafka:jar:4.2.0:compile -- module spring.boot.starter.kafka [auto] +org.springframework.kafka:spring-kafka-test:jar:4.2.0:test -- module spring.kafka.test [auto] +org.springframework.kafka:spring-kafka:jar:4.2.0:compile -- module spring.kafka [auto] diff --git a/keda/output/01-partition-cap.txt b/keda/output/01-partition-cap.txt new file mode 100644 index 0000000..fc6f546 --- /dev/null +++ b/keda/output/01-partition-cap.txt @@ -0,0 +1,31 @@ +Topic 'cap' has 6 partitions. N consumers join one group; who gets what? + +N=1 consumers: + c1 -> partitions [0, 1, 2, 3, 4, 5] + idle consumers: 0 + +N=3 consumers: + c1 -> partitions [0, 1] + c2 -> partitions [2, 3] + c3 -> partitions [4, 5] + idle consumers: 0 + +N=6 consumers: + c1 -> partitions [1] + c2 -> partitions [2] + c3 -> partitions [3] + c4 -> partitions [4] + c5 -> partitions [5] + c6 -> partitions [0] + 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 diff --git a/keda/output/02-lag-to-replicas.txt b/keda/output/02-lag-to-replicas.txt new file mode 100644 index 0000000..cc59384 --- /dev/null +++ b/keda/output/02-lag-to-replicas.txt @@ -0,0 +1,17 @@ +Lag is read from the broker (log end offset - committed offset, summed). +Replica counts come from KedaMath, a model of the scaler + HPA (KEDA is not run here). + +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 + +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 + +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 + +D) activation (minReplicaCount=0, activationLagThreshold=0): + lag=0 -> active=false desired=0; lag=1 -> active=true desired=1 diff --git a/keda/output/03-rebalance-cost.txt b/keda/output/03-rebalance-cost.txt new file mode 100644 index 0000000..2c68900 --- /dev/null +++ b/keda/output/03-rebalance-cost.txt @@ -0,0 +1,15 @@ +1 pod owns 6 partitions; KEDA adds 2 pods. How many partitions does pod 1 give up? + +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 + +Timing varies per run; the revoked-partition counts are what the test asserts. diff --git a/keda/output/04-sigterm-vs-sigkill.txt b/keda/output/04-sigterm-vs-sigkill.txt new file mode 100644 index 0000000..546cba2 --- /dev/null +++ b/keda/output/04-sigterm-vs-sigkill.txt @@ -0,0 +1,15 @@ +A consumer JVM processes records (50 ms each) and commits every 20. We stop it after it has +processed 30 records (20 committed + 10 in flight). A standby consumer is already in the group. +session.timeout.ms=6000 (the broker's minimum). + +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 + +Both replay the uncommitted tail (at-least-once). Only SIGKILL also waits out session.timeout.ms. diff --git a/keda/output/05-spring-graceful-shutdown.txt b/keda/output/05-spring-graceful-shutdown.txt new file mode 100644 index 0000000..af8a750 --- /dev/null +++ b/keda/output/05-spring-graceful-shutdown.txt @@ -0,0 +1,8 @@ +The real Spring Boot app (OrderListener, 50 ms of work per record, max.poll.records=20). +200 records on one partition. Close the context after >= 25 records were processed. + +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 + +Spring's container finished the in-flight batch and committed it before stopping. diff --git a/keda/pom.xml b/keda/pom.xml new file mode 100644 index 0000000..84b3322 --- /dev/null +++ b/keda/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + keda + 1.0.0 + keda + Autoscaling Spring Boot Kafka consumers on Kubernetes with KEDA + + + 25 + + + + + org.springframework.boot + spring-boot-starter-kafka + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-webmvc + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.kafka + spring-kafka-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/keda/scripts/run-all.sh b/keda/scripts/run-all.sh new file mode 100755 index 0000000..d707fa2 --- /dev/null +++ b/keda/scripts/run-all.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Regenerates every file in output/ with one command. Needs JDK 25 and network access to Maven Central. +# Timing figures (rebalance milliseconds, SIGKILL takeover time) drift between runs; the counts are asserted. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p output + +{ + echo "# environment" + java -version 2>&1 | grep -v '^Picked up' + mvn -v 2>&1 | grep -E '^Apache Maven' + echo "# resolved dependencies" + mvn -B -q dependency:list -DincludeArtifactIds=kafka-clients,spring-kafka,spring-boot-starter-kafka,spring-kafka-test \ + -DoutputFile=/dev/stdout 2>/dev/null | grep -E ':(jar):' | sed 's/^ *//' | sort -u +} > output/00-versions.txt + +mvn -B test +echo "done: $(ls output | wc -l) files in output/" diff --git a/keda/src/main/java/com/ankurm/keda/GroupLag.java b/keda/src/main/java/com/ankurm/keda/GroupLag.java new file mode 100644 index 0000000..8cbde08 --- /dev/null +++ b/keda/src/main/java/com/ankurm/keda/GroupLag.java @@ -0,0 +1,44 @@ +package com.ankurm.keda; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; + +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.ListOffsetsResult; +import org.apache.kafka.clients.admin.OffsetSpec; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.common.TopicPartition; + +/** + * Consumer-group lag the way the KEDA Kafka scaler defines it: for every partition, + * (log end offset) - (committed offset of the group), summed over partitions. + */ +public final class GroupLag { + + private GroupLag() { + } + + public static Map 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 committed = + admin.listConsumerGroupOffsets(group).partitionsToOffsetAndMetadata().get(); + Map latest = committed.keySet().stream() + .collect(Collectors.toMap(tp -> tp, tp -> OffsetSpec.latest())); + Map ends = admin.listOffsets(latest).all().get(); + Map lag = new HashMap<>(); + committed.forEach((tp, oam) -> lag.put(tp, ends.get(tp).offset() - oam.offset())); + return lag; + } + } + + public static long total(Map perPartition) { + return perPartition.values().stream().mapToLong(Long::longValue).sum(); + } +} diff --git a/keda/src/main/java/com/ankurm/keda/KedaConsumerApplication.java b/keda/src/main/java/com/ankurm/keda/KedaConsumerApplication.java new file mode 100644 index 0000000..dcf9716 --- /dev/null +++ b/keda/src/main/java/com/ankurm/keda/KedaConsumerApplication.java @@ -0,0 +1,16 @@ +package com.ankurm.keda; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * A deliberately small Kafka consumer: the interesting part of KEDA autoscaling is not the + * listener, it is what happens around it (partitions, lag, rebalances, shutdown). + */ +@SpringBootApplication +public class KedaConsumerApplication { + + public static void main(String[] args) { + SpringApplication.run(KedaConsumerApplication.class, args); + } +} diff --git a/keda/src/main/java/com/ankurm/keda/KedaMath.java b/keda/src/main/java/com/ankurm/keda/KedaMath.java new file mode 100644 index 0000000..0c6a331 --- /dev/null +++ b/keda/src/main/java/com/ankurm/keda/KedaMath.java @@ -0,0 +1,55 @@ +package com.ankurm.keda; + +import java.util.Map; + +import org.apache.kafka.common.TopicPartition; + +/** + * A small model of what the KEDA Kafka scaler plus the Kubernetes HPA decide, written from the + * scaler's documentation and the v2.21.1 source ({@code pkg/scalers/apache_kafka_scaler.go}). + * It is a model: KEDA itself is not executed anywhere in this repository's tests. + * + *
    + *
  1. the scaler reports total lag as the metric, clamped to {@code upperBound * lagThreshold} + * (integer division in the comparison) unless {@code allowIdleConsumers} is on
  2. + *
  3. the HPA, with an {@code AverageValue} target of {@code lagThreshold}, asks for + * {@code ceil(metric / lagThreshold)} replicas
  4. + *
  5. the ScaledObject's min/max replica counts clamp the result
  6. + *
+ * Ignored on purpose: HPA tolerance, readiness of new pods, stabilization windows. + */ +public final class KedaMath { + + private KedaMath() { + } + + public record Config(long lagThreshold, long activationLagThreshold, int minReplicas, int maxReplicas, + boolean allowIdleConsumers, boolean limitToPartitionsWithLag) { + } + + public record Decision(long totalLag, long reportedMetric, boolean active, int desired) { + } + + public static Decision decide(Map 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); + } +} diff --git a/keda/src/main/java/com/ankurm/keda/OrderListener.java b/keda/src/main/java/com/ankurm/keda/OrderListener.java new file mode 100644 index 0000000..59533e2 --- /dev/null +++ b/keda/src/main/java/com/ankurm/keda/OrderListener.java @@ -0,0 +1,31 @@ +package com.ankurm.keda; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +/** + * One listener thread per pod ({@code spring.kafka.listener.concurrency=1}). + * Scale out by adding pods (KEDA), not by adding threads inside a pod: a pod and a thread both + * consume at most as many partitions as the topic has, so the two multiply the same ceiling. + */ +@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 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()); + } +} diff --git a/keda/src/main/java/com/ankurm/keda/Processed.java b/keda/src/main/java/com/ankurm/keda/Processed.java new file mode 100644 index 0000000..c96d122 --- /dev/null +++ b/keda/src/main/java/com/ankurm/keda/Processed.java @@ -0,0 +1,35 @@ +package com.ankurm.keda; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import org.springframework.stereotype.Component; + +/** + * Remembers how many times each record (topic-partition@offset) has been processed. + * Kafka consumers are at-least-once: when a pod dies or is scaled down mid-batch, another pod + * re-reads the uncommitted tail. This counter is how the experiments make that visible. + */ +@Component +public class Processed { + + private final Map deliveries = new ConcurrentHashMap<>(); + + public int record(String topic, int partition, long offset) { + return deliveries.computeIfAbsent(topic + "-" + partition + "@" + offset, k -> new AtomicInteger()) + .incrementAndGet(); + } + + public int distinct() { + return deliveries.size(); + } + + public int total() { + return deliveries.values().stream().mapToInt(AtomicInteger::get).sum(); + } + + public long duplicates() { + return deliveries.values().stream().filter(c -> c.get() > 1).count(); + } +} diff --git a/keda/src/main/resources/application.yml b/keda/src/main/resources/application.yml new file mode 100644 index 0000000..68858c1 --- /dev/null +++ b/keda/src/main/resources/application.yml @@ -0,0 +1,41 @@ +# 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 diff --git a/keda/src/test/java/com/ankurm/keda/CrashableConsumer.java b/keda/src/test/java/com/ankurm/keda/CrashableConsumer.java new file mode 100644 index 0000000..bebb7a0 --- /dev/null +++ b/keda/src/test/java/com/ankurm/keda/CrashableConsumer.java @@ -0,0 +1,68 @@ +package com.ankurm.keda; + +import java.time.Duration; +import java.util.List; +import java.util.Properties; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +/** + * Runs in a child JVM so the test can really SIGTERM or SIGKILL it, like Kubernetes does. + * + *

Processes records one at a time (50 ms each), commits after every batch of 20, and prints + * {@code PROCESSED } for each record. On SIGTERM it stops between records and + * closes the consumer (which leaves the group); it does NOT commit the partial batch. + */ +public final class CrashableConsumer { + + private static volatile boolean stopping; + + public static void main(String[] args) throws Exception { + String bootstrap = args[0]; + String topic = args[1]; + String group = args[2]; + + Properties p = Kafka.consumerProps(bootstrap, group); + p.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "20"); + p.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "6000"); // broker minimum is 6000 + p.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "1000"); + + KafkaConsumer consumer = new KafkaConsumer<>(p); + Thread main = Thread.currentThread(); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + stopping = true; + try { + main.join(10_000); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + })); + + consumer.subscribe(List.of(topic)); + try { + while (!stopping) { + ConsumerRecords batch = consumer.poll(Duration.ofMillis(200)); + for (ConsumerRecord r : batch) { + if (stopping) { + break; + } + Thread.sleep(50); + System.out.println("PROCESSED " + r.offset()); + System.out.flush(); + } + if (!stopping && !batch.isEmpty()) { + consumer.commitSync(); + System.out.println("COMMITTED"); + System.out.flush(); + } + } + System.out.println("SIGTERM: stopped between records, closing consumer (leaves the group)"); + System.out.flush(); + } finally { + consumer.close(); + } + } +} diff --git a/keda/src/test/java/com/ankurm/keda/GroupMember.java b/keda/src/test/java/com/ankurm/keda/GroupMember.java new file mode 100644 index 0000000..f4ed260 --- /dev/null +++ b/keda/src/test/java/com/ankurm/keda/GroupMember.java @@ -0,0 +1,77 @@ +package com.ankurm.keda; + +import java.util.Collection; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.errors.WakeupException; + +/** One consumer-group member running in its own thread: a stand-in for one pod. */ +final class GroupMember implements AutoCloseable { + + final String name; + final Set assigned = new ConcurrentSkipListSet<>(); + final AtomicInteger revokedPartitions = new AtomicInteger(); + final AtomicInteger assignmentChanges = new AtomicInteger(); + volatile long lastChangeNanos = System.nanoTime(); + private final KafkaConsumer consumer; + private final Thread thread; + private volatile boolean running = true; + + GroupMember(String name, String topic, Properties props) { + this.name = name; + this.consumer = new KafkaConsumer<>(props); + this.thread = new Thread(() -> { + try { + consumer.subscribe(java.util.List.of(topic), new ConsumerRebalanceListener() { + @Override + public void onPartitionsRevoked(Collection parts) { + parts.forEach(tp -> assigned.remove(tp.partition())); + lastChangeNanos = System.nanoTime(); + revokedPartitions.addAndGet(parts.size()); + if (!parts.isEmpty()) { + assignmentChanges.incrementAndGet(); + } + } + + @Override + public void onPartitionsAssigned(Collection parts) { + parts.forEach(tp -> assigned.add(tp.partition())); + if (!parts.isEmpty()) { + lastChangeNanos = System.nanoTime(); + } + if (!parts.isEmpty()) { + assignmentChanges.incrementAndGet(); + } + } + }); + while (running) { + consumer.poll(Kafka.ms(100)); + } + } catch (WakeupException ignored) { + // normal shutdown path + } finally { + consumer.close(); + } + }, "member-" + name); + this.thread.setDaemon(true); + this.thread.start(); + } + + Set partitions() { + return new TreeSet<>(assigned); + } + + @Override + public void close() throws InterruptedException { + running = false; + consumer.wakeup(); + thread.join(15_000); + } +} diff --git a/keda/src/test/java/com/ankurm/keda/Kafka.java b/keda/src/test/java/com/ankurm/keda/Kafka.java new file mode 100644 index 0000000..a9a5189 --- /dev/null +++ b/keda/src/test/java/com/ankurm/keda/Kafka.java @@ -0,0 +1,77 @@ +package com.ankurm.keda; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ExecutionException; + +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; + +/** Small helpers shared by the experiments. */ +final class Kafka { + + private Kafka() { + } + + static void createTopic(String bootstrap, String topic, int partitions) throws Exception { + Properties p = new Properties(); + p.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap); + try (Admin admin = Admin.create(p)) { + admin.createTopics(List.of(new NewTopic(topic, partitions, (short) 1))).all().get(); + } + } + + /** Sends {@code count} records to one partition and waits for the acks. */ + static void produce(String bootstrap, String topic, int partition, int count) { + Properties p = new Properties(); + p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap); + p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + try (KafkaProducer producer = new KafkaProducer<>(p)) { + for (int i = 0; i < count; i++) { + producer.send(new ProducerRecord<>(topic, partition, "k" + i, "v" + i)); + } + producer.flush(); + } + } + + /** Creates a group whose committed offset is 0 on every partition: "exists, has read nothing". */ + static void commitZero(String bootstrap, String group, String topic, int partitions) + throws ExecutionException, InterruptedException { + Properties p = new Properties(); + p.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap); + try (Admin admin = Admin.create(p)) { + Map zero = new java.util.HashMap<>(); + for (int i = 0; i < partitions; i++) { + zero.put(new TopicPartition(topic, i), new OffsetAndMetadata(0)); + } + admin.alterConsumerGroupOffsets(group, zero).all().get(); + } + } + + static Properties consumerProps(String bootstrap, String group) { + Properties p = new Properties(); + p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap); + p.put(ConsumerConfig.GROUP_ID_CONFIG, group); + p.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); + p.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + p.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + p.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + return p; + } + + static Duration ms(long v) { + return Duration.ofMillis(v); + } +} diff --git a/keda/src/test/java/com/ankurm/keda/KedaExperimentsTest.java b/keda/src/test/java/com/ankurm/keda/KedaExperimentsTest.java new file mode 100644 index 0000000..3fe7ede --- /dev/null +++ b/keda/src/test/java/com/ankurm/keda/KedaExperimentsTest.java @@ -0,0 +1,436 @@ +package com.ankurm.keda; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.kafka.test.EmbeddedKafkaKraftBroker; + +/** + * The experiments behind the post. Each test prints a transcript to {@code output/NN-*.txt} and + * asserts the same facts, so the numbers quoted in the article are checked on every build. + * A real (embedded, KRaft) Kafka broker is used; Kubernetes and KEDA are NOT involved. + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class KedaExperimentsTest { + + static EmbeddedKafkaKraftBroker broker; + static String bootstrap; + + @BeforeAll + static void startBroker() { + broker = new EmbeddedKafkaKraftBroker(1, 1); + broker.afterPropertiesSet(); + bootstrap = broker.getBrokersAsString(); + } + + @AfterAll + static void stopBroker() { + broker.destroy(); + } + + // ------------------------------------------------------------------ 01 + + @Test + @Order(1) + void partitionsCapParallelism() throws Exception { + Transcript t = new Transcript("01-partition-cap"); + t.line("Topic 'cap' has 6 partitions. N consumers join one group; who gets what?"); + Kafka.createTopic(bootstrap, "cap", 6); + + for (int n : new int[] {1, 3, 6, 8}) { + String group = "cap-" + n; + List members = new ArrayList<>(); + for (int i = 1; i <= n; i++) { + members.add(new GroupMember("c" + i, "cap", Kafka.consumerProps(bootstrap, group))); + } + settle(members, 6, group); + t.line(""); + t.line("N=%d consumers:", n); + int idle = 0; + for (GroupMember m : members) { + t.line(" %s -> partitions %s", m.name, m.partitions()); + if (m.partitions().isEmpty()) { + idle++; + } + } + t.line(" idle consumers: %d", idle); + assertThat(idle).isEqualTo(Math.max(0, n - 6)); + for (GroupMember m : members) { + m.close(); + } + } + t.write(); + } + + // ------------------------------------------------------------------ 02 + + @Test + @Order(2) + void lagBecomesReplicas() throws Exception { + Transcript t = new Transcript("02-lag-to-replicas"); + t.line("Lag is read from the broker (log end offset - committed offset, summed)."); + t.line("Replica counts come from KedaMath, a model of the scaler + HPA (KEDA is not run here)."); + + KedaMath.Config def = new KedaMath.Config(100, 0, 0, 100, false, false); + + // uniform: 100 per partition + Kafka.createTopic(bootstrap, "lag-uniform", 6); + Kafka.commitZero(bootstrap, "g-uniform", "lag-uniform", 6); + for (int p = 0; p < 6; p++) { + Kafka.produce(bootstrap, "lag-uniform", p, 100); + } + Map uniform = GroupLag.perPartition(bootstrap, "g-uniform"); + t.line(""); + t.line("A) uniform: %s", show(uniform)); + KedaMath.Decision a1 = KedaMath.decide(uniform, 6, def); + t.line(" lagThreshold=100 -> total=%d metric=%d desired=%d", + a1.totalLag(), a1.reportedMetric(), a1.desired()); + KedaMath.Decision a2 = KedaMath.decide(uniform, 6, new KedaMath.Config(50, 0, 0, 100, false, false)); + t.line(" lagThreshold=50 (wants 12, 6 partitions) -> total=%d metric=%d desired=%d", + a2.totalLag(), a2.reportedMetric(), a2.desired()); + KedaMath.Decision a3 = KedaMath.decide(uniform, 6, new KedaMath.Config(50, 0, 0, 100, true, false)); + t.line(" same, allowIdleConsumers=true -> total=%d metric=%d desired=%d", + a3.totalLag(), a3.reportedMetric(), a3.desired()); + assertThat(a1.totalLag()).isEqualTo(600); + assertThat(a1.desired()).isEqualTo(6); + assertThat(a2.desired()).isEqualTo(6); + assertThat(a3.desired()).isEqualTo(12); + + // skewed: all 600 on partition 0 + Kafka.createTopic(bootstrap, "lag-skew", 6); + Kafka.commitZero(bootstrap, "g-skew", "lag-skew", 6); + Kafka.produce(bootstrap, "lag-skew", 0, 600); + Map skew = GroupLag.perPartition(bootstrap, "g-skew"); + t.line(""); + t.line("B) skewed (hot key): %s", show(skew)); + KedaMath.Decision b1 = KedaMath.decide(skew, 6, def); + t.line(" default -> total=%d desired=%d (5 of 6 pods would sit idle)", + b1.totalLag(), b1.desired()); + KedaMath.Decision b2 = KedaMath.decide(skew, 6, new KedaMath.Config(100, 0, 0, 100, false, true)); + t.line(" limitToPartitionsWithLag=true -> total=%d desired=%d", b2.totalLag(), b2.desired()); + assertThat(b1.desired()).isEqualTo(6); + assertThat(b2.desired()).isEqualTo(1); + + // remainder quirk: 650 on 6 partitions + Kafka.createTopic(bootstrap, "lag-remainder", 6); + Kafka.commitZero(bootstrap, "g-remainder", "lag-remainder", 6); + for (int p = 0; p < 6; p++) { + Kafka.produce(bootstrap, "lag-remainder", p, p == 0 ? 150 : 100); + } + Map rem = GroupLag.perPartition(bootstrap, "g-remainder"); + KedaMath.Decision c = KedaMath.decide(rem, 6, def); + t.line(""); + t.line("C) remainder edge: %s", show(rem)); + t.line(" 650 / 100 = 6 (integer) is not > 6, so the clamp is skipped -> metric=%d desired=%d on 6 partitions", + c.reportedMetric(), c.desired()); + assertThat(c.desired()).isEqualTo(7); + + // activation and scale to zero + Kafka.createTopic(bootstrap, "lag-idle", 6); + Kafka.commitZero(bootstrap, "g-idle", "lag-idle", 6); + Map idle = GroupLag.perPartition(bootstrap, "g-idle"); + KedaMath.Decision d0 = KedaMath.decide(idle, 6, def); + Kafka.produce(bootstrap, "lag-idle", 3, 1); + KedaMath.Decision d1 = KedaMath.decide(GroupLag.perPartition(bootstrap, "g-idle"), 6, def); + t.line(""); + t.line("D) activation (minReplicaCount=0, activationLagThreshold=0):"); + t.line(" lag=0 -> active=%s desired=%d; lag=1 -> active=%s desired=%d", + d0.active(), d0.desired(), d1.active(), d1.desired()); + assertThat(d0.desired()).isZero(); + assertThat(d1.desired()).isEqualTo(1); + t.write(); + } + + // ------------------------------------------------------------------ 03 + + @Test + @Order(3) + void rebalanceCostOfScalingOut() throws Exception { + Transcript t = new Transcript("03-rebalance-cost"); + t.line("1 pod owns 6 partitions; KEDA adds 2 pods. How many partitions does pod 1 give up?"); + Kafka.createTopic(bootstrap, "rebalance", 6); + + Map revokedByA = new HashMap<>(); + Map modes = new java.util.LinkedHashMap<>(); + modes.put("classic + RangeAssignor (eager)", "range"); + modes.put("classic + CooperativeStickyAssignor", "coop"); + modes.put("group.protocol=consumer (KIP-848)", "consumer"); + + for (Map.Entry mode : modes.entrySet()) { + String group = "rb-" + mode.getValue(); + Properties p = Kafka.consumerProps(bootstrap, group); + switch (mode.getValue()) { + case "range" -> p.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, + "org.apache.kafka.clients.consumer.RangeAssignor"); + case "coop" -> p.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, + "org.apache.kafka.clients.consumer.CooperativeStickyAssignor"); + default -> p.put(ConsumerConfig.GROUP_PROTOCOL_CONFIG, "consumer"); + } + GroupMember a = new GroupMember("A", "rebalance", p); + settle(List.of(a), 6, group); + int before = a.revokedPartitions.get(); + long joinAt = System.nanoTime(); + GroupMember b = new GroupMember("B", "rebalance", p); + GroupMember c = new GroupMember("C", "rebalance", p); + List all = List.of(a, b, c); + settle(all, 6, group); + int revoked = a.revokedPartitions.get() - before; + long ms = Duration.ofNanos(Math.max(a.lastChangeNanos, Math.max(b.lastChangeNanos, c.lastChangeNanos)) + - joinAt).toMillis(); + t.line(""); + t.line("%s", mode.getKey()); + t.line(" final: A=%s B=%s C=%s", a.partitions(), b.partitions(), c.partitions()); + t.line(" partitions A had to give up: %d of 6; time until last assignment change: ~%d ms", revoked, ms); + revokedByA.put(mode.getValue(), revoked); + assertThat(a.partitions()).hasSize(2); + assertThat(b.partitions()).hasSize(2); + assertThat(c.partitions()).hasSize(2); + for (GroupMember m : all) { + m.close(); + } + } + assertThat(revokedByA.get("range")).isEqualTo(6); + assertThat(revokedByA.get("coop")).isLessThan(6); + t.line(""); + t.line("Timing varies per run; the revoked-partition counts are what the test asserts."); + t.write(); + } + + // ------------------------------------------------------------------ 04 + + @Test + @Order(4) + void sigtermVersusSigkill() throws Exception { + Transcript t = new Transcript("04-sigterm-vs-sigkill"); + t.line("A consumer JVM processes records (50 ms each) and commits every 20. We stop it after it has"); + t.line("processed 30 records (20 committed + 10 in flight). A standby consumer is already in the group."); + t.line("session.timeout.ms=6000 (the broker's minimum)."); + + Map results = new java.util.LinkedHashMap<>(); + for (boolean kill : new boolean[] {false, true}) { + String topic = kill ? "stop-sigkill" : "stop-sigterm"; + String group = "g-" + topic; + Kafka.createTopic(bootstrap, topic, 1); + Kafka.produce(bootstrap, topic, 0, 100); + + Process child = new ProcessBuilder( + Path_java(), "-cp", System.getProperty("java.class.path"), + CrashableConsumer.class.getName(), bootstrap, topic, group) + .redirectErrorStream(true).start(); + AtomicInteger processed = new AtomicInteger(); + AtomicInteger committed = new AtomicInteger(); + Thread reader = new Thread(() -> { + try (BufferedReader r = new BufferedReader(new InputStreamReader(child.getInputStream()))) { + String line; + while ((line = r.readLine()) != null) { + if (line.startsWith("PROCESSED")) { + processed.incrementAndGet(); + } else if (line.startsWith("COMMITTED")) { + committed.set(processed.get()); + } + } + } catch (java.io.IOException ignored) { + // child went away + } + }); + reader.setDaemon(true); + reader.start(); + + // wait until the child is working, then bring the standby into the group + waitFor(() -> committed.get() >= 20, 60_000); + Properties sp = Kafka.consumerProps(bootstrap, group); + sp.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "6000"); + sp.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "1000"); + sp.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "20"); + AtomicLong firstOffset = new AtomicLong(-1); + AtomicLong firstAt = new AtomicLong(); + try (KafkaConsumer standby = new KafkaConsumer<>(sp)) { + standby.subscribe(List.of(topic)); + standby.poll(Duration.ofMillis(500)); // join; the child still owns the partition + + waitFor(() -> processed.get() >= 30, 60_000); + int processedAtStop = processed.get(); + int committedAtStop = committed.get(); + long stopAt = System.nanoTime(); + if (kill) { + child.destroyForcibly(); // SIGKILL: no shutdown hook, no goodbye to the broker + } else { + child.destroy(); // SIGTERM: the JVM runs the shutdown hook, the consumer leaves the group + } + long deadline = System.nanoTime() + Duration.ofSeconds(40).toNanos(); + while (firstOffset.get() < 0 && System.nanoTime() < deadline) { + ConsumerRecords recs = standby.poll(Duration.ofMillis(100)); + if (!recs.isEmpty()) { + firstOffset.set(recs.iterator().next().offset()); + firstAt.set(System.nanoTime()); + } + } + child.waitFor(); + reader.join(2_000); + long takeoverMs = Duration.ofNanos(firstAt.get() - stopAt).toMillis(); + long redone = processed.get() - firstOffset.get(); + t.line(""); + t.line("%s:", kill ? "SIGKILL (pod crash, node loss)" : "SIGTERM (what Kubernetes sends on scale-down)"); + t.line(" child had processed %d, committed %d at the moment of the signal", processedAtStop, committedAtStop); + t.line(" standby's first record: offset %d after %d ms", firstOffset.get(), takeoverMs); + t.line(" records processed twice (child processed %d, standby restarted at %d): %d", + processed.get(), firstOffset.get(), redone); + results.put(kill ? "kill" : "term", new long[] {takeoverMs, firstOffset.get(), redone}); + } + } + assertThat(results.get("term")[1]).isEqualTo(20); // restarted from the last commit, not from 30 + assertThat(results.get("kill")[1]).isEqualTo(20); + assertThat(results.get("term")[2]).isGreaterThanOrEqualTo(10); + assertThat(results.get("kill")[0]).isGreaterThan(results.get("term")[0]); + assertThat(results.get("kill")[0]).isGreaterThan(2_000); + t.line(""); + t.line("Both replay the uncommitted tail (at-least-once). Only SIGKILL also waits out session.timeout.ms."); + t.write(); + } + + // ------------------------------------------------------------------ 05 + + @Test + @Order(5) + void springContainerFinishesTheBatchOnShutdown() throws Exception { + Transcript t = new Transcript("05-spring-graceful-shutdown"); + t.line("The real Spring Boot app (OrderListener, 50 ms of work per record, max.poll.records=20)."); + t.line("200 records on one partition. Close the context after >= 25 records were processed."); + Kafka.createTopic(bootstrap, "orders-spring", 1); + Kafka.produce(bootstrap, "orders-spring", 0, 200); + + ConfigurableApplicationContext a = appContext("spring-graceful"); + Processed pa = a.getBean(Processed.class); + waitFor(() -> pa.total() >= 25, 60_000); + long t0 = System.nanoTime(); + a.close(); + long closeMs = Duration.ofNanos(System.nanoTime() - t0).toMillis(); + int processedA = pa.total(); + long committed = 200 - GroupLag.total(GroupLag.perPartition(bootstrap, "spring-graceful")); + t.line(""); + t.line("pod A: context.close() took ~%d ms; processed=%d; committed offset=%d", closeMs, processedA, committed); + + ConfigurableApplicationContext b = appContext("spring-graceful"); + Processed pb = b.getBean(Processed.class); + waitFor(() -> GroupLag.total(lagOrEmpty("spring-graceful")) == 0, 60_000); + int processedB = pb.total(); + b.close(); + long redelivered = (long) processedA + processedB - 200; + t.line("pod B (same group): processed=%d until lag=0", processedB); + t.line("records processed twice across A and B: %d", redelivered); + assertThat(committed).isEqualTo(processedA); + assertThat(redelivered).isZero(); + t.line(""); + t.line("Spring's container finished the in-flight batch and committed it before stopping."); + t.write(); + } + + // ------------------------------------------------------------------ helpers + + private static ConfigurableApplicationContext appContext(String group) { + // command-line arguments, not .properties(): the latter are lowest-priority defaults and + // application.yml would silently win (this cost one wasted run while writing the module) + return new SpringApplicationBuilder(KedaConsumerApplication.class) + .web(WebApplicationType.NONE) + .run( + "--spring.kafka.bootstrap-servers=" + bootstrap, + "--spring.kafka.consumer.group-id=" + group, + "--spring.kafka.consumer.max-poll-records=20", + "--app.topic=orders-spring", + "--app.work-ms=50", + "--logging.level.root=WARN"); + } + + private static Map lagOrEmpty(String group) { + try { + return GroupLag.perPartition(bootstrap, group); + } catch (Exception e) { + return Map.of(new TopicPartition("x", 0), Long.MAX_VALUE / 4); + } + } + + private static String Path_java() { + return Path_of(System.getProperty("java.home"), "bin", "java"); + } + + private static String Path_of(String first, String... more) { + return java.nio.file.Path.of(first, more).toString(); + } + + private static String show(Map lag) { + Map sorted = new java.util.TreeMap<>(); + lag.forEach((tp, l) -> sorted.put(tp.partition(), l)); + return sorted + " total=" + GroupLag.total(lag); + } + + /** Waits until every member has joined, all partitions are assigned and nothing has moved for 2 seconds. */ + private static void settle(List members, int partitions, String group) throws Exception { + long deadline = System.nanoTime() + Duration.ofSeconds(60).toNanos(); + long stableSince = 0; + String last = ""; + while (System.nanoTime() < deadline) { + int total = members.stream().mapToInt(m -> m.assigned.size()).sum(); + String snap = members.stream().map(m -> new TreeSet<>(m.assigned).toString()).reduce("", String::concat); + int floor = partitions / members.size(); + // with more members than partitions, "served" means every partition has its own member + boolean everyoneServed = members.size() <= partitions + ? members.stream().allMatch(m -> m.assigned.size() >= floor) + : members.stream().filter(m -> !m.assigned.isEmpty()).count() == partitions; + if (total == partitions && everyoneServed && memberCount(group) == members.size() && snap.equals(last)) { + if (stableSince == 0) { + stableSince = System.nanoTime(); + } else if (System.nanoTime() - stableSince > Duration.ofSeconds(2).toNanos()) { + return; + } + } else { + stableSince = 0; + } + last = snap; + Thread.sleep(200); + } + throw new IllegalStateException("group did not settle"); + } + + /** How many members the broker's group coordinator currently lists for the group. */ + private static int memberCount(String group) throws Exception { + Properties p = new Properties(); + p.put(org.apache.kafka.clients.admin.AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap); + try (org.apache.kafka.clients.admin.Admin admin = org.apache.kafka.clients.admin.Admin.create(p)) { + return admin.describeConsumerGroups(List.of(group)).describedGroups().get(group).get().members().size(); + } + } + + private static void waitFor(java.util.function.BooleanSupplier cond, long timeoutMs) throws InterruptedException { + long deadline = System.currentTimeMillis() + timeoutMs; + while (!cond.getAsBoolean()) { + if (System.currentTimeMillis() > deadline) { + throw new IllegalStateException("timed out"); + } + Thread.sleep(50); + } + } +} diff --git a/keda/src/test/java/com/ankurm/keda/Transcript.java b/keda/src/test/java/com/ankurm/keda/Transcript.java new file mode 100644 index 0000000..51ea2ff --- /dev/null +++ b/keda/src/test/java/com/ankurm/keda/Transcript.java @@ -0,0 +1,33 @@ +package com.ankurm.keda; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * Collects lines and writes them to {@code output/NN-name.txt}. The tests assert the same numbers + * they print, so every figure quoted in the post is also a failing build if it stops being true. + */ +final class Transcript { + + private final Path file; + private final List lines = new ArrayList<>(); + + Transcript(String name) { + this.file = Path.of("output", name + ".txt"); + } + + Transcript line(String format, Object... args) { + String s = args.length == 0 ? format : String.format(format, args); + lines.add(s); + System.out.println("[transcript] " + s); + return this; + } + + void write() throws IOException { + Files.createDirectories(file.getParent()); + Files.write(file, lines); + } +}